diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 34a02f2b73..d914f579e2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -978,13 +978,23 @@ jobs: account-service - name: πŸ”Ž Verify Account committed connect source readback proof - if: ${{ matrix.module == 'account-service' }} + if: ${{ !cancelled() && matrix.module == 'account-service' }} run: | bash dev-tools/validation/inspect-test-results.sh \ --strict \ --require-suite integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#readsExactCommittedOriginalSourceAndLostResultWithoutMutation()' \ --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#readsExpiredCommittedSourceOnlyThroughHistoricalEvidenceWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#historicalReadRejectsRequestTargetHashAndTokenIdentityMismatches()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#historicalReadRequiresCommittedSuccess()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#historicalReadRequiresRegisteredGatewayAndAccountSigningKeys()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#readsCommittedStoredFrameAndOriginalSourceAfterGatewayContextExpiryWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#storedHistoryRejectsChangedDigestSourceContextResultHashAndKey()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#correlatesExpiredOriginalFrameWithSeparateFreshCommittedSourceWithoutMutation()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#correlationRejectsExpiredFreshContextAndReissuedContextForOriginalSource()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#correlationRequiresExactAccountTenantAndCompleteSelectedTarget()' \ + --require-case 'integration.net.firedevops.firemud.accountservice.AccountCommittedConnectSourceReaderIntegrationTest#correlationRechecksFreshDeadlineAfterStoredFrameReadWait()' \ account-service - name: Verify Account fresh tenant association PostgreSQL proof diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 2cc11d468e..b22cb7bf95 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -60,7 +60,7 @@ The hosted Creator Party, terms catalog, acceptance/currentness evidence, and ch The current credential-granting `Authenticate`, `RequestEmailLoginOtp`, and `VerifyEmailLoginOtp` gRPC handlers require the exact authenticated Game Session mTLS peer before credential or challenge work; the shared public-method list still bypasses bearer validation for these methods, so the peer guard is required and is not a JWT fallback. Legacy profile GET/PUT now require the exact Social Groups peer and a non-internal caller subject matching the requested account; presence-policy batch reads require the exact Social Groups peer and read only tenant-scoped profiles. The account-ID export, external-link, and verification gRPC handlers deny before data access or mutation because no authorized caller contract exists. Runtime membership, grant, and entitlement methods deny before Account reads until typed player/target binding is available; these local guards are not complete admission proof. `GetBalance`, `AddCurrency`, and `SpendCurrency` now return `FAILED_PRECONDITION` before balance access or mutation because virtual currency is a deferred substrate, not a supported v1 API. -Fresh-tenant identity adds no public Account endpoint or membership shortcut. The selected #2915 consumer uses Account's authenticated normal workload to read exact Game Design creation evidence, then commits an immutable canonical-UUID association and shared UUID conflict claim before using the existing no-reset tenant-generation initialization; it neither infers a retained numeric key nor admits a player. This local implementation is in progress, with no exact Account-consumer proof. In [CI run 36791561008](https://github.com/benhook1013/FireMUD/actions/runs/36791561008), the strict seven-case Game Design producer/readback database suite executed and all seven failed because the migrated test schema did not expose the expected relations; the proposed schema-selection correction has not been rerun. The Game Design wire and digest remain owned by its [API contract](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback), and Account's local storage/readback consequence is described in [Runtime & Data](./runtime-and-data.md). The membership RPC remains denied. +Fresh-tenant identity adds no public Account endpoint or membership shortcut. The #2915 consumer uses Account's authenticated normal workload to read exact Game Design creation evidence, then commits an immutable canonical-UUID association and shared UUID conflict claim before using the existing no-reset tenant-generation initialization; it neither infers a retained numeric key nor admits a player. Exact #2915 head `910d0a6f41d60ee7214b610d56f89c51db260413` [CI 36796087279](https://github.com/benhook1013/FireMUD/actions/runs/36796087279) executed and passed all six Account fresh-association and seven Game Design creation PostgreSQL cases without skips, including retry, concurrency and rollback. This corrected component proof supersedes the earlier schema-fixture failure; it does not prove deployed workload identity, a live cross-owner handoff or activation. Detailed proof and remaining gates belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). The Game Design wire and digest remain owned by its [API contract](../game-design-service/api-contracts.md#fresh-tenant-creation-operation-and-account-readback), and Account's local storage/readback consequence is described in [Runtime & Data](./runtime-and-data.md). The membership RPC remains denied. `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fa8d46a4a2..eb21f14790 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -158,7 +158,7 @@ The `player-bootstrap` token profile is distinct from both `control-ui` and priv - It establishes account identity for first-party gameplay bootstrap only. Target behavior is that public-game membership is created only by explicit `/auth/bootstrap/join`; character discovery, character creation, and `POST /auth/connect-token` later require that membership and recheck applicable grants, entitlements, and the discovery-selected runtime target. The current Account REST runtime requires existing caller-bound membership for character discovery and connect-token issuance and uses only `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`; world and realm discovery remain available before membership. Non-public REST realm discovery, character listing, and connect-token issuance fail closed even when a legacy four-field grant row exists, because it cannot prove the current lifecycle and state generation; public-production behavior remains unchanged. The separate Game Session text `PLAY` path is currently blocked earlier by Account runtime membership/grant/entitlement gRPC methods returning `FAILED_PRECONDITION` before reads, producing `AUTH_UNAVAILABLE`; its downstream membership outcomes require successful mocked Account responses. For a publicly visible public-production target whose joining policy permits entry, the Account connect-token issuance branch may return `JOIN_REQUIRED` without creating or restoring membership; the latter existing-membership case is not lifecycle-aware while explicit `JOIN` is a separate local action. The target lifecycle-qualified grant authority is not implemented. - It is stored in memory only by first-party gameplay UIs and is accepted only on gameplay-bootstrap surfaces such as bootstrap discovery and `POST /auth/connect-token`. - For first-party `/ws/game/**`, subsequent gameplay `LOGIN` must complete from the bootstrap/connect context already established for that socket; browser clients must not be required to replay account credentials after bootstrap. -- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The V37 storage candidate binds an exchange to a committed V35 connect operation and stores an immutable purpose-bound terminal envelope, but neither operation is wired to credential issuance or recovery. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish the complete proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. +- Account issues the private `game-session-account-delegation` JWT for bare first-party `LOGIN` only through the one-use, idempotent exchange defined in [Authentication and Authorization](../../system-architecture-authentication.md). Its own committed connect issuance and bootstrap subject, independently verified Gateway-signed context, exact Game Session mTLS identity, target binding, current authority, and issuance fence must all agree before issuance. The V37 storage candidate binds an exchange to a committed V35 connect operation and stores an immutable purpose-bound terminal envelope, but neither operation is wired to credential issuance or recovery. The selected expired-context terminal-recovery contract is owned by [Authentication](../../system-architecture-authentication.md#terminal-bare-login-result-recovery-normative); it is unimplemented and unproved. The current Redis-only connect replay/session records and Gateway context verifier configuration do not establish the complete proof, so no current bare-`LOGIN` exchange or live runtime-read authorization is claimed. - If the token is lost because the page/app process is restarted, the client must restart bootstrap from `POST /auth/player-bootstrap`; the current architecture does not define a hidden silent-bootstrap refresh mechanism. - It is backed by one `session:auth:token:` record so per-token logout and account-level revocation semantics remain consistent. - `POST /auth/logout` and `POST /auth/logout-all` must accept this profile so first-party gameplay UIs can explicitly revoke bootstrap capability on sign-out rather than waiting for expiry. @@ -243,6 +243,10 @@ Account owns one versioned, mounted-secret key ring and rotation procedure for b The operation identity is claimed by a serializable transaction or equivalent Account-owned CAS: one matching digest wins, a concurrent matching request waits for and reads the same operation, and any changed digest returns `IDEMPOTENCY_CONFLICT` without minting or mutating. Account records the durable operation before exposing a result, accepts and reads back the required registry/admission postconditions before `COMMITTED`, and exact retries revalidate current authority and all applicable registry/admission postconditions before decrypting and returning a successful credential envelope. If that revalidation fails, the retry returns the applicable canonical denial and leaves the committed operation and envelope unchanged; it does not remint or replace the credential. A deterministic `FAILED` result, such as `JOIN_REQUIRED`, replays its stored failure envelope directly after the exact operation identity and digest match, without rerunning authority or membership checks, while that failure envelope remains retained. If the matching compact receipt remains after its response envelope has been removed at the declared response-recovery horizon, an exact digest match returns `RESPONSE_RECOVERY_EXPIRED`; a changed digest still returns `IDEMPOTENCY_CONFLICT`. That outcome is terminal for the original issuance attempt and callers must use a new `requestId` for a fresh authorized request. Missing, ambiguous, or unreconciled durable state fails closed; no retry reconstructs or silently remints a JWT. The response envelope must not be removed while the operation is pending, ambiguous, or otherwise blocked on reconciliation. This target persistence/CAS/readback path is unimplemented and must not be inferred from the current Redis map. +For the Authentication-owned [terminal bare-`LOGIN` result-recovery exception](../../system-architecture-authentication.md#terminal-bare-login-result-recovery-normative), Account retains the original signed Gateway context bytes encrypted with the exact original result under the existing `BARE_LOGIN_RESPONSE` purpose and unchanged operation binding. The operation row stores no raw JWT or context bytes. Its local `BareLoginRecoveryPayload` uses one closed versioned, byte-length-framed representation within the existing envelope plaintext bound; it preserves context and opaque result bytes without normalization and introduces no additional key purpose. Envelope reads must verify the exact committed operation, request/source/context evidence, purpose and key before decoding. The shared history-only Gateway evidence type is distinct from current authorization and never substitutes into a current-context API. Original result expiry and a separately declared recovery horizon remain mandatory Account checks; neither is inferred from `created_at` or extended. The complete fresh-proof, authority and postcondition requirements remain at Authentication's owner. The unwired Account source reader has separate strict-current and history-only methods: the latter checks an exact committed V35 source against the supplied signed historical Gateway assertion and returns immutable, non-authorizing evidence. It does not establish that V37 retained that assertion or that Gateway accepted it. The actual V37 producer does not yet persist the frame, and current-authority/registry/recovery composition and complete canonical-UUID request wiring remain open in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). No fixed TTL, new public route or runtime enablement is selected. + +The unwired `AccountStoredBareLoginRecoveryReader` reads an exact committed V37 operation and purpose-bound encrypted frame under the Account fence, verifies the opaque result hash and stored signed context against its exact committed V35 source, and returns only immutable, redacted provenance facts. Its separate correlation read first verifies a distinct strict-current committed connect source and signed Gateway context, then exact-compares the original and fresh canonical player, tenant and complete selected target, including conditional lifecycle/generation. A final unchanged strict-source read rechecks deadlines after historical work; original/fresh operation identities, requests, scope hashes and timestamps remain separate evidence rather than being rewritten. Stored historical Gateway expiry is the signed context's `expiresAt`, not the source token's potentially later `exp`. This is non-authorizing correspondence only: it does not return the context or result, establish past Gateway acceptance, verify the original result JWT/expiry or recovery horizon, compare the producer's complete context/authority/postcondition evidence, or authorize recovery. Detailed component proof and the remaining producer/composition gates are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md). + The target projection is physically isolated from the legacy map: `session:connect-token:v1:tenant::account::scope::request:` is target-only, while the unversioned family remains legacy-only. Because the legacy writer has no issuance fence, cutover requires closing issuance for the full Account cohort, stopping legacy writers, draining in-flight requests, waiting the configured maximum legacy TTL/retry horizon, and verifying that no legacy writer remains before enabling target issuance. A mixed-version rollout is not permitted unless every writer first honors a shared owner fence. Legacy entries are retained read-only through the TTL/retry horizon, then Account performs owner cleanup from an exact inventory with readback; they are not migrated, promoted, or interpreted as target envelopes. Region/tenant reset preservation follows the reset matrix for both families; after a cluster/cold-start loss, exact durable target repair/readback is required and otherwise the handshake fails closed. Under [ADR 0163](../../decisions/adr-0163-service-owned-retention-classes-with-cross-service-safety.md), the operation is an Account-owned **retry and idempotency receipt** class. `PENDING`, `ABORTED` with unresolved reconciliation, and any row with a live registry/admission/postcondition blocker are nonterminal and retained; `COMMITTED` and deterministic `FAILED` become eligible only after the complete supported client, producer, duplicate-delivery, reconnect, reset-recovery, and audit-read window ends. The minimum horizon is the greatest applicable connect-scope, response-envelope, client/internal retry, recovery, and legal/governance horizon, with no universal duration assumed. Account-owned bounded cleanup records holds and blocker reason, never deletes held or nonterminal rows, and removes the encrypted credential-bearing response envelope only after its declared response-recovery horizon while retaining the compact receipt through the deduplication horizon. A matching duplicate after envelope removal but before receipt expiry returns `RESPONSE_RECOVERY_EXPIRED`; exact digest comparison remains mandatory, changed input remains `IDEMPOTENCY_CONFLICT`, and no replacement credential is minted. A retained deterministic `FAILED` envelope continues to replay its exact failure; after that envelope is removed, the same recovery-expired outcome applies. Callers treat `RESPONSE_RECOVERY_EXPIRED` as terminal for the original issuance attempt and start a fresh authorized request under a new `requestId`. Cleanup never removes an envelope while the operation is pending, ambiguous, or blocked on unresolved reconciliation. Account exposes oldest-blocking-row and cleanup-lag metrics. Partition/drop or row deletion requires the same terminal, reference, hold, and safe-watermark checks as the shared retention contract. diff --git a/design/architecture/system-architecture-authentication.md b/design/architecture/system-architecture-authentication.md index 1b4ea65b2f..74c6f77e4b 100644 --- a/design/architecture/system-architecture-authentication.md +++ b/design/architecture/system-architecture-authentication.md @@ -61,7 +61,7 @@ For the closed `account-auth-authority-event/v1` membership event, `membershipVe - **JWT claim contract** – Services must validate a strict JWT claim profile (required claims and audience per token profile), not only signature plus ad-hoc fields. Registry-backed profiles carry the complete `authorityTuple` and positive `issuanceFence` with the exact nested names above. A field marked `Absent` by its profile is omitted, not encoded as an empty string, null, map, or list; an empty map/list is valid only when that profile declares the field present and its value is empty. `control-ui` must include `scopedRoles` as `{}` when empty; omission is rejected. Its `tenantAuthorityGeneration` keys equal the non-empty scoped-role tenant keys whose allowed routes require target-tenant authority, while its independent `membershipAuthorityGeneration` and `membershipVersion` keys equal the caller-membership tenants needed by the token's allowed route classifications, including a `billing_safe_tenant` key that deliberately has no target-tenant authority entry. Explicitly unscoped profiles use empty maps/lists only where their profile declares those fields present, never absent or fabricated scope values. - **Authority tuple comparison** – Every applicable `issuerAuthGeneration`, `accountAuthorityGeneration`, exact tenant and membership map entry, private-realm `grantVersion`, `accountSecurityCutoff`, and `tenantBillingCutoff` is compared as part of one tuple. `membershipVersion` is a separate current/stored membership projection check and is never substituted for `membershipAuthorityGeneration`; a tuple, cutoff, fence, or membership mismatch fails closed. - **Internal gameplay delegation boundary** – Gameplay services authenticate the concrete mTLS workload identity, enforce an exact method-level caller allowlist, and validate a typed `PlayerExecutionContext` against request and domain scope. -- **First-party bare `LOGIN` delegation** – A first-party WebSocket `LOGIN` without credentials may obtain the private `game-session-account-delegation` JWT only through an Account-owned, one-use, idempotent exchange. Account verifies its committed gameplay-connect issuance and bootstrap subject, the verified Gateway-signed connect context, the exact Game Session mTLS caller, the player/tenant/target binding, current authority, and the issuance fence before issuing. Gateway context or a connect-token `jti` alone is not Account authentication. Game Session never mints this JWT or returns it to a gameplay client; an exact retry recovers the same bounded exchange result, while changed binding or fence evidence fails closed. +- **First-party bare `LOGIN` delegation** – A first-party WebSocket `LOGIN` without credentials may obtain the private `game-session-account-delegation` JWT only through an Account-owned, one-use, idempotent exchange. Account verifies its committed gameplay-connect issuance and bootstrap subject, the verified Gateway-signed connect context, the exact Game Session mTLS caller, the player/tenant/target binding, current authority, and the issuance fence before issuing. Gateway context or a connect-token `jti` alone is not Account authentication. Game Session never mints this JWT or returns it to a gameplay client; exact terminal-result recovery after context expiry is governed by [Terminal bare-`LOGIN` result recovery](#terminal-bare-login-result-recovery-normative), and changed binding or fence evidence fails closed. - **No universal player attestation** – Routine gameplay delegation does not use signed per-action player attestations or a replay cache. Mutation replay is controlled by the owning command/effect/request idempotency contract. - **Route classification governance** – Protected routes must be classified in the shared route matrix document and enforced through middleware annotations/interceptors; behavior must not rely on per-service ad-hoc interpretation. - **Gameplay session ownership** – Game Session owns gameplay binding records, the atomic monotonic binding CAS, and bounded secondary indexes that map gameplay bindings by the target uniqueness key `{tenantId, playableStateNamespaceId, characterId}`, account/tenant scope, and tenant scope so takeover, reconnect, and revocation do not require scans. Server-derived `playableStateScope` and binding values/evidence retain `{sessionId, gameInstanceId, bindingGeneration}` as locally appropriate. Account owns the admission decision and exact-binding lease only; Account finalization commits lease/decision evidence and never creates, deletes, or mutates Game Session bindings or indexes. Orphan evidence from Account reconciliation becomes a durable cleanup request that Gateway and Game Session consume under their respective edge and gameplay fences. @@ -69,6 +69,12 @@ For the closed `account-auth-authority-event/v1` membership event, `membershipVe - **Ordinary gameplay authentication** – Each gameplay `LOGIN` uses one account-selected mode, either `PASSWORD` or verified `EMAIL_OTP`. Account configuration may expose both choices separately, but no combined password-plus-email-OTP request is part of the wire contract. Gameplay authentication does not perform active-gameplay reauthentication or elevate the gameplay session into account/control-plane authority; HTTPS step-up remains separate. - **Ingress identity validation** – Public and cross-service readers validate the declared shape of UUID-governed identifiers before authorization or lookup, then treat the values as opaque. Identifier contents never confer authority or determine tenant scope. +### Terminal bare-`LOGIN` result recovery (normative) + +After the original Gateway context expires, Account may return only the exact result of an already `COMMITTED` bare-`LOGIN` exchange, only while that original delegation result remains unexpired and its bounded response envelope is retained. This is a separate reauthorization for exact-result recovery, not a new `LOGIN` success path: the caller supplies a fresh Account-committed gameplay-connect issuance and its independently signed, currently valid Gateway context under the exact Game Session workload identity. Account binds that separate fresh proof to the explicitly requested original operation, request ID and digest; its committed-source reader verifies the fresh source/context pair and proves the same player, tenant, and complete Account-selected target as that original operation, including the applicable playtest lifecycle and generation. The fresh issuance's own request, scope and token identities remain fresh-source evidence and do not replace any original operation field. Gateway context or `connectTokenJti` alone is insufficient. + +Before releasing bytes, Account re-reads current authority, the separate `membershipVersion`, applicable Account issuance and token-identity fences, the original delegation's active registry record, and every applicable installation, lease, and binding postcondition. The exact original exchange operation ID, request ID and digest, committed connect-source operation identity, original signed context and its evidence digest, result bytes, and result expiry are immutable. The expired original context is historical evidence only; it is never accepted as current authorization. Recovery returns the original result byte-for-byte and does not mint, replace, or extend a credential or admit gameplay. A missing, expired, changed, stale, unavailable, ambiguous, or contradictory input or postcondition denies recovery without mutation. Ordinary bare `LOGIN` still rejects an expired Gateway context; no expiry bypass or frozen-clock compatibility path is permitted. Account-local encrypted storage and proof consequences are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md). + ## Responsibility Split - **Account Service** – Verifies login secrets according to account-selected password/email-code modes and owns Account-side authentication authority. JWT profiles, registry, generation, signer, and JWKS rules are defined in [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md). diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index 5c766504f5..d8d336ee8f 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -157,7 +157,7 @@ Issuance and refresh use an explicit authority linearization boundary. One seria `membershipVersion` is an independent issuance and refresh fence carrier, not a projection of or substitute for `authorityTuple.membershipAuthorityGeneration`. For every applicable token issuance or refresh, Account must read both values from the same live membership snapshot, validate each against its own current high-water and route requirement, bind both independently into the authority evidence, registry candidate, and refresh/replacement operation, and include both in the composite compare-and-set. A membership-version advance rejects or retries a candidate even when the membership authority generation is unchanged; a membership-authority-generation advance rejects or retries it even when the membership version is unchanged. Missing, regressed, mismatched, or separately assembled evidence for either carrier fails closed, and a successful refresh must install both refreshed carriers without scalarizing or silently dropping `membershipVersion`. -Issuance and refresh have a durable idempotency commit point. Account binds each operation to a high-entropy `requestId` and immutable request digest, stores only token identities, hashes, digests, metadata, complete `authorityTuple`, `issuanceFence`, and postcondition evidence in durable operation state, and accepts the exact registry record before returning the token. For a private delegation or admission-bound operation, the applicable lease and Game Session binding/installation are additional idempotent postconditions of the same request and fence; Account and Game Session must read back the complete postcondition set before exposing a successful usable result. Durable operation evidence never stores a raw JWT. A separate bounded response envelope encrypted under Account-owned application encryption may retain the exact response credential for the same request after reconciliation, bound to the request, digest, caller workload, binding, lineage, replacement, lease, issuance fence, and tuple; it is not registry state or authorization evidence. A registry, lease, or binding timeout or ambiguous response returns no token until the durable operation and all applicable postconditions reconcile. A matching retry may recover the exact response credential only from that separate envelope after current-state revalidation, while a changed digest conflicts without mutation. Refresh applies the same rule to the replacement lineage: the replacement registry record is accepted before the predecessor is retired, and any orphaned replacement is explicitly aborted or retired by Account's reconciler rather than becoming usable by registry absence. A crash between postcondition acceptance and response is replayable by request identity, not a reason to mint a second token or infer success from partial state. +Issuance and refresh have a durable idempotency commit point. Account binds each operation to a high-entropy `requestId` and immutable request digest, stores only token identities, hashes, digests, metadata, complete `authorityTuple`, `issuanceFence`, and postcondition evidence in durable operation state, and accepts the exact registry record before returning the token. For a private delegation or admission-bound operation, the applicable lease and Game Session binding/installation are additional idempotent postconditions of the same request and fence; Account and Game Session must read back the complete postcondition set before exposing a successful usable result. Durable operation evidence never stores a raw JWT. A separate bounded response envelope encrypted under Account-owned application encryption may retain the exact response credential for the same request after reconciliation, bound to the request, digest, caller workload, binding, lineage, replacement, lease, issuance fence, and tuple; it is not registry state or authorization evidence. A registry, lease, or binding timeout or ambiguous response returns no token until the durable operation and all applicable postconditions reconcile. A matching retry may recover the exact response credential only from that separate envelope after current-state revalidation, while a changed digest conflicts without mutation. The terminal bare-`LOGIN` recovery exception after original Gateway-context expiry is owned by [Authentication](./system-architecture-authentication.md#terminal-bare-login-result-recovery-normative) and does not relax exact-envelope, current-authority, registry, or postcondition requirements. Refresh applies the same rule to the replacement lineage: the replacement registry record is accepted before the predecessor is retired, and any orphaned replacement is explicitly aborted or retired by Account's reconciler rather than becoming usable by registry absence. A crash between postcondition acceptance and response is replayable by request identity, not a reason to mint a second token or infer success from partial state. Every generation-bearing validation on a registry-backed JWT route, and every later gameplay admission lease/binding validation that consumes an issuance baseline, must obtain explicit authority-projection freshness evidence for the registry, lease, binding, token-identity fence, and Account authority evidence used by the operation. The evidence fence identifies the exact authority scope, every applicable field in `authorityTuple`, cutoff checkpoint, `issuanceFence`, source transaction or outbox/event version, and observed projection status. A validator may authorize only when that evidence proves the projection represents the current committed authority for the requested scope; Redis key presence, a successful read, a timestamp, or a cached value is not freshness evidence. This requirement explicitly excludes Gateway's replay-fence validation in the bounded `gameplay-connect` issuance-evidence path: Gateway does not read the ordinary issued-token registry or the Account authority evidence bundle, and it validates the signed `replayAdmissionFence` and atomically consumes the dedicated single-use replay record. Game Session performs the later exact-binding lease, binding-fence, and current-authority checks. Missing, malformed, ambiguous, stale, regressed, or unavailable fence evidence fails closed. An unreachable or timed-out registry, lease, binding, fence, authority-generation source, or Account authority-evidence dependency is retryable `AUTH_UNAVAILABLE` / HTTP 503; entitlement-only unavailability is classified as `ENTITLEMENT_UNAVAILABLE` by the owning entitlement/admission contract and never relabeled as an auth-authority outage. Reachable missing, expired, revoked, mismatched, or otherwise invalid evidence is `AUTH_SESSION_REVOKED` or the specific invalid-token outcome requiring reauthentication. diff --git a/design/project-management/design-alignment/README.md b/design/project-management/design-alignment/README.md index 8c71fec498..e18ec8ac43 100644 --- a/design/project-management/design-alignment/README.md +++ b/design/project-management/design-alignment/README.md @@ -29,7 +29,7 @@ The preserved 5B implementation work was rebuilt into #2826 Schema, the dependen | Section | Original scope | Status | Main PR | Evidence / routed work | | --- | --- | --- | --- | --- | | 1A | Identity, entitlement, and hosted terms | Provisional; earlier broad discovery closed by judgment, required implementation and proof open | [#2840](https://github.com/benhook1013/FireMUD/pull/2840) | The refreshed 29-source unit had no taper finding; #2846–#2848 are stacked correction drafts, not merge or activation proof. #2848 contains Account gRPC/provider fail-closed boundaries, atomic recovery-token claims, disabled deletion/legacy export, and bounded evidence-only JOIN reconciliation. The [Player Access tracker](../implementation-tracking/player-access-and-session.md#unit-1a-section-exit-dispositions) names each current correction, pre-v1 Account successor, Unit 1B consumer, and activation gate. PostgreSQL concurrency/lost-acknowledgement, composed cross-service/certificate CI, direct text-to-Logging delivery, retained-data disposition, and billing/hosted-terms authority remain open; locally skipped tests do not close them. | -| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) β†’ [#2876](https://github.com/benhook1013/FireMUD/pull/2876) β†’ [#2880](https://github.com/benhook1013/FireMUD/pull/2880) β†’ [#2881](https://github.com/benhook1013/FireMUD/pull/2881) β†’ [#2911](https://github.com/benhook1013/FireMUD/pull/2911) β†’ [#2914](https://github.com/benhook1013/FireMUD/pull/2914) β†’ [#2915](https://github.com/benhook1013/FireMUD/pull/2915) | Provisional; #2915's corrected creation and Account association database proof passed, but complete authenticated snapshot, current authority, credential/delegation/registry, protected ring delivery, durable reconnect, and HTTPS/mail/abuse/browser gates remain open. Database component proof is not a live owner handoff or activation proof. Membership RPC and credentials stay denied; ring mount unpublished. See the [Player Access tracker](../implementation-tracking/player-access-and-session.md) for exact proof and handoffs. | +| 1B | Admission, session continuity, and reconnect | Provisional; required producer/consumer implementation and proof open | [#2857](https://github.com/benhook1013/FireMUD/pull/2857), [#2861](https://github.com/benhook1013/FireMUD/pull/2861), [#2873](https://github.com/benhook1013/FireMUD/pull/2873) β†’ [#2876](https://github.com/benhook1013/FireMUD/pull/2876) β†’ [#2880](https://github.com/benhook1013/FireMUD/pull/2880) β†’ [#2881](https://github.com/benhook1013/FireMUD/pull/2881) β†’ [#2911](https://github.com/benhook1013/FireMUD/pull/2911) β†’ [#2914](https://github.com/benhook1013/FireMUD/pull/2914) β†’ [#2915](https://github.com/benhook1013/FireMUD/pull/2915) β†’ [#2917](https://github.com/benhook1013/FireMUD/pull/2917) | Provisional; #2915's corrected creation and Account association database proof passed; #2917 adds the fresh UUID-only pair/snapshot prerequisite, with database proof pending. Complete authenticated snapshot, current authority, credential/delegation/registry, protected ring delivery, durable reconnect, and HTTPS/mail/abuse/browser gates remain open. Database component proof is not a live owner handoff or activation proof. Membership RPC and credentials stay denied; ring mount unpublished. See the [Player Access tracker](../implementation-tracking/player-access-and-session.md) for exact proof and handoffs. | | 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/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 041dbec621..db72cc70b8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,6 +6,12 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +The next #2918 component correlates the exact stored original V37 exchange/request/digest and V35 history with a distinct strict-current committed V35 source under the same Account fence. It compares the full canonical player/tenant/selected-target projection, retaining original and fresh requests, operations, scope hashes, token identities and timestamps separately. The strict source is checked before historical frame access and again afterward, without extending its signed deadline. Historical Gateway expiry evidence now uses signed `expiresAt`, not the source JWT's `exp`. Four additional PostgreSQL cases cover immutable exact reread, expired or non-distinct fresh proof, player/tenant/target/lifecycle/generation and original-request/digest mismatch, and an actual database lock wait during stored-frame access that outlives the fresh deadline; a unit case covers early peer/transaction denial. The consolidated Account full check/JAR, formatting, Checkstyle, SpotBugs, JaCoCo and documentation passed (70 tasks, 23 executed/47 up-to-date): 441 unit cases executed without failures/skips, and all 133 PostgreSQL cases compiled/discovered but skipped without Docker. Four new named cases are mandatory in strict CI; the preexisting Account-fence case now exercises the correlation path without losing its required method name. Actionlint and all 23 CI-scope contracts passed. Actual PostgreSQL execution of the new correlation cases remains required. These are source-correspondence prerequisites only: current authority, membershipVersion, result JWT/expiry/registry, recovery horizon, producer evidence and postconditions remain open, and no credential or runtime path is enabled. The component counts below refer to earlier checkpoints, not this batch. + +The next terminal-recovery component is an unwired `AccountStoredBareLoginRecoveryReader`: exact Game Session peer and owner transaction precede repository/crypto interaction, the Account fence protects exact committed V37 operation/envelope readback, and the decoded retained frame's result hash and signed historical context must match its exact committed V35 source. It returns redacted immutable provenance facts, never credential/context bytes or authorization. Two new PostgreSQL cases cover repeated expired-context framed readback and changed digest/source/context/result hash/key rejection, including unframed-payload denial; three unit cases cover early caller/transaction denial. Named PostgreSQL methods are required by strict CI verification. Local Account full check/JAR, formatting/static analysis and documentation passed: 440 unit cases executed with zero failures/skips, and all 129 PostgreSQL cases compiled but skipped without Docker. SpotBugs rejected an unnecessary suppression; it was removed rather than bypassing the check. Exact composed [CI 36807876923](https://github.com/benhook1013/FireMUD/actions/runs/36807876923) on `a65200c1e4bf9c28eb157a4e2ca34f44234e17b4` executed all eleven earlier source cases with zero skips and one assertion-message failure: the verifier deliberately sanitizes projection errors, but the negative test expected the underlying message. This fixture is corrected at its #2918 owner without changing rejection or no-mutation assertions; the final local rerun passed (70 tasks, 15 executed/55 up-to-date; unchanged unit results cached), and remote rerun remains required for both it and the two new stored-frame methods. That earlier run also passed the strict fresh-association 6, pair-authority 8, fresh-snapshot 10 and Game Design creation 7 cases. Game Session was cancelled; no Script Pin/WebSocket proof is credited to that run. The original result JWT/expiry, declared recovery horizon, producer evidence digests, separate fresh authorization, current authority/registry/postconditions and complete canonical-UUID wiring remain required; neither this component nor historical evidence enables the exchange. The reader clears decrypted/extracted byte arrays, but the framing object's internal defensive copies have no explicit destruction API and are left for garbage collection; no complete memory-erasure guarantee is claimed. + +The recovery foundation includes a distinct historical Account source verifier and an unwired committed V35 history reader. The reader requires the exact Game Session peer and an active owner transaction before data access, then fences the Account row, verifies canonical Account/approved retained tenant provenance, reads the exact committed operation/envelope, checks its purpose/hash/JTI and independently signed source/context correspondence, and returns deeply immutable non-authorizing evidence without the compact credentials. Decrypted bytes are cleared. The strict-current reader still rejects expired evidence and rechecks unchanged deadlines after fence waits; no clock is reset. Four new PostgreSQL cases cover expired-source historical readback with strict-reader denial, request/target/hash/JTI mismatches, noncommitted source rejection, and unregistered signing keys; existing cases also exercise historical key/provenance denial. Root removed an impossible missing-envelope fixture rather than weakening V35's deletion guard; no missing-envelope fault-injection proof is claimed. Consolidated Account/Common Security full checks, Account JAR and docs passed (82 tasks, 23 executed/59 up-to-date): 437 Account unit cases executed, including all 13 source-verifier and five early-denial cases; all 127 Account PostgreSQL cases skipped without Docker, and unchanged Common Security checks were up-to-date. Named history cases are required by strict CI verification even when another Account check fails. This supplied historical assertion is not evidence of V37 original-context retention or past Gateway acceptance. Durable original-context/result production, separate fresh authorization, current authority, active registry and exact terminal result release remain unproved; no runtime path is enabled. + PR #2917's snapshot failure-injection fixture now stubs the underlying Mockito target instead of entering the Spring transaction proxy during setup. The actual producer call still traverses that original proxy inside its owner transaction and executes the real mutation before the injected failure; neither `MANDATORY` propagation nor the explicit repository guard is weakened. The correction's local Account full check/JAR, formatting and static analysis passed, with unchanged 426 unit results up-to-date and all 123 PostgreSQL cases skipped without Docker. Documentation validation is rerun after the final status edit. Corrected runtime execution of both failed cases remains required; the failed exact-head CI below is incident evidence, not replaced by local skips. Exact #2915 head `910d0a6f41d60ee7214b610d56f89c51db260413` [CI 36796087279](https://github.com/benhook1013/FireMUD/actions/runs/36796087279) executed and passed all six Account fresh-association and seven Game Design creation PostgreSQL cases with zero skips, failures or errors; every strictly required retry/concurrency/rollback case executed once. These counts come from the strict JUnit XML-verifier logs, not JaCoCo; retained artifacts contain HTML but not raw JUnit XML. Account, Game Design and shared-core unit tasks ran with build/configuration caches disabled. Account's check and JAR passed; Game Design's check failed on the unchanged Entity baseline-migration fixture already routed to #2872 and its hosted JAR step skipped. Automation formatting, shared Ruff and the dev-demo summary validator also keep aggregate CI red. This supersedes the earlier failed creation-fixture proof below, not its incident evidence. Database component proof does not establish live mTLS/SPIFFE, certificate rotation, fresh-image boot, a deployed cross-owner handoff or activation. @@ -14,8 +20,12 @@ Draft [#2917](https://github.com/benhook1013/FireMUD/pull/2917) extends the exis The next Account-owned committed-connect source reader is an unwired prerequisite, not an authorization or credential producer. It recovers a complete successful V35 receipt and purpose-bound envelope by exact identity, checks the original compact JWT hash/JTI and asymmetric signature against the closed selected-target profile, verifies the Gateway assertion independently, and proves source/context correspondence under the Account row fence and approved retained tenant mapping. It requires the exact Game Session peer and an active owner transaction before data access, returns no raw credential, and rechecks unchanged deadlines after a fence wait. The consolidated local Account check passed with 413 unit cases executed, including 11 original-source verifier and four early-denial cases; all 105 PostgreSQL cases compiled but skipped without Docker, including the seven source-readback cases. Separately, exact #2914 head `ac8d52758384e16a2c5f1fc086af40589ad86350` [CI 36785132585](https://github.com/benhook1013/FireMUD/actions/runs/36785132585) passed its Account and Game Session jobs: the seven new PostgreSQL cases and exact-reread/fence-expiry methods each executed once with zero skips or failures, alongside the strict 30 JOIN, 9 connect-issuance, 9 bare-LOGIN storage, 2 authority-generation, 4 authority-outbox, 25 Script Pin, and 16 WebSocket cases. Aggregate CI remains red on failures outside this slice. The source reader supplies original-source evidence onlyβ€”not current authority or authorizationβ€”and does not supply fresh tenant authority, an issued-token registry, protected key delivery, or a working bare-LOGIN exchange; no runtime path or mount is enabled. +Terminal bare-`LOGIN` result recovery after original Gateway-context expiry is a selected extension of the canonical [Authentication contract](../../architecture/system-architecture-authentication.md#terminal-bare-login-result-recovery-normative), not an implemented exchange. It uses a separate fresh Account-committed connect issuance and independently signed valid Gateway context under the exact Game Session peer to reauthorize readback of the same player's complete same-target `COMMITTED` result. The original source/request/operation identity, digest, signed context, result bytes, and result expiry remain unchanged; no new token, expiry extension, expired-context `LOGIN`, or admission is permitted. Current authority, separate membership version, issuance/token fences, active result registry, applicable installation/lease/binding checks, original JWT `exp`, and the distinct envelope-recovery horizon must all pass. A local shared codec now verifies a closed signed assertion as a distinct immutable `HistoricalGatewayConnectEvidence` type; current-context readers still reject the same expired assertion. Its focused Common Security check passed with 116 executed unit cases and no skips or failures, including exact bytes, signature/key/schema/receiver/time-geometry negatives, source correspondence and strict-reader denial. This is historical signature/shape proof only, not Account source authentication, past Gateway acceptance, fresh authorization or terminal recovery eligibility. V37 still retains only the original context digest; encrypted original-context/result retention, current-authority/registry composition, complete canonical-UUID identity wiring and end-to-end recovery remain required. Existing #2914 source-reader cases are not recovery proof; live caller, ring/key-channel and runtime activation proof remain open, and bare `LOGIN`/membership paths remain denied. Account-local evidence requirements are in [Runtime & Data](../../architecture/microservices/account-service/runtime-and-data.md). + Exact #2911 `78c3fe88614708a4cd224800ac0f1bd6d03b310e` [CI 36778631119](https://github.com/benhook1013/FireMUD/actions/runs/36778631119) passed both strict Account PostgreSQL gates: JOIN 30/30, connect issuance 9/9, bare-LOGIN storage 9/9, authority-generation 2/2 and authority-outbox 4/4, all zero skips/failures. The complete nonadmitting snapshot versus concurrent first-JOIN case and both exhaustion rollback methods each executed once. Game Session strict Script Pin 25/25 and WebSocket 16/16 also passed. Account and Game Session checks disabled build/configuration cache and executed their tasks; aggregate CI remains red on separately routed shared tooling, Game Design fixture and Automation formatting failures. This closes those source/component database-proof gaps, not the live authenticated snapshot, complete immutable Account evidence bundle, credential producer/registry, or end-to-end bare-LOGIN gates below. The runtime RPC and credential paths remain denied, and the ring mount remains unpublished. +The local terminal-recovery storage foundation adds `BareLoginRecoveryPayload` under the existing `BARE_LOGIN_RESPONSE` purpose, without a new purpose, persistence column, fixed TTL or activation. Its closed versioned byte frame preserves the original signed Gateway context and opaque result bytes within the existing plaintext limit, rejects unknown version/header, malformed lengths, invalid context encoding, truncation and trailing bytes, and defensively copies/redacts contents. Eight framing cases and the extended existing purpose-bound encryption/readback case passed in the composed Account check: **434 unit tests executed**, zero failures/errors/skips; Common Security's unchanged **116** passing cases were up-to-date from its preceding executed check. All **123 Account PostgreSQL tests skipped locally** without Docker. Formatting, Checkstyle, SpotBugs, JaCoCo, JAR packaging, links and Markdown passed. This is frame/crypto and historical-assertion component proof, not durable operation/envelope producer proof, fresh reauthorization, current registry/postcondition readback or a successful terminal exchange. The producer, protected ring channel/readiness and complete positive/negative end-to-end proof remain open. + Account-fenced runtime snapshot preparation reuses durable absence enrollment and exact readback for a verified never-joined pair, while retained active membership requires its existing receipt/event proof and preserved counters. Unmapped tenants, inactive membership, and absent rows with retained history remain denied; neither enrollment nor exact retry creates membership or an authority event. The pure snapshot reader still rejects an absent baseline. #2880 composes preparation with the complete typed same-snapshot response, and the executed PostgreSQL proof above covers that nonadmitting DTO against concurrent first JOIN. It does not prove an authenticated runtime RPC or admission; those paths and the Account ring mount remain disabled. The unmerged #2876 `account-auth-authority-event/v1` correction uses ADR 0030's exact one-tenant `membershipVersion` map in the producer, strict shared codec, canonical digest vectors, immutable evidence, and Account exact retry/readback comparisons. The Account producer may extract a local numeric value only after validating the map; it does not persist or transmit a scalar event field. Shared codec and Account/Game Session vector tests execute locally; PostgreSQL JOIN/reconciliation tests compile but skip without Docker, and the runtime membership RPC remains denied until its complete same-snapshot producer and consumer proof is ready. The unactivated Account ring materializer binds a dedicated service-account username in the protected source record, checks server-reported identity before Secret access, and returns a typed non-secret receipt with source generation/predecessor and exact Secret UID/resourceVersion readback. A focused read-side verifier now checks its closed typed shape, canonical digest, and exact source, writer, and Secret bindings; this remains local structural proof, not authenticated environment/secrets-channel publication. Sole-writer RBAC, protected custody, handoff, deployment readback, and live readiness remain unproved, so no Account ring mount is published. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java index 3cf47cbf1c..cbc2bd00dc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifier.java @@ -19,6 +19,7 @@ import java.util.Map; import java.util.Set; import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; import tools.jackson.core.StreamReadFeature; import tools.jackson.core.json.JsonFactory; import tools.jackson.databind.DeserializationFeature; @@ -105,13 +106,61 @@ public AccountGameplayConnectSourceVerifier( */ public Map verify(String compactJwt) { try { - return verifyInternal(compactJwt); + SignedCompactSource source = verifySignedCompactSource(compactJwt); + Instant now = clock.instant(); + validateIssuerAudienceAndTimeAt(source.claims(), now); + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + source.claims(), now.getEpochSecond(), SAFE_PROJECTION_CORRELATION_ID); + return deepImmutableObject(source.claims()); } catch (RuntimeException | GeneralSecurityException ex) { throw invalidToken(); } } - private Map verifyInternal(String compactJwt) throws GeneralSecurityException { + /** + * Verifies an Account gameplay-connect source only as historical evidence for an already + * signature-verified Gateway assertion. The Gateway assertion's signed {@code verifiedAt} is the + * source-time anchor; this method does not change or backdate this verifier's clock. + * + *

The returned value is deliberately distinct from the current source claim map. It proves the + * Account signature and closed source profile, plus exact correspondence to the supplied + * historical Gateway projection. It does not prove that Gateway accepted the assertion, that the + * source was durably issued, or that any current authority, registry, recovery, or admission + * condition holds. The compact Account JWT is not retained. + * + *

Every verification failure has the same sanitized exception message. Neither the source + * token nor detailed parser or cryptographic failures are retained. + * + * @param compactJwt compact Account-signed JWT + * @param historicalGatewayEvidence Gateway evidence produced by the historical Gateway codec + * @return immutable Account source claims and their historical Gateway correspondence + * @throws IllegalArgumentException if either assertion is malformed, untrusted, or mismatched + */ + public HistoricalAccountGameplayConnectEvidence verifyHistorical( + String compactJwt, HistoricalGatewayConnectEvidence historicalGatewayEvidence) { + try { + if (historicalGatewayEvidence == null) { + throw invalidToken(); + } + SignedCompactSource source = verifySignedCompactSource(compactJwt); + BigInteger gatewayVerifiedAt = historicalGatewayEvidence.integer("verifiedAt"); + if (gatewayVerifiedAt == null || gatewayVerifiedAt.signum() <= 0) { + throw invalidToken(); + } + Instant originalGatewayVerificationTime = + Instant.ofEpochSecond(gatewayVerifiedAt.longValueExact()); + validateIssuerAudienceAndTimeAt(source.claims(), originalGatewayVerificationTime); + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesHistoricalGatewayEvidence( + source.claims(), historicalGatewayEvidence); + return new HistoricalAccountGameplayConnectEvidence( + source.keyId(), deepImmutableObject(source.claims()), historicalGatewayEvidence); + } catch (RuntimeException | GeneralSecurityException ex) { + throw invalidToken(); + } + } + + private SignedCompactSource verifySignedCompactSource(String compactJwt) + throws GeneralSecurityException { String[] segments = splitCanonicalCompactJwt(compactJwt); byte[] protectedHeaderBytes = decodeCanonicalBase64Url(segments[0]); byte[] payloadBytes = decodeCanonicalBase64Url(segments[1]); @@ -133,12 +182,7 @@ private Map verifyInternal(String compactJwt) throws GeneralSecu verifySignature(segments[0], segments[1], signatureBytes, key, jcaAlgorithm); Map sourceClaims = parseJsonObject(payloadBytes); - Instant now = clock.instant(); - validateIssuerAudienceAndTime(sourceClaims, now); - - GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( - sourceClaims, now.getEpochSecond(), SAFE_PROJECTION_CORRELATION_ID); - return deepImmutableObject(sourceClaims); + return new SignedCompactSource(kid, sourceClaims); } private String[] splitCanonicalCompactJwt(String compactJwt) { @@ -246,7 +290,7 @@ private void verifySignature( } } - private void validateIssuerAudienceAndTime(Map claims, Instant now) { + private void validateIssuerAudienceAndTimeAt(Map claims, Instant validationTime) { if (!exactIssuer.equals(claims.get("iss")) || !(claims.get("iss") instanceof String) || !"gameplay-connect".equals(claims.get("aud"))) { @@ -260,9 +304,9 @@ private void validateIssuerAudienceAndTime(Map claims, Instant n try { Instant issuedAtInstant = Instant.ofEpochSecond(issuedAt.longValueExact()); Instant expiresAtInstant = Instant.ofEpochSecond(expiresAt.longValueExact()); - if (!now.isBefore(expiresAtInstant) + if (!validationTime.isBefore(expiresAtInstant) || issuedAt - .subtract(BigInteger.valueOf(now.getEpochSecond())) + .subtract(BigInteger.valueOf(validationTime.getEpochSecond())) .compareTo(BigInteger.valueOf(MAX_FUTURE_ISSUED_AT_SECONDS)) > 0) { throw invalidToken(); @@ -334,4 +378,6 @@ private static boolean isSupportedKey(PublicKey key) { private static IllegalArgumentException invalidToken() { return new IllegalArgumentException(INVALID_TOKEN_MESSAGE); } + + private record SignedCompactSource(String keyId, Map claims) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayload.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayload.java new file mode 100644 index 0000000000..7bce98a427 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayload.java @@ -0,0 +1,174 @@ +package net.firedevops.firemud.accountservice.security; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; + +/** + * Bounded storage framing for the exact original bare-LOGIN Gateway assertion and result bytes. + * + *

This payload is intended only for encryption with {@link + * AccountEnvelopePurpose#BARE_LOGIN_RESPONSE} and the matching durable operation binding. It does + * not verify either signature, establish current authorization, or determine recovery eligibility. + */ +public final class BareLoginRecoveryPayload { + private static final byte[] MAGIC = new byte[] {'F', 'M', 'B', 'R'}; + private static final int VERSION = 1; + private static final int HEADER_BYTES = Integer.BYTES * 4; + + private final byte[] originalGatewayContextUtf8; + private final byte[] originalResultBytes; + + private BareLoginRecoveryPayload(byte[] originalGatewayContextUtf8, byte[] originalResultBytes) { + this.originalGatewayContextUtf8 = + Objects.requireNonNull(originalGatewayContextUtf8, "original Gateway context is required") + .clone(); + this.originalResultBytes = + Objects.requireNonNull(originalResultBytes, "original result is required").clone(); + validateContext(this.originalGatewayContextUtf8); + validateResult(this.originalResultBytes); + requireFrameWithinLimit( + this.originalGatewayContextUtf8.length, this.originalResultBytes.length); + } + + /** Creates a frame from the exact compact Gateway envelope and exact opaque result bytes. */ + public static BareLoginRecoveryPayload of( + String exactOriginalGatewayContext, byte[] exactOriginalResultBytes) { + Objects.requireNonNull(exactOriginalGatewayContext, "original Gateway context is required"); + if (exactOriginalGatewayContext.isEmpty() + || exactOriginalGatewayContext.chars().anyMatch(character -> character > 0x7f)) { + throw invalid("Original Gateway context must be non-empty ASCII compact data"); + } + return new BareLoginRecoveryPayload( + exactOriginalGatewayContext.getBytes(StandardCharsets.UTF_8), exactOriginalResultBytes); + } + + /** Decodes one complete version-1 frame, rejecting truncation and trailing data. */ + public static BareLoginRecoveryPayload decode(byte[] encodedFrame) { + Objects.requireNonNull(encodedFrame, "encoded frame is required"); + if (encodedFrame.length < HEADER_BYTES || encodedFrame.length > maxFrameBytes()) { + throw invalid("Bare LOGIN recovery payload length is invalid"); + } + + ByteBuffer input = ByteBuffer.wrap(encodedFrame).order(ByteOrder.BIG_ENDIAN); + byte[] magic = new byte[MAGIC.length]; + input.get(magic); + if (!Arrays.equals(MAGIC, magic)) { + throw invalid("Bare LOGIN recovery payload header is invalid"); + } + if (input.getInt() != VERSION) { + throw invalid("Bare LOGIN recovery payload version is unsupported"); + } + + int contextLength = input.getInt(); + if (contextLength <= 0 || contextLength > input.remaining() - Integer.BYTES) { + throw invalid("Bare LOGIN recovery payload context length is invalid"); + } + byte[] context = new byte[contextLength]; + input.get(context); + + int resultLength = input.getInt(); + if (resultLength <= 0 || resultLength != input.remaining()) { + throw invalid("Bare LOGIN recovery payload result length is invalid"); + } + byte[] result = new byte[resultLength]; + input.get(result); + return new BareLoginRecoveryPayload(context, result); + } + + /** Returns a newly encoded, versioned frame suitable for Account envelope encryption. */ + public byte[] encode() { + int frameLength = + Math.addExact( + HEADER_BYTES, + Math.addExact(originalGatewayContextUtf8.length, originalResultBytes.length)); + requireFrameWithinLimit(originalGatewayContextUtf8.length, originalResultBytes.length); + ByteBuffer output = ByteBuffer.allocate(frameLength).order(ByteOrder.BIG_ENDIAN); + output.put(MAGIC); + output.putInt(VERSION); + output.putInt(originalGatewayContextUtf8.length); + output.put(originalGatewayContextUtf8); + output.putInt(originalResultBytes.length); + output.put(originalResultBytes); + return output.array(); + } + + /** Returns the exact original ASCII compact envelope as UTF-8 bytes. */ + public byte[] originalGatewayContextUtf8() { + return originalGatewayContextUtf8.clone(); + } + + /** Returns the exact compact envelope text, without parsing or verifying its JWS. */ + public String originalGatewayContext() { + return new String(originalGatewayContextUtf8, StandardCharsets.UTF_8); + } + + /** Returns the exact opaque result bytes without text decoding or normalization. */ + public byte[] originalResultBytes() { + return originalResultBytes.clone(); + } + + @Override + public String toString() { + return "BareLoginRecoveryPayload[version=" + + VERSION + + ", gatewayContextBytes=" + + originalGatewayContextUtf8.length + + ", resultBytes=" + + originalResultBytes.length + + ", contents=]"; + } + + private static void validateContext(byte[] context) { + final String decoded; + try { + decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(context)) + .toString(); + } catch (CharacterCodingException exception) { + throw invalid("Original Gateway context is not valid UTF-8"); + } + if (decoded.chars().anyMatch(character -> character > 0x7f)) { + throw invalid("Original Gateway context must be ASCII compact data"); + } + int firstDot = decoded.indexOf('.'); + int secondDot = firstDot < 0 ? -1 : decoded.indexOf('.', firstDot + 1); + if (firstDot <= 0 + || secondDot <= firstDot + 1 + || secondDot == decoded.length() - 1 + || decoded.indexOf('.', secondDot + 1) >= 0) { + throw invalid("Original Gateway context must contain three non-empty compact segments"); + } + } + + private static void validateResult(byte[] result) { + if (result.length == 0) { + throw invalid("Original bare LOGIN result must not be empty"); + } + } + + private static void requireFrameWithinLimit(int contextLength, int resultLength) { + long frameLength = (long) HEADER_BYTES + contextLength + resultLength; + if (contextLength <= 0 + || resultLength <= 0 + || frameLength > AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES) { + throw invalid("Bare LOGIN recovery payload exceeds its storage bound"); + } + } + + private static int maxFrameBytes() { + return AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES; + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/HistoricalAccountGameplayConnectEvidence.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/HistoricalAccountGameplayConnectEvidence.java new file mode 100644 index 0000000000..35631d6cba --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/HistoricalAccountGameplayConnectEvidence.java @@ -0,0 +1,94 @@ +package net.firedevops.firemud.accountservice.security; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; + +/** + * Immutable Account source claims verified against a previously signed Gateway assertion. + * + *

This is historical provenance only. It does not prove original durable issuance, past Gateway + * acceptance, current authority, registry state, recovery eligibility, or gameplay admission. It is + * not a current source claim or a {@code GatewayConnectContext}, and it never retains the compact + * Account JWT. + */ +public final class HistoricalAccountGameplayConnectEvidence { + private final String accountKeyId; + private final Map sourceClaims; + private final HistoricalGatewayConnectEvidence gatewayEvidence; + + HistoricalAccountGameplayConnectEvidence( + String accountKeyId, + Map sourceClaims, + HistoricalGatewayConnectEvidence gatewayEvidence) { + if (accountKeyId == null || accountKeyId.isBlank()) { + throw new IllegalArgumentException("Account source key identifier is required"); + } + this.accountKeyId = accountKeyId; + this.sourceClaims = immutableObject(sourceClaims); + this.gatewayEvidence = Objects.requireNonNull(gatewayEvidence, "Gateway evidence is required"); + } + + public String accountKeyId() { + return accountKeyId; + } + + /** Returns an immutable, recursively copied view of the verified Account source claims. */ + public Map sourceClaims() { + return immutableObject(sourceClaims); + } + + /** Returns the distinct historical Gateway evidence used for exact source correspondence. */ + public HistoricalGatewayConnectEvidence gatewayEvidence() { + return gatewayEvidence; + } + + @Override + public String toString() { + return "HistoricalAccountGameplayConnectEvidence[accountKeyId=" + + accountKeyId + + ", gatewayKeyId=" + + gatewayEvidence.kid() + + ", historical=true]"; + } + + private static Map immutableObject(Map source) { + Objects.requireNonNull(source, "source claims are required"); + Map copy = new LinkedHashMap<>(); + source.forEach((key, value) -> copy.put(key, immutableValue(value))); + return Collections.unmodifiableMap(copy); + } + + private static Object immutableValue(Object value) { + if (value == null + || value instanceof String + || value instanceof Boolean + || value instanceof BigInteger + || value instanceof BigDecimal) { + return value; + } + if (value instanceof Map source) { + Map copy = new LinkedHashMap<>(); + source.forEach( + (key, nested) -> { + if (!(key instanceof String text)) { + throw new IllegalArgumentException("source claim object keys must be strings"); + } + copy.put(text, immutableValue(nested)); + }); + return Collections.unmodifiableMap(copy); + } + if (value instanceof List source) { + List copy = new ArrayList<>(source.size()); + source.forEach(nested -> copy.add(immutableValue(nested))); + return Collections.unmodifiableList(copy); + } + throw new IllegalArgumentException("unsupported verified source claim value"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java index 7f3f21d132..bcfb123ca9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReader.java @@ -28,10 +28,12 @@ import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.accountservice.security.HistoricalAccountGameplayConnectEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.GatewayConnectContext; import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -173,6 +175,82 @@ public OriginalSourceEvidence read( } } + /** + * Reads one exact, already-committed V35 Account source as historical provenance, using the + * caller-supplied signed original Gateway assertion to anchor source-time verification. This + * proves the committed source and its correspondence to that supplied assertion only. It does not + * prove that a V37 frame retained the original Gateway context, that Gateway accepted it, fresh + * authorization, current authority, registry readiness, result recovery eligibility, or + * admission. It cannot be used in place of {@link #read} or a current Gateway context. + */ + @Transactional(propagation = Propagation.MANDATORY) + public HistoricalCommittedSourceEvidence readHistorical( + AccountConnectTokenIssuanceIdentity identity, String signedOriginalGatewayAssertion) { + Objects.requireNonNull(identity, "identity"); + requireGameSessionPeer(); + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Committed Account source readback requires an active owner transaction"); + } + HistoricalGatewayConnectEvidence historicalGatewayEvidence = + GatewayConnectContextCodec.verifyHistoricalEvidence( + signedOriginalGatewayAssertion, gatewayVerificationKeys); + requireContextRequestIdentity(identity, historicalGatewayEvidence); + + // Keep the same Account row fence, canonical UUID provenance, and retained tenant resolver as + // strict-current source readback. The historical assertion changes neither the source identity + // nor the transaction/data-access boundary. + joinOperationRepository.lockAccount(identity.accountId()); + Account account = + accountRepository + .findById(identity.accountId()) + .orElseThrow(() -> new IllegalStateException("Account source identity is absent")); + UUID accountUuid = requireAccountIdentity(account, identity.accountId()); + requireContextValue(historicalGatewayEvidence, "accountId", accountUuid.toString()); + + ApprovedAssociation tenantAssociation = tenantIdentityResolver.resolve(identity.tenantId()); + if (tenantAssociation.legacyTenantId() != identity.tenantId()) { + throw new IllegalStateException("Account source tenant identity is mismatched"); + } + requireContextValue( + historicalGatewayEvidence, "tenantId", tenantAssociation.canonicalTenantId().toString()); + + AccountCommittedConnectSource committedSource = + issuanceRepository + .readCommittedResponseEnvelope(identity) + .orElseThrow(() -> new IllegalStateException("Committed Account source is absent")); + byte[] compactJwtBytes = + envelopeCrypto.decrypt( + committedSource.responseEnvelope().envelope(), + AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, + committedSource.responseEnvelope().binding()); + try { + String compactJwt = decodeStrictUtf8(compactJwtBytes); + byte[] actualTokenHash = sha256(compactJwtBytes); + if (!MessageDigest.isEqual(committedSource.operation().tokenHash(), actualTokenHash)) { + throw new IllegalStateException("Committed Account source token hash does not match"); + } + + HistoricalAccountGameplayConnectEvidence historicalSourceEvidence = + sourceVerifier.verifyHistorical(compactJwt, historicalGatewayEvidence); + Map sourceClaims = historicalSourceEvidence.sourceClaims(); + if (!Objects.equals(sourceClaims.get("jti"), committedSource.operation().tokenIdentity())) { + throw new IllegalStateException("Committed Account source token identity does not match"); + } + + return new HistoricalCommittedSourceEvidence( + committedSource.operation().operationId(), + committedSource.responseEnvelope().envelope().keyId(), + actualTokenHash, + historicalSourceEvidence.accountKeyId(), + historicalGatewayEvidence.kid(), + sourceClaims, + historicalGatewayEvidence.claims()); + } finally { + java.util.Arrays.fill(compactJwtBytes, (byte) 0); + } + } + private GatewayConnectContext verifyGatewayContext(String signedGatewayContext) { return GatewayConnectContextCodec.verifyAndDecode( signedGatewayContext, gatewayVerificationKeys, clock); @@ -195,6 +273,16 @@ private static void requireContextRequestIdentity( } } + private static void requireContextRequestIdentity( + AccountConnectTokenIssuanceIdentity identity, + HistoricalGatewayConnectEvidence historicalContext) { + if (!identity.connectScopeId().equals(historicalContext.text("connectScopeId")) + || !identity.requestId().equals(historicalContext.text("connectRequestId"))) { + throw new IllegalArgumentException( + "Gateway context does not match the exact Account source request identity"); + } + } + private static UUID requireAccountIdentity(Account account, long numericAccountId) { if (account.getId() == null || account.getId() != numericAccountId @@ -215,6 +303,14 @@ private static void requireContextValue( } } + private static void requireContextValue( + HistoricalGatewayConnectEvidence historicalContext, String field, String expectedValue) { + if (!expectedValue.equals(historicalContext.text(field))) { + throw new IllegalArgumentException( + "Gateway context does not match the retained Account " + field); + } + } + private static String decodeStrictUtf8(byte[] bytes) { try { return StandardCharsets.UTF_8 @@ -309,4 +405,49 @@ private static Object immutableValue(Object value) { throw new IllegalArgumentException("unsupported verified claim value"); } } + + /** + * Immutable readback of a committed V35 source matched to a caller-supplied historical Gateway + * assertion. This is source/correspondence provenance only; it does not establish retained V37 + * context, past Gateway acceptance, fresh or current authorization, registry state, recovery + * eligibility, or admission. It retains neither compact Account JWT nor signed Gateway envelope. + */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Verified claim maps and nested JSON values are deeply copied into immutable containers " + + "by the canonical constructor before record accessors expose them") + public record HistoricalCommittedSourceEvidence( + UUID operationId, + String responseEnvelopeKeyId, + byte[] sourceTokenHash, + String accountSourceKeyId, + String gatewayKeyId, + Map originalSourceClaims, + Map historicalGatewayClaims) { + public HistoricalCommittedSourceEvidence { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(responseEnvelopeKeyId, "responseEnvelopeKeyId"); + Objects.requireNonNull(accountSourceKeyId, "accountSourceKeyId"); + Objects.requireNonNull(gatewayKeyId, "gatewayKeyId"); + if (sourceTokenHash == null || sourceTokenHash.length != 32) { + throw new IllegalArgumentException("source token hash must be 32 bytes"); + } + sourceTokenHash = sourceTokenHash.clone(); + originalSourceClaims = OriginalSourceEvidence.immutableObject(originalSourceClaims); + historicalGatewayClaims = OriginalSourceEvidence.immutableObject(historicalGatewayClaims); + } + + @Override + public byte[] sourceTokenHash() { + return sourceTokenHash.clone(); + } + + @Override + public String toString() { + return "HistoricalCommittedSourceEvidence[operationId=" + + operationId + + ", committedSource=, historicalGateway=]"; + } + } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReader.java new file mode 100644 index 0000000000..57e3f51b43 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReader.java @@ -0,0 +1,589 @@ +package net.firedevops.firemud.accountservice.service; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeOperation; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeRepository; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginResponseEnvelope; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeBinding; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.BareLoginRecoveryPayload; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader.HistoricalCommittedSourceEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unwired, non-authorizing readback of one committed bare-LOGIN response frame and its original + * committed connect source. It never releases or retains the opaque original result, compact JWT, + * or original signed Gateway context. + */ +public final class AccountStoredBareLoginRecoveryReader { + private final AccountBareLoginExchangeRepository exchangeRepository; + private final AccountJoinOperationRepository joinOperationRepository; + private final AccountEnvelopeCrypto envelopeCrypto; + private final AccountCommittedConnectSourceReader committedSourceReader; + private final Map gatewayVerificationKeys; + private final String expectedGameSessionPeerUri; + + public AccountStoredBareLoginRecoveryReader( + AccountBareLoginExchangeRepository exchangeRepository, + AccountJoinOperationRepository joinOperationRepository, + AccountEnvelopeCrypto envelopeCrypto, + AccountCommittedConnectSourceReader committedSourceReader, + Map gatewayVerificationKeys, + String workloadNamespace) { + this.exchangeRepository = Objects.requireNonNull(exchangeRepository, "exchangeRepository"); + this.joinOperationRepository = + Objects.requireNonNull(joinOperationRepository, "joinOperationRepository"); + this.envelopeCrypto = Objects.requireNonNull(envelopeCrypto, "envelopeCrypto"); + this.committedSourceReader = + Objects.requireNonNull(committedSourceReader, "committedSourceReader"); + this.gatewayVerificationKeys = Map.copyOf(gatewayVerificationKeys); + if (this.gatewayVerificationKeys.isEmpty()) { + throw new IllegalArgumentException("Gateway verification keys are required"); + } + if (workloadNamespace == null || workloadNamespace.isBlank()) { + throw new IllegalArgumentException("Account workload namespace is required"); + } + this.expectedGameSessionPeerUri = + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service") + .filter(identity -> workloadNamespace.equals(identity.namespace())) + .map(GrpcPeerIdentity::uri) + .orElseThrow( + () -> new IllegalArgumentException("Account workload namespace is invalid")); + } + + /** + * Verifies committed encrypted V37/V35 provenance for an exact bare-LOGIN exchange identity and + * its caller-supplied immutable request digest. The stored frame is decoded only to verify its + * result hash and original historical Gateway/source correspondence; result bytes are never + * returned. + * + *

This proves stored framed provenance only. It does not prove prior Gateway acceptance, + * current authority, freshness, the original result expiry or recovery horizon, registry state, + * admission postconditions, recovery eligibility, or authorization. It does not release a + * credential or enable the bare-LOGIN runtime path. + */ + @Transactional(propagation = Propagation.MANDATORY) + public HistoricalStoredBareLoginEvidence readHistorical( + AccountBareLoginExchangeIdentity identity, byte[] requestDigest) { + Objects.requireNonNull(identity, "identity"); + requireGameSessionPeer(); + requireOwnerTransaction(); + return readHistoricalStored(identity, requestDigest).evidence(); + } + + /** + * Correlates exact stored original exchange/source history with a separately committed, strictly + * current Account connect source and its independently valid current Gateway context. This is + * only immutable source/target correspondence evidence: it does not prove current authority or + * membershipVersion, original result expiry, registry state, admission postconditions, recovery + * eligibility, or authorization, and releases no result, credential, JWT, or signed context. + */ + @Transactional(propagation = Propagation.MANDATORY) + public HistoricalStoredBareLoginCorrelationEvidence readCorrelation( + AccountBareLoginExchangeIdentity originalIdentity, + byte[] originalRequestDigest, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext) { + Objects.requireNonNull(originalIdentity, "originalIdentity"); + Objects.requireNonNull(freshIdentity, "freshIdentity"); + Objects.requireNonNull(signedFreshGatewayContext, "signedFreshGatewayContext"); + requireGameSessionPeer(); + requireOwnerTransaction(); + if (originalIdentity.accountId() != freshIdentity.accountId() + || originalIdentity.tenantId() != freshIdentity.tenantId()) { + throw new IllegalArgumentException( + "Original and fresh source identities must belong to the same Account and tenant"); + } + + // Establish the independent strict-current source first. Its Account reader checks the signed + // Gateway deadline again after any Account-fence wait, before this component reads the opaque + // stored original result frame. + var fresh = committedSourceReader.read(freshIdentity, signedFreshGatewayContext); + if (originalIdentity.sourceConnectOperationId().equals(fresh.operationId())) { + throw new IllegalStateException( + "Fresh connect proof must be a separate committed Account source operation"); + } + HistoricalReadback original = readHistoricalStored(originalIdentity, originalRequestDigest); + + SelectedTargetEvidence originalTarget = + selectedTarget(original.source().originalSourceClaims()); + SelectedTargetEvidence freshTarget = selectedTarget(fresh.originalSourceClaims()); + if (!originalTarget.equals(freshTarget)) { + throw new IllegalStateException( + "Fresh connect source does not select the exact original Account target"); + } + + // The original encrypted frame read can itself take time after the strict source reader's + // fence recheck. Re-run the unchanged strict-current path immediately before returning so an + // assertion that expires during history work cannot yield correlation evidence. + var finalFresh = committedSourceReader.read(freshIdentity, signedFreshGatewayContext); + requireSameCurrentReadback(fresh, finalFresh); + + return new HistoricalStoredBareLoginCorrelationEvidence( + original.evidence(), + connectSourceIdentity(original.source()), + connectSourceIdentity(freshIdentity, finalFresh), + originalTarget); + } + + private HistoricalReadback readHistoricalStored( + AccountBareLoginExchangeIdentity identity, byte[] requestDigest) { + byte[] checkedRequestDigest = requireDigest(requestDigest, "request digest"); + byte[] frameBytes = null; + byte[] originalGatewayContextBytes = null; + byte[] originalResultBytes = null; + byte[] originalResultHash = null; + byte[] storedResultHash = null; + byte[] sourceConnectTokenHash = null; + try { + // This is the same Account row fence used by the original-source reader. No operation, + // envelope, key-ring or signed-context access happens before the exact caller guard above. + joinOperationRepository.lockAccount(identity.accountId()); + + AccountBareLoginExchangeOperation operation = + exchangeRepository + .find(identity, checkedRequestDigest) + .orElseThrow(() -> new IllegalStateException("Bare LOGIN exchange source is absent")); + if (operation.lifecycle() != AccountBareLoginExchangeOperation.Lifecycle.COMMITTED + || !"SUCCESS".equals(operation.outcomeCode()) + || !operation.sourceConnectOperationId().equals(identity.sourceConnectOperationId()) + || operation.accountId() != identity.accountId() + || operation.tenantId() != identity.tenantId() + || !operation + .connectScopeHash() + .equals(AccountJoinDigest.tokenHash(identity.connectScopeId())) + || !operation.requestId().equals(identity.requestId()) + || !MessageDigest.isEqual(operation.requestDigest(), checkedRequestDigest)) { + throw new IllegalStateException("Bare LOGIN exchange is not the exact committed success"); + } + + AccountEnvelopeBinding binding = bindingFor(operation, identity); + AccountBareLoginResponseEnvelope responseEnvelope = + exchangeRepository + .readResponseEnvelope(identity, checkedRequestDigest, binding) + .orElseThrow( + () -> new IllegalStateException("Committed bare LOGIN response is absent")); + if (!operation.operationId().equals(responseEnvelope.operationId()) + || !binding.equals(responseEnvelope.binding()) + || responseEnvelope.envelope().purpose() != AccountEnvelopePurpose.BARE_LOGIN_RESPONSE) { + throw new IllegalStateException( + "Bare LOGIN response envelope does not match its operation"); + } + + frameBytes = + envelopeCrypto.decrypt( + responseEnvelope.envelope(), + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + responseEnvelope.binding()); + BareLoginRecoveryPayload payload = BareLoginRecoveryPayload.decode(frameBytes); + originalResultBytes = payload.originalResultBytes(); + originalResultHash = sha256(originalResultBytes); + storedResultHash = operation.tokenHash(); + if (!MessageDigest.isEqual(storedResultHash, originalResultHash)) { + throw new IllegalStateException( + "Stored bare LOGIN result hash does not match its operation"); + } + + originalGatewayContextBytes = payload.originalGatewayContextUtf8(); + String originalGatewayContext = + new String(originalGatewayContextBytes, StandardCharsets.UTF_8); + HistoricalGatewayConnectEvidence gatewayEvidence = + GatewayConnectContextCodec.verifyHistoricalEvidence( + originalGatewayContext, gatewayVerificationKeys); + if (!identity.connectScopeId().equals(gatewayEvidence.text("connectScopeId"))) { + throw new IllegalArgumentException( + "Stored original Gateway context does not match the bare LOGIN connect scope"); + } + String sourceConnectRequestId = gatewayEvidence.text("connectRequestId"); + if (sourceConnectRequestId == null || sourceConnectRequestId.isBlank()) { + throw new IllegalArgumentException( + "Stored original Gateway context has no source connect request identity"); + } + + HistoricalCommittedSourceEvidence sourceEvidence = + committedSourceReader.readHistorical( + new AccountConnectTokenIssuanceIdentity( + identity.accountId(), + identity.tenantId(), + identity.connectScopeId(), + sourceConnectRequestId), + originalGatewayContext); + if (!identity.sourceConnectOperationId().equals(sourceEvidence.operationId()) + || !gatewayEvidence.kid().equals(sourceEvidence.gatewayKeyId()) + || !gatewayEvidence.claims().equals(sourceEvidence.historicalGatewayClaims())) { + throw new IllegalStateException( + "Stored bare LOGIN source does not match its original Gateway context"); + } + sourceConnectTokenHash = sourceEvidence.sourceTokenHash(); + + HistoricalStoredBareLoginEvidence storedEvidence = + new HistoricalStoredBareLoginEvidence( + operation.operationId(), + identity.sourceConnectOperationId(), + identity.accountId(), + identity.tenantId(), + operation.requestId(), + operation.connectScopeHash(), + operation.requestDigestVersion(), + checkedRequestDigest, + originalResultHash, + sourceConnectTokenHash, + responseEnvelope.envelope().keyId(), + sourceEvidence.responseEnvelopeKeyId(), + sourceEvidence.accountSourceKeyId(), + sourceEvidence.gatewayKeyId(), + gatewayEvidence.integer("verifiedAt"), + gatewayEvidence.integer("expiresAt")); + return new HistoricalReadback(storedEvidence, sourceEvidence); + } finally { + Arrays.fill(checkedRequestDigest, (byte) 0); + wipe(frameBytes); + wipe(originalGatewayContextBytes); + wipe(originalResultBytes); + wipe(originalResultHash); + wipe(storedResultHash); + wipe(sourceConnectTokenHash); + } + } + + private AccountEnvelopeBinding bindingFor( + AccountBareLoginExchangeOperation operation, AccountBareLoginExchangeIdentity identity) { + return new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + operation.operationId().toString(), + identity.requestId(), + Long.toString(identity.accountId()), + Long.toString(identity.tenantId()), + identity.connectScopeId(), + identity.sourceConnectOperationId().toString(), + operation.requestDigest(), + operation.contextEvidenceDigest(), + operation.authorityTupleDigest(), + operation.issuanceFenceDigest(), + operation.postconditionDigest()); + } + + private void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Stored bare LOGIN history readback requires an active owner transaction"); + } + } + + private static ConnectSourceIdentityEvidence connectSourceIdentity( + HistoricalCommittedSourceEvidence evidence) { + Map claims = evidence.originalSourceClaims(); + Map gateway = evidence.historicalGatewayClaims(); + return new ConnectSourceIdentityEvidence( + evidence.operationId(), + requireText(claims, "requestId"), + AccountJoinDigest.tokenHash(requireText(claims, "connectScopeId")), + requireText(claims, "jti"), + evidence.sourceTokenHash(), + evidence.responseEnvelopeKeyId(), + evidence.accountSourceKeyId(), + evidence.gatewayKeyId(), + requireInteger(claims, "iat"), + requireInteger(claims, "exp"), + requireInteger(gateway, "verifiedAt"), + requireInteger(gateway, "expiresAt")); + } + + private static ConnectSourceIdentityEvidence connectSourceIdentity( + AccountConnectTokenIssuanceIdentity identity, + AccountCommittedConnectSourceReader.OriginalSourceEvidence evidence) { + Map claims = evidence.originalSourceClaims(); + Map gateway = evidence.gatewayContextClaims(); + return new ConnectSourceIdentityEvidence( + evidence.operationId(), + identity.requestId(), + AccountJoinDigest.tokenHash(identity.connectScopeId()), + requireText(claims, "jti"), + evidence.sourceTokenHash(), + evidence.responseEnvelopeKeyId(), + null, + evidence.gatewayKeyId(), + requireInteger(claims, "iat"), + requireInteger(claims, "exp"), + requireInteger(gateway, "verifiedAt"), + requireInteger(gateway, "expiresAt")); + } + + private static SelectedTargetEvidence selectedTarget(Map claims) { + return new SelectedTargetEvidence( + requireText(claims, "accountId"), + requireText(claims, "tenantId"), + requireText(claims, "realmId"), + requireText(claims, "worldSlug"), + requireText(claims, "realmSlug"), + requireText(claims, "playableStateNamespaceId"), + requireText(claims, "playableStateScope"), + requireText(claims, "gameInstanceId"), + requireInteger(claims, "catalogRevision"), + requireInteger(claims, "pointerVersion"), + optionalText(claims, "playtestLifecycleId"), + optionalInteger(claims, "playtestStateGeneration")); + } + + private static void requireSameCurrentReadback( + AccountCommittedConnectSourceReader.OriginalSourceEvidence first, + AccountCommittedConnectSourceReader.OriginalSourceEvidence last) { + if (!first.operationId().equals(last.operationId()) + || !first.responseEnvelopeKeyId().equals(last.responseEnvelopeKeyId()) + || !MessageDigest.isEqual(first.sourceTokenHash(), last.sourceTokenHash()) + || !first.gatewayKeyId().equals(last.gatewayKeyId()) + || !first.originalSourceClaims().equals(last.originalSourceClaims()) + || !first.gatewayContextClaims().equals(last.gatewayContextClaims())) { + throw new IllegalStateException("Fresh Account source changed during history correlation"); + } + } + + private static String requireText(Map claims, String field) { + Object value = claims.get(field); + if (!(value instanceof String text) || text.isBlank()) { + throw new IllegalStateException("Verified connect source is missing a required target fact"); + } + return text; + } + + private static String optionalText(Map claims, String field) { + if (!claims.containsKey(field)) { + return null; + } + return requireText(claims, field); + } + + private static BigInteger requireInteger(Map claims, String field) { + Object value = claims.get(field); + if (!(value instanceof BigInteger integer)) { + throw new IllegalStateException("Verified connect source is missing a required time fact"); + } + return integer; + } + + private static BigInteger optionalInteger(Map claims, String field) { + if (!claims.containsKey(field)) { + return null; + } + return requireInteger(claims, field); + } + + private void requireGameSessionPeer() { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !expectedGameSessionPeerUri.equals(peer.uri())) { + throw new AdminAuthorizationException( + "Stored bare LOGIN history readback requires the exact Game Session workload identity"); + } + } + + private static byte[] requireDigest(byte[] value, String fieldName) { + Objects.requireNonNull(value, fieldName); + if (value.length != 32) { + throw new IllegalArgumentException(fieldName + " must be 32 bytes"); + } + return value.clone(); + } + + private static byte[] sha256(byte[] bytes) { + try { + return MessageDigest.getInstance("SHA-256").digest(bytes); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 is unavailable", exception); + } + } + + private static void wipe(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + private record HistoricalReadback( + HistoricalStoredBareLoginEvidence evidence, HistoricalCommittedSourceEvidence source) {} + + /** Immutable provenance facts only; no original result, JWT, Gateway context, or claims. */ + public record HistoricalStoredBareLoginEvidence( + UUID exchangeOperationId, + UUID sourceConnectOperationId, + long accountId, + long tenantId, + String requestId, + String connectScopeHash, + int requestDigestVersion, + byte[] requestDigest, + byte[] originalResultHash, + byte[] sourceConnectTokenHash, + String responseEnvelopeKeyId, + String sourceResponseEnvelopeKeyId, + String accountSourceKeyId, + String gatewayKeyId, + java.math.BigInteger signedGatewayVerifiedAt, + java.math.BigInteger signedGatewayExpiresAt) { + public HistoricalStoredBareLoginEvidence { + Objects.requireNonNull(exchangeOperationId, "exchangeOperationId"); + Objects.requireNonNull(sourceConnectOperationId, "sourceConnectOperationId"); + if (accountId <= 0 || tenantId <= 0 || requestDigestVersion != 1) { + throw new IllegalArgumentException("Stored bare LOGIN provenance identity is invalid"); + } + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(connectScopeHash, "connectScopeHash"); + requestDigest = requireDigest(requestDigest, "request digest"); + originalResultHash = requireDigest(originalResultHash, "original result hash"); + sourceConnectTokenHash = requireDigest(sourceConnectTokenHash, "source connect-token hash"); + Objects.requireNonNull(responseEnvelopeKeyId, "responseEnvelopeKeyId"); + Objects.requireNonNull(sourceResponseEnvelopeKeyId, "sourceResponseEnvelopeKeyId"); + Objects.requireNonNull(accountSourceKeyId, "accountSourceKeyId"); + Objects.requireNonNull(gatewayKeyId, "gatewayKeyId"); + Objects.requireNonNull(signedGatewayVerifiedAt, "signedGatewayVerifiedAt"); + Objects.requireNonNull(signedGatewayExpiresAt, "signedGatewayExpiresAt"); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] originalResultHash() { + return originalResultHash.clone(); + } + + @Override + public byte[] sourceConnectTokenHash() { + return sourceConnectTokenHash.clone(); + } + + @Override + public String toString() { + return "HistoricalStoredBareLoginEvidence[exchangeOperationId=" + + exchangeOperationId + + ", sourceConnectOperationId=" + + sourceConnectOperationId + + ", requestId=, result=, originalGateway=]"; + } + } + + /** Separate original/fresh V35 identities and selected target; not an authorization result. */ + public record HistoricalStoredBareLoginCorrelationEvidence( + HistoricalStoredBareLoginEvidence originalExchange, + ConnectSourceIdentityEvidence originalConnectSource, + ConnectSourceIdentityEvidence freshConnectSource, + SelectedTargetEvidence selectedTarget) { + public HistoricalStoredBareLoginCorrelationEvidence { + Objects.requireNonNull(originalExchange, "originalExchange"); + Objects.requireNonNull(originalConnectSource, "originalConnectSource"); + Objects.requireNonNull(freshConnectSource, "freshConnectSource"); + Objects.requireNonNull(selectedTarget, "selectedTarget"); + if (!originalExchange.sourceConnectOperationId().equals(originalConnectSource.operationId()) + || originalConnectSource.operationId().equals(freshConnectSource.operationId())) { + throw new IllegalArgumentException("Historical/fresh source identities are not distinct"); + } + } + + @Override + public String toString() { + return "HistoricalStoredBareLoginCorrelationEvidence[originalExchange=, " + + "originalConnectSource=, freshConnectSource=, " + + "selectedTarget=]"; + } + } + + /** Immutable source identity facts; connect scope is represented only by its digest. */ + public record ConnectSourceIdentityEvidence( + UUID operationId, + String requestId, + String connectScopeHash, + String tokenIdentity, + byte[] sourceTokenHash, + String responseEnvelopeKeyId, + String accountSourceKeyId, + String gatewayKeyId, + BigInteger sourceIssuedAt, + BigInteger sourceExpiresAt, + BigInteger gatewayVerifiedAt, + BigInteger gatewayExpiresAt) { + public ConnectSourceIdentityEvidence { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(connectScopeHash, "connectScopeHash"); + Objects.requireNonNull(tokenIdentity, "tokenIdentity"); + sourceTokenHash = requireDigest(sourceTokenHash, "source token hash"); + Objects.requireNonNull(responseEnvelopeKeyId, "responseEnvelopeKeyId"); + Objects.requireNonNull(gatewayKeyId, "gatewayKeyId"); + Objects.requireNonNull(sourceIssuedAt, "sourceIssuedAt"); + Objects.requireNonNull(sourceExpiresAt, "sourceExpiresAt"); + Objects.requireNonNull(gatewayVerifiedAt, "gatewayVerifiedAt"); + Objects.requireNonNull(gatewayExpiresAt, "gatewayExpiresAt"); + } + + @Override + public byte[] sourceTokenHash() { + return sourceTokenHash.clone(); + } + + @Override + public String toString() { + return "ConnectSourceIdentityEvidence[operationId=" + + operationId + + ", request=, scope=, tokenIdentity=, " + + "sourceToken=, gatewayContext=]"; + } + } + + /** The complete canonical selected-target projection, excluding per-issuance identity/time. */ + public record SelectedTargetEvidence( + String accountId, + String tenantId, + String realmId, + String worldSlug, + String realmSlug, + String playableStateNamespaceId, + String playableStateScope, + String gameInstanceId, + BigInteger catalogRevision, + BigInteger pointerVersion, + String playtestLifecycleId, + BigInteger playtestStateGeneration) { + public SelectedTargetEvidence { + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(realmId, "realmId"); + Objects.requireNonNull(worldSlug, "worldSlug"); + Objects.requireNonNull(realmSlug, "realmSlug"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(playableStateScope, "playableStateScope"); + Objects.requireNonNull(gameInstanceId, "gameInstanceId"); + Objects.requireNonNull(catalogRevision, "catalogRevision"); + Objects.requireNonNull(pointerVersion, "pointerVersion"); + if ((playtestLifecycleId == null) != (playtestStateGeneration == null)) { + throw new IllegalArgumentException("Playtest target lifecycle and generation differ"); + } + } + + @Override + public String toString() { + return "SelectedTargetEvidence[account=, tenant=, realm=, " + + "world=, runtime=, revision=]"; + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java index 0b1e04e981..1e37c1cc39 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountCommittedConnectSourceReaderIntegrationTest.java @@ -33,6 +33,9 @@ import java.util.function.Supplier; import net.firedevops.firemud.accountservice.dto.AccountJoinDigest; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeRepository; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginResponseEnvelope; import net.firedevops.firemud.accountservice.repository.AccountCommittedConnectSource; import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceOperation.Lifecycle; @@ -49,8 +52,14 @@ import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException.Failure; import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.accountservice.security.BareLoginRecoveryPayload; import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader.HistoricalCommittedSourceEvidence; import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader.OriginalSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountStoredBareLoginRecoveryReader; +import net.firedevops.firemud.accountservice.service.AccountStoredBareLoginRecoveryReader.HistoricalStoredBareLoginCorrelationEvidence; +import net.firedevops.firemud.accountservice.service.AccountStoredBareLoginRecoveryReader.HistoricalStoredBareLoginEvidence; +import net.firedevops.firemud.accountservice.service.AccountStoredBareLoginRecoveryReader.SelectedTargetEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.GatewayConnectContextCodec; @@ -130,6 +139,592 @@ void readsExactCommittedOriginalSourceAndLostResultWithoutMutation() throws Exce assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); } + @Test + void readsExpiredCommittedSourceOnlyThroughHistoricalEvidenceWithoutMutation() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + AccountCommittedConnectSource committed = + inTransaction( + prepared.db().transaction(), + () -> + prepared + .db() + .issuanceRepository() + .readCommittedResponseEnvelope(source.identity()) + .orElseThrow()); + Snapshot before = sourceSnapshot(prepared, source.identity()); + + // Both the Account token and its projected Gateway context expire after twenty seconds. + prepared.clock().advance(Duration.ofSeconds(21)); + HistoricalCommittedSourceEvidence historical = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .readHistorical(source.identity(), source.gatewayEnvelope()))); + + assertThat(historical.operationId()).isEqualTo(committed.operation().operationId()); + assertThat(historical.responseEnvelopeKeyId()) + .isEqualTo(committed.responseEnvelope().envelope().keyId()); + assertThat(historical.sourceTokenHash()).containsExactly(committed.operation().tokenHash()); + assertThat(historical.accountSourceKeyId()).isEqualTo(ACCOUNT_KEY_ID); + assertThat(historical.gatewayKeyId()).isEqualTo(GATEWAY_KEY_ID); + assertThat(historical.originalSourceClaims()).isEqualTo(source.sourceClaims()); + assertThat(historical.historicalGatewayClaims()).isEqualTo(source.gatewayClaims()); + assertThat(historical.originalSourceClaims().get("jti")).isEqualTo(source.tokenIdentity()); + assertThat(historical.toString()) + .doesNotContain(source.identity().connectScopeId()) + .doesNotContain(source.tokenIdentity()) + .doesNotContain(source.gatewayEnvelope()); + byte[] modifiedHash = historical.sourceTokenHash(); + modifiedHash[0] ^= 0x01; + assertThat(historical.sourceTokenHash()).containsExactly(committed.operation().tokenHash()); + assertThatThrownBy(() -> historical.originalSourceClaims().put("extra", "value")) + .isInstanceOf(UnsupportedOperationException.class); + assertThatThrownBy( + () -> + ((Map) historical.originalSourceClaims().get("authorityTuple")) + .put("extra", BigInteger.ONE)) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); + + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .read(source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Gateway context is expired"); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); + } + + @Test + void readsCommittedStoredFrameAndOriginalSourceAfterGatewayContextExpiryWithoutMutation() + throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + byte[] originalResult = "opaque-original-bare-login-result".getBytes(StandardCharsets.UTF_8); + StoredBareLoginFixture stored = + storeBareLoginFrame(prepared, source, source.gatewayEnvelope(), originalResult, null); + AccountCommittedConnectSource committedSource = + inTransaction( + prepared.db().transaction(), + () -> + prepared + .db() + .issuanceRepository() + .readCommittedResponseEnvelope(source.identity()) + .orElseThrow()); + Snapshot sourceBefore = sourceSnapshot(prepared, source.identity()); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + AccountStoredBareLoginRecoveryReader reader = storedReader(prepared); + + prepared.clock().advance(Duration.ofSeconds(21)); + HistoricalStoredBareLoginEvidence first = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> reader.readHistorical(stored.identity(), stored.requestDigest()))); + HistoricalStoredBareLoginEvidence reread = + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> reader.readHistorical(stored.identity(), stored.requestDigest()))); + + assertThat(first.exchangeOperationId()).isEqualTo(stored.operationId()); + assertThat(first.sourceConnectOperationId()) + .isEqualTo(stored.identity().sourceConnectOperationId()); + assertThat(first.accountId()).isEqualTo(source.identity().accountId()); + assertThat(first.tenantId()).isEqualTo(source.identity().tenantId()); + assertThat(first.requestId()).isEqualTo(stored.identity().requestId()); + assertThat(first.requestDigestVersion()).isEqualTo(1); + assertThat(first.connectScopeHash()) + .isEqualTo(AccountJoinDigest.tokenHash(source.identity().connectScopeId())); + assertThat(first.requestDigest()).containsExactly(stored.requestDigest()); + assertThat(first.originalResultHash()).containsExactly(sha256(originalResult)); + assertThat(first.sourceConnectTokenHash()) + .containsExactly(committedSource.operation().tokenHash()); + assertThat(first.responseEnvelopeKeyId()).isEqualTo("test-key"); + assertThat(first.sourceResponseEnvelopeKeyId()).isEqualTo("test-key"); + assertThat(first.accountSourceKeyId()).isEqualTo(ACCOUNT_KEY_ID); + assertThat(first.gatewayKeyId()).isEqualTo(GATEWAY_KEY_ID); + assertThat(first.signedGatewayVerifiedAt()).isEqualTo(source.gatewayClaims().get("verifiedAt")); + assertThat(first.signedGatewayExpiresAt()).isEqualTo(source.gatewayClaims().get("expiresAt")); + assertThat(first.exchangeOperationId()).isEqualTo(reread.exchangeOperationId()); + assertThat(first.sourceConnectOperationId()).isEqualTo(reread.sourceConnectOperationId()); + assertThat(first.originalResultHash()).containsExactly(reread.originalResultHash()); + byte[] changedRequestDigest = first.requestDigest(); + changedRequestDigest[0] ^= 0x01; + assertThat(first.requestDigest()).containsExactly(stored.requestDigest()); + byte[] changedSourceHash = first.sourceConnectTokenHash(); + changedSourceHash[0] ^= 0x01; + assertThat(first.sourceConnectTokenHash()) + .containsExactly(committedSource.operation().tokenHash()); + assertThat(first.toString()) + .doesNotContain(new String(originalResult, StandardCharsets.UTF_8)) + .doesNotContain(source.gatewayEnvelope()) + .doesNotContain(source.identity().connectScopeId()); + byte[] changedHash = first.originalResultHash(); + changedHash[0] ^= 0x01; + assertThat(first.originalResultHash()).containsExactly(sha256(originalResult)); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(sourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + } + + @Test + void correlatesExpiredOriginalFrameWithSeparateFreshCommittedSourceWithoutMutation() + throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceTarget target = + new SourceTarget( + "world", + "realm", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + BigInteger.valueOf(3)); + SourceFixture original = newSourceWithTarget(prepared, target); + byte[] originalResult = "opaque-original-result".getBytes(StandardCharsets.UTF_8); + StoredBareLoginFixture stored = + storeBareLoginFrame(prepared, original, original.gatewayEnvelope(), originalResult, null); + Snapshot originalSourceBefore = sourceSnapshot(prepared, original.identity()); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + + prepared.clock().advance(Duration.ofSeconds(21)); + long now = prepared.clock().instant().getEpochSecond(); + assertThat(((BigInteger) original.gatewayClaims().get("expiresAt")).longValue()) + .isLessThan(now); + SourceFixture fresh = newSourceWithTarget(prepared, target); + Snapshot freshSourceBefore = sourceSnapshot(prepared, fresh.identity()); + + AccountStoredBareLoginRecoveryReader reader = storedReader(prepared); + HistoricalStoredBareLoginCorrelationEvidence first = + readCorrelation(reader, prepared, stored, fresh.identity(), fresh.gatewayEnvelope()); + HistoricalStoredBareLoginCorrelationEvidence reread = + readCorrelation(reader, prepared, stored, fresh.identity(), fresh.gatewayEnvelope()); + + assertThat(first.originalExchange().exchangeOperationId()).isEqualTo(stored.operationId()); + assertThat(first.originalExchange().requestId()).isEqualTo(stored.identity().requestId()); + assertThat(first.originalExchange().requestDigest()).containsExactly(stored.requestDigest()); + assertThat(first.originalExchange().connectScopeHash()) + .isEqualTo(AccountJoinDigest.tokenHash(stored.identity().connectScopeId())); + assertThat(first.originalExchange().originalResultHash()) + .containsExactly(sha256(originalResult)); + assertThat(first.originalConnectSource().operationId()) + .isEqualTo(stored.identity().sourceConnectOperationId()); + assertThat(first.freshConnectSource().operationId()).isEqualTo(freshSourceBefore.operationId()); + assertThat(first.freshConnectSource().operationId()) + .isNotEqualTo(first.originalConnectSource().operationId()); + assertThat(first.originalConnectSource().requestId()) + .isEqualTo(original.identity().requestId()); + assertThat(first.freshConnectSource().requestId()).isEqualTo(fresh.identity().requestId()); + assertThat(first.originalConnectSource().requestId()) + .isNotEqualTo(first.freshConnectSource().requestId()); + assertThat(first.originalConnectSource().connectScopeHash()) + .isEqualTo(AccountJoinDigest.tokenHash(original.identity().connectScopeId())); + assertThat(first.freshConnectSource().connectScopeHash()) + .isEqualTo(AccountJoinDigest.tokenHash(fresh.identity().connectScopeId())); + assertThat(first.originalConnectSource().connectScopeHash()) + .isNotEqualTo(first.freshConnectSource().connectScopeHash()); + assertThat(first.originalConnectSource().tokenIdentity()).isEqualTo(original.tokenIdentity()); + assertThat(first.freshConnectSource().tokenIdentity()).isEqualTo(fresh.tokenIdentity()); + assertThat(first.originalConnectSource().sourceExpiresAt()).isLessThan(BigInteger.valueOf(now)); + assertThat(first.freshConnectSource().gatewayExpiresAt()) + .isGreaterThan(BigInteger.valueOf(now)); + assertThat(first.selectedTarget()) + .isEqualTo( + new SelectedTargetEvidence( + (String) original.sourceClaims().get("accountId"), + (String) original.sourceClaims().get("tenantId"), + (String) original.sourceClaims().get("realmId"), + (String) original.sourceClaims().get("worldSlug"), + (String) original.sourceClaims().get("realmSlug"), + (String) original.sourceClaims().get("playableStateNamespaceId"), + (String) original.sourceClaims().get("playableStateScope"), + (String) original.sourceClaims().get("gameInstanceId"), + (BigInteger) original.sourceClaims().get("catalogRevision"), + (BigInteger) original.sourceClaims().get("pointerVersion"), + (String) original.sourceClaims().get("playtestLifecycleId"), + (BigInteger) original.sourceClaims().get("playtestStateGeneration"))); + assertThat(first.selectedTarget()).isEqualTo(reread.selectedTarget()); + assertThat(first.originalConnectSource().sourceTokenHash()) + .containsExactly(reread.originalConnectSource().sourceTokenHash()); + byte[] mutatedHash = first.freshConnectSource().sourceTokenHash(); + mutatedHash[0] ^= 0x01; + assertThat(first.freshConnectSource().sourceTokenHash()) + .containsExactly(reread.freshConnectSource().sourceTokenHash()); + assertThat(first.toString()) + .doesNotContain(new String(originalResult, StandardCharsets.UTF_8)) + .doesNotContain(original.gatewayEnvelope()) + .doesNotContain(fresh.gatewayEnvelope()); + assertThat(sourceSnapshot(prepared, original.identity())).isEqualTo(originalSourceBefore); + assertThat(sourceSnapshot(prepared, fresh.identity())).isEqualTo(freshSourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + + assertReadRejected( + prepared.reader(), + prepared, + original, + IllegalArgumentException.class, + "Gateway context is expired"); + } + + @Test + void correlationRejectsExpiredFreshContextAndReissuedContextForOriginalSource() throws Exception { + PreparedAccount expiredPrepared = newPreparedAccount(); + SourceFixture expiredOriginal = newSource(expiredPrepared, SourceState.COMMITTED); + StoredBareLoginFixture expiredStored = + storeBareLoginFrame( + expiredPrepared, + expiredOriginal, + expiredOriginal.gatewayEnvelope(), + "opaque-result".getBytes(StandardCharsets.UTF_8), + null); + SourceFixture expiredFresh = newSource(expiredPrepared, SourceState.COMMITTED); + expiredPrepared.clock().advance(Duration.ofSeconds(21)); + assertCorrelationReadRejected( + expiredPrepared, + storedReader(expiredPrepared), + expiredStored, + expiredFresh.identity(), + expiredFresh.gatewayEnvelope(), + IllegalArgumentException.class, + "Gateway context is expired"); + + PreparedAccount samePrepared = newPreparedAccount(); + SourceFixture sameSource = + newSource( + samePrepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, false, true, false)); + StoredBareLoginFixture sameStored = + storeBareLoginFrame( + samePrepared, + sameSource, + sameSource.gatewayEnvelope(), + "opaque-result".getBytes(StandardCharsets.UTF_8), + null); + samePrepared.clock().advance(Duration.ofSeconds(3)); + String currentContextForSameSource = resignCurrentGatewayContext(samePrepared, sameSource); + assertCorrelationReadRejected( + samePrepared, + storedReader(samePrepared), + sameStored, + sameSource.identity(), + currentContextForSameSource, + IllegalStateException.class, + "separate committed Account source operation"); + } + + @Test + void correlationRequiresExactAccountTenantAndCompleteSelectedTarget() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceTarget originalTarget = + new SourceTarget( + "world", + "realm", + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + BigInteger.valueOf(3)); + SourceFixture original = newSourceWithTarget(prepared, originalTarget); + StoredBareLoginFixture stored = + storeBareLoginFrame( + prepared, + original, + original.gatewayEnvelope(), + "opaque-result".getBytes(StandardCharsets.UTF_8), + null); + AccountStoredBareLoginRecoveryReader reader = storedReader(prepared); + + SourceFixture freshMatchingTarget = newSourceWithTarget(prepared, originalTarget); + byte[] changedDigest = stored.requestDigest(); + changedDigest[0] ^= 0x01; + assertCorrelationReadRejected( + prepared, + reader, + stored, + changedDigest, + freshMatchingTarget.identity(), + freshMatchingTarget.gatewayEnvelope(), + AccountBareLoginExchangeRepository.IdempotencyConflictException.class, + "different digest"); + + AccountBareLoginExchangeIdentity changedRequest = + new AccountBareLoginExchangeIdentity( + stored.identity().sourceConnectOperationId(), + stored.identity().accountId(), + stored.identity().tenantId(), + stored.identity().connectScopeId(), + stored.identity().requestId() + "-different"); + assertCorrelationReadRejected( + prepared, + reader, + stored, + changedRequest, + stored.requestDigest(), + freshMatchingTarget.identity(), + freshMatchingTarget.gatewayEnvelope(), + IllegalStateException.class, + "exchange identity was reused with different source or binding"); + + SourceFixture changedWorld = + newSourceWithTarget(prepared, new SourceTarget("other-world", "realm", null, null)); + assertCorrelationReadRejected( + prepared, + reader, + stored, + stored.requestDigest(), + changedWorld.identity(), + changedWorld.gatewayEnvelope(), + IllegalStateException.class, + "exact original Account target"); + + AccountConnectTokenIssuanceIdentity wrongPlayer = + new AccountConnectTokenIssuanceIdentity( + original.identity().accountId() + 1, + original.identity().tenantId(), + "fresh-scope-player", + "fresh-request-player"); + assertCorrelationIdentityRejected(prepared, reader, stored, wrongPlayer); + AccountConnectTokenIssuanceIdentity wrongTenant = + new AccountConnectTokenIssuanceIdentity( + original.identity().accountId(), + original.identity().tenantId() + 1, + "fresh-scope-tenant", + "fresh-request-tenant"); + assertCorrelationIdentityRejected(prepared, reader, stored, wrongTenant); + + SourceFixture changedLifecycle = + newSourceWithTarget( + prepared, + new SourceTarget( + "world", + "realm", + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + BigInteger.valueOf(3))); + assertCorrelationReadRejected( + prepared, + reader, + stored, + changedLifecycle.identity(), + changedLifecycle.gatewayEnvelope(), + IllegalStateException.class, + "exact original Account target"); + + SourceFixture changedGeneration = + newSourceWithTarget( + prepared, + new SourceTarget( + "world", "realm", originalTarget.playtestLifecycleId(), BigInteger.valueOf(4))); + assertCorrelationReadRejected( + prepared, + reader, + stored, + changedGeneration.identity(), + changedGeneration.gatewayEnvelope(), + IllegalStateException.class, + "exact original Account target"); + } + + @Test + void storedHistoryRejectsChangedDigestSourceContextResultHashAndKey() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + byte[] result = "opaque-original-result".getBytes(StandardCharsets.UTF_8); + StoredBareLoginFixture stored = + storeBareLoginFrame(prepared, source, source.gatewayEnvelope(), result, null); + byte[] wrongRequestDigest = stored.requestDigest(); + wrongRequestDigest[0] ^= 0x01; + assertStoredReadRejected( + storedReader(prepared), + prepared, + stored, + wrongRequestDigest, + AccountBareLoginExchangeRepository.IdempotencyConflictException.class, + "different digest"); + + SourceFixture linkedSource = newSource(prepared, SourceState.COMMITTED); + SourceFixture sameScopeOtherSource = + newSource( + prepared, + SourceState.COMMITTED, + SourceOptions.NORMAL, + linkedSource.identity().connectScopeId()); + Snapshot contextSourceBefore = sourceSnapshot(prepared, sameScopeOtherSource.identity()); + StoredBareLoginFixture linkedToWrongSource = + storeBareLoginFrame( + prepared, linkedSource, sameScopeOtherSource.gatewayEnvelope(), result, null); + assertStoredReadRejected( + storedReader(prepared), + prepared, + linkedToWrongSource, + linkedToWrongSource.requestDigest(), + IllegalStateException.class, + "does not match its original Gateway context"); + assertThat(sourceSnapshot(prepared, sameScopeOtherSource.identity())) + .isEqualTo(contextSourceBefore); + + SourceFixture changedContextSource = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, true, false, false, false)); + StoredBareLoginFixture changedContext = + storeBareLoginFrame( + prepared, changedContextSource, changedContextSource.gatewayEnvelope(), result, null); + assertStoredReadRejected( + storedReader(prepared), + prepared, + changedContext, + changedContext.requestDigest(), + IllegalArgumentException.class, + "invalid Account gameplay-connect source JWT"); + + byte[] differentStoredHash = sha256("different-result".getBytes(StandardCharsets.UTF_8)); + SourceFixture resultHashSource = newSource(prepared, SourceState.COMMITTED); + StoredBareLoginFixture changedResultHash = + storeBareLoginFrame( + prepared, + resultHashSource, + resultHashSource.gatewayEnvelope(), + result, + differentStoredHash); + assertStoredReadRejected( + storedReader(prepared), + prepared, + changedResultHash, + changedResultHash.requestDigest(), + IllegalStateException.class, + "result hash does not match"); + + SourceFixture oldPayloadSource = newSource(prepared, SourceState.COMMITTED); + StoredBareLoginFixture oldOpaquePayload = + storeOpaqueBareLoginPayload( + prepared, + oldPayloadSource, + "legacy unframed response payload".getBytes(StandardCharsets.UTF_8)); + assertStoredReadRejected( + storedReader(prepared), + prepared, + oldOpaquePayload, + oldOpaquePayload.requestDigest(), + IllegalArgumentException.class, + "payload header is invalid"); + + assertStoredReadRejected( + storedReader(prepared, differentConnectPurposeKey()), + prepared, + stored, + stored.requestDigest(), + AccountEnvelopeCryptoException.class, + "AUTHENTICATION_FAILED"); + } + + @Test + void historicalReadRejectsRequestTargetHashAndTokenIdentityMismatches() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture source = newSource(prepared, SourceState.COMMITTED); + SourceFixture wrongHash = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, true, false, false, false, false, false)); + SourceFixture wrongJti = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, true, false, false, false, false)); + SourceFixture wrongTarget = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, true, false, false, false)); + + assertHistoricalReadRejected(prepared, wrongHash, IllegalStateException.class, "token hash"); + assertHistoricalReadRejected(prepared, wrongJti, IllegalStateException.class, "token identity"); + // Source verification deliberately sanitizes signature/profile/projection failure details. + assertHistoricalReadRejected( + prepared, + wrongTarget, + IllegalArgumentException.class, + "invalid Account gameplay-connect source JWT"); + + Snapshot before = sourceSnapshot(prepared, source.identity()); + AccountConnectTokenIssuanceIdentity wrongRequestIdentity = + new AccountConnectTokenIssuanceIdentity( + source.identity().accountId(), + source.identity().tenantId(), + source.identity().connectScopeId() + "-different", + source.identity().requestId()); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + prepared + .reader() + .readHistorical( + wrongRequestIdentity, source.gatewayEnvelope())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("request identity"); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); + } + + @Test + void historicalReadRequiresCommittedSuccess() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture absent = newSource(prepared, SourceState.ABSENT); + SourceFixture pending = newSource(prepared, SourceState.PENDING); + SourceFixture failed = newSource(prepared, SourceState.FAILED); + + assertHistoricalReadRejected( + prepared, absent, IllegalStateException.class, "Committed Account source is absent"); + assertHistoricalReadRejected( + prepared, pending, IllegalStateException.class, "not a complete committed success"); + assertHistoricalReadRejected( + prepared, failed, IllegalStateException.class, "not a complete committed success"); + } + + @Test + void historicalReadRequiresRegisteredGatewayAndAccountSigningKeys() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture unknownGateway = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, true, false, false)); + SourceFixture unknownAccount = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(true, false, false, false, false, false, false)); + + assertHistoricalReadRejected( + prepared, + unknownGateway, + IllegalArgumentException.class, + "unknown Gateway verification key"); + assertHistoricalReadRejected( + prepared, + unknownAccount, + IllegalArgumentException.class, + "invalid Account gameplay-connect source JWT"); + } + @Test void requiresExactGameSessionCallerAndRegisteredGatewayAndAccountKeys() throws Exception { PreparedAccount prepared = newPreparedAccount(); @@ -278,6 +873,11 @@ void rejectsUnmappedAndChangedRetainedTenantEvidence() throws Exception { unmappedTenant, IllegalStateException.class, "approved Account tenant association is absent"); + assertHistoricalReadRejected( + prepared, + unmappedTenant, + IllegalStateException.class, + "approved Account tenant association is absent"); SourceFixture changedRetainedEvidence = newSource(prepared, SourceState.COMMITTED); inTransaction( @@ -296,6 +896,11 @@ void rejectsUnmappedAndChangedRetainedTenantEvidence() throws Exception { changedRetainedEvidence, IllegalStateException.class, "approved Account source evidence differs from retained rows"); + assertHistoricalReadRejected( + prepared, + changedRetainedEvidence, + IllegalStateException.class, + "approved Account source evidence differs from retained rows"); } @Test @@ -346,11 +951,34 @@ void rejectsWrongPurposeAndWrongPurposeKeyForStoredEnvelope() throws Exception { source, AccountEnvelopeCryptoException.class, "AUTHENTICATION_FAILED"); + assertHistoricalReadRejected( + wrongKeyReader, + prepared, + source, + AccountEnvelopeCryptoException.class, + "AUTHENTICATION_FAILED"); + + AccountCommittedConnectSourceReader missingRingReader = + readerWithCrypto(prepared, missingKeyRingCrypto()); + assertHistoricalReadRejected( + missingRingReader, + prepared, + source, + AccountEnvelopeCryptoException.class, + "KEY_RING_UNAVAILABLE"); } @Test void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() throws Exception { PreparedAccount prepared = newPreparedAccount(); + SourceFixture original = newSource(prepared, SourceState.COMMITTED); + StoredBareLoginFixture stored = + storeBareLoginFrame( + prepared, + original, + original.gatewayEnvelope(), + "opaque-result".getBytes(StandardCharsets.UTF_8), + null); SourceFixture source = newSource( prepared, @@ -384,7 +1012,7 @@ void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() thro })); try { assertThat(accountRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); - Future reader = + Future reader = executor.submit( () -> withPeer( @@ -396,9 +1024,12 @@ void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() thro readerBackendPid.set( requirePositiveBackendPid(prepared.db().dsl())); readerBackendIdentified.countDown(); - return prepared - .reader() - .read(source.identity(), source.gatewayEnvelope()); + return storedReader(prepared) + .readCorrelation( + stored.identity(), + stored.requestDigest(), + source.identity(), + source.gatewayEnvelope()); }))); if (!readerBackendIdentified.await(5, TimeUnit.SECONDS)) { try { @@ -442,6 +1073,107 @@ void doesNotReturnWhenAccountFenceWaitOutlivesTheUnchangedGatewayDeadline() thro } } + @Test + void correlationRechecksFreshDeadlineAfterStoredFrameReadWait() throws Exception { + PreparedAccount prepared = newPreparedAccount(); + SourceFixture original = newSource(prepared, SourceState.COMMITTED); + StoredBareLoginFixture stored = + storeBareLoginFrame( + prepared, + original, + original.gatewayEnvelope(), + "opaque-result".getBytes(StandardCharsets.UTF_8), + null); + SourceFixture fresh = + newSource( + prepared, + SourceState.COMMITTED, + new SourceOptions(false, false, false, false, false, true, false)); + Snapshot originalBefore = sourceSnapshot(prepared, original.identity()); + Snapshot freshBefore = sourceSnapshot(prepared, fresh.identity()); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + + CountDownLatch envelopeTableLocked = new CountDownLatch(1); + CountDownLatch releaseEnvelopeTable = new CountDownLatch(1); + CountDownLatch readerBackendIdentified = new CountDownLatch(1); + AtomicInteger blockerBackendPid = new AtomicInteger(); + AtomicInteger readerBackendPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + Future blocker = + executor.submit( + () -> + inTransaction( + prepared.db().transaction(), + () -> { + blockerBackendPid.set(requirePositiveBackendPid(prepared.db().dsl())); + prepared + .db() + .dsl() + .execute( + "LOCK TABLE account_bare_login_response_envelopes " + + "IN ACCESS EXCLUSIVE MODE"); + envelopeTableLocked.countDown(); + if (!await(releaseEnvelopeTable, 20, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "V37 envelope-table blocker was not released"); + } + return null; + })); + try { + assertThat(envelopeTableLocked.await(5, TimeUnit.SECONDS)).isTrue(); + Future reader = + executor.submit( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> { + readerBackendPid.set( + requirePositiveBackendPid(prepared.db().dsl())); + readerBackendIdentified.countDown(); + return storedReader(prepared) + .readCorrelation( + stored.identity(), + stored.requestDigest(), + fresh.identity(), + fresh.gatewayEnvelope()); + }))); + assertThat(readerBackendIdentified.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat( + awaitRelationLockBlock( + prepared.db().dsl(), + readerBackendPid.get(), + blockerBackendPid.get(), + Duration.ofSeconds(5))) + .as( + "correlation passed its first strict source read and reached stored-envelope readback") + .isTrue(); + + prepared.clock().advance(Duration.ofSeconds(3)); + releaseEnvelopeTable.countDown(); + assertThatThrownBy(() -> reader.get(10, TimeUnit.SECONDS)) + .satisfies( + thrown -> { + Throwable cause = thrown; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertThat(cause) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Gateway context is expired"); + }); + assertThat(sourceSnapshot(prepared, original.identity())).isEqualTo(originalBefore); + assertThat(sourceSnapshot(prepared, fresh.identity())).isEqualTo(freshBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + } finally { + releaseEnvelopeTable.countDown(); + blocker.get(10, TimeUnit.SECONDS); + executor.shutdownNow(); + } + } + private PreparedAccount newPreparedAccount() throws Exception { String schema = "account_source_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16); @@ -522,6 +1254,8 @@ private PreparedAccount newPreparedAccount() throws Exception { Map.of(GATEWAY_KEY_ID, gatewayKeyPair.getPublic()); AccountConnectTokenIssuanceRepository issuanceRepository = new AccountConnectTokenIssuanceRepository(dsl); + AccountBareLoginExchangeRepository bareLoginExchangeRepository = + new AccountBareLoginExchangeRepository(dsl); AccountRepository accountRepository = new AccountRepository(dsl); AccountTenantIdentityResolver tenantResolver = new AccountTenantIdentityResolver(associations, sourceEvidence, WORKLOAD_NAMESPACE); @@ -537,7 +1271,9 @@ private PreparedAccount newPreparedAccount() throws Exception { gatewayKeys, clock, WORKLOAD_NAMESPACE); - TestContext db = new TestContext(dsl, transaction, issuanceRepository, envelopeCrypto); + TestContext db = + new TestContext( + dsl, transaction, issuanceRepository, bareLoginExchangeRepository, envelopeCrypto); return new PreparedAccount( db, accountId, @@ -565,6 +1301,45 @@ private SourceFixture newSource( PreparedAccount prepared, SourceState state, SourceOptions options) throws Exception { String requestId = "source-request-" + UUID.randomUUID(); String connectScopeId = "source-scope-" + UUID.randomUUID(); + return newSource(prepared, state, options, requestId, connectScopeId); + } + + private SourceFixture newSource( + PreparedAccount prepared, SourceState state, SourceOptions options, String connectScopeId) + throws Exception { + String requestId = "source-request-" + UUID.randomUUID(); + return newSource(prepared, state, options, requestId, connectScopeId); + } + + private SourceFixture newSource( + PreparedAccount prepared, + SourceState state, + SourceOptions options, + String requestId, + String connectScopeId) + throws Exception { + return newSource(prepared, state, options, requestId, connectScopeId, SourceTarget.NORMAL); + } + + private SourceFixture newSourceWithTarget(PreparedAccount prepared, SourceTarget target) + throws Exception { + return newSource( + prepared, + SourceState.COMMITTED, + SourceOptions.NORMAL, + "source-request-" + UUID.randomUUID(), + "source-scope-" + UUID.randomUUID(), + target); + } + + private SourceFixture newSource( + PreparedAccount prepared, + SourceState state, + SourceOptions options, + String requestId, + String connectScopeId, + SourceTarget target) + throws Exception { long sourceTenantId = options.unmappedTenant() ? prepared.tenantId() + 1000L : prepared.tenantId(); UUID sourceTenantUuid = options.unmappedTenant() ? UUID.randomUUID() : prepared.tenantUuid(); @@ -574,7 +1349,12 @@ private SourceFixture newSource( String tokenIdentity = "source-jti-" + UUID.randomUUID(); Map sourceClaims = sourceClaims( - prepared.accountUuid(), sourceTenantUuid, identity, tokenIdentity, prepared.clock()); + prepared.accountUuid(), + sourceTenantUuid, + identity, + tokenIdentity, + prepared.clock(), + target); KeyPair tokenSigner = options.unknownSourceKey() ? prepared.unknownAccountKeyPair() : prepared.accountKeyPair(); String tokenKeyId = options.unknownSourceKey() ? "unregistered-account-key" : ACCOUNT_KEY_ID; @@ -676,6 +1456,145 @@ private AccountEnvelopeCrypto differentConnectPurposeKey() throws Exception { return new AccountEnvelopeCrypto(manifest); } + private StoredBareLoginFixture storeBareLoginFrame( + PreparedAccount prepared, + SourceFixture source, + String originalGatewayContext, + byte[] originalResult, + byte[] operationResultHash) + throws Exception { + byte[] encodedFrame = + BareLoginRecoveryPayload.of(originalGatewayContext, originalResult).encode(); + byte[] storedResultHash = + operationResultHash == null ? sha256(originalResult) : operationResultHash.clone(); + try { + return storeBareLoginResponse(prepared, source, encodedFrame, storedResultHash); + } finally { + java.util.Arrays.fill(encodedFrame, (byte) 0); + java.util.Arrays.fill(storedResultHash, (byte) 0); + } + } + + private StoredBareLoginFixture storeOpaqueBareLoginPayload( + PreparedAccount prepared, SourceFixture source, byte[] opaquePayload) throws Exception { + byte[] resultHash = sha256(opaquePayload); + try { + return storeBareLoginResponse(prepared, source, opaquePayload, resultHash); + } finally { + java.util.Arrays.fill(resultHash, (byte) 0); + } + } + + private StoredBareLoginFixture storeBareLoginResponse( + PreparedAccount prepared, + SourceFixture source, + byte[] encryptedPlaintext, + byte[] storedResultHash) + throws Exception { + AccountCommittedConnectSource committedSource = + inTransaction( + prepared.db().transaction(), + () -> + prepared + .db() + .issuanceRepository() + .readCommittedResponseEnvelope(source.identity()) + .orElseThrow()); + AccountBareLoginExchangeIdentity identity = + new AccountBareLoginExchangeIdentity( + committedSource.operation().operationId(), + source.identity().accountId(), + source.identity().tenantId(), + source.identity().connectScopeId(), + "exchange-request-" + UUID.randomUUID()); + byte[] requestDigest = randomDigest(); + byte[] contextEvidenceDigest = randomDigest(); + byte[] authorityTupleDigest = randomDigest(); + byte[] issuanceFenceDigest = randomDigest(); + byte[] postconditionDigest = randomDigest(); + String resultTokenIdentity = "stored-result-jti-" + UUID.randomUUID(); + try { + AccountBareLoginResponseEnvelope stored = + inTransaction( + prepared.db().transaction(), + () -> { + var claim = + prepared.db().bareLoginExchangeRepository().claim(identity, requestDigest); + prepared + .db() + .bareLoginExchangeRepository() + .recordPendingEvidence( + claim, + requestDigest, + resultTokenIdentity, + storedResultHash, + contextEvidenceDigest, + authorityTupleDigest, + issuanceFenceDigest, + postconditionDigest); + AccountEnvelopeBinding binding = + new AccountEnvelopeBinding( + AccountEnvelopeBinding.OperationKind.BARE_LOGIN_EXCHANGE, + claim.operation().operationId().toString(), + identity.requestId(), + Long.toString(identity.accountId()), + Long.toString(identity.tenantId()), + identity.connectScopeId(), + identity.sourceConnectOperationId().toString(), + requestDigest, + contextEvidenceDigest, + authorityTupleDigest, + issuanceFenceDigest, + postconditionDigest); + AccountEncryptedEnvelope encrypted = + prepared + .db() + .envelopeCrypto() + .encrypt( + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, + binding, + encryptedPlaintext); + return prepared + .db() + .bareLoginExchangeRepository() + .completeWithEnvelope( + claim, + requestDigest, + resultTokenIdentity, + storedResultHash, + binding, + encrypted); + }); + return new StoredBareLoginFixture( + identity, requestDigest, source.identity(), stored.operationId()); + } finally { + java.util.Arrays.fill(contextEvidenceDigest, (byte) 0); + java.util.Arrays.fill(authorityTupleDigest, (byte) 0); + java.util.Arrays.fill(issuanceFenceDigest, (byte) 0); + java.util.Arrays.fill(postconditionDigest, (byte) 0); + } + } + + private static AccountStoredBareLoginRecoveryReader storedReader(PreparedAccount prepared) { + return storedReader(prepared, prepared.db().envelopeCrypto()); + } + + private static AccountStoredBareLoginRecoveryReader storedReader( + PreparedAccount prepared, AccountEnvelopeCrypto crypto) { + return new AccountStoredBareLoginRecoveryReader( + prepared.db().bareLoginExchangeRepository(), + prepared.joinRepository(), + crypto, + prepared.reader(), + prepared.gatewayKeys(), + WORKLOAD_NAMESPACE); + } + + private AccountEnvelopeCrypto missingKeyRingCrypto() { + return new AccountEnvelopeCrypto( + tempDir.resolve("missing-account-response-ring-" + UUID.randomUUID() + ".v1")); + } + private static AccountCommittedConnectSourceReader readerWithCrypto( PreparedAccount prepared, AccountEnvelopeCrypto crypto) { return new AccountCommittedConnectSourceReader( @@ -695,7 +1614,8 @@ private static Map sourceClaims( UUID tenantUuid, AccountConnectTokenIssuanceIdentity identity, String tokenIdentity, - Clock clock) { + Clock clock, + SourceTarget target) { BigInteger one = BigInteger.ONE; BigInteger now = BigInteger.valueOf(clock.instant().getEpochSecond()); Map tenantGeneration = Map.of(tenantUuid.toString(), one); @@ -714,13 +1634,28 @@ private static Map sourceClaims( "account:auth-authority:v1:tenant/" + tenantUuid, "outboxSequence", one); + List privateRealmGrantVersions = + target.playtestLifecycleId() == null + ? List.of() + : List.of( + Map.of( + "tenantId", + tenantUuid.toString(), + "worldSlug", + target.worldSlug(), + "realmSlug", + target.realmSlug(), + "playtestLifecycleId", + target.playtestLifecycleId().toString(), + "grantVersion", + one)); Map authorityTuple = Map.of( "issuerAuthGeneration", one, "accountAuthorityGeneration", one, "tenantAuthorityGeneration", tenantGeneration, "membershipAuthorityGeneration", tenantGeneration, - "privateRealmGrantVersions", List.of(), + "privateRealmGrantVersions", privateRealmGrantVersions, "accountSecurityCutoff", accountSecurityCutoff, "tenantBillingCutoff", Map.of(tenantUuid.toString(), tenantBillingCutoffEntry)); Map claims = new LinkedHashMap<>(); @@ -732,8 +1667,8 @@ private static Map sourceClaims( claims.put("accountId", accountUuid.toString()); claims.put("tenantId", tenantUuid.toString()); claims.put("realmId", UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb").toString()); - claims.put("worldSlug", "world"); - claims.put("realmSlug", "realm"); + claims.put("worldSlug", target.worldSlug()); + claims.put("realmSlug", target.realmSlug()); claims.put( "playableStateNamespaceId", UUID.fromString("cccccccc-cccc-4ccc-8ccc-cccccccccccc").toString()); @@ -747,6 +1682,10 @@ private static Map sourceClaims( claims.put("authorityTuple", authorityTuple); claims.put("membershipVersion", tenantGeneration); claims.put("replayAdmissionFence", one); + if (target.playtestLifecycleId() != null) { + claims.put("playtestLifecycleId", target.playtestLifecycleId().toString()); + claims.put("playtestStateGeneration", target.playtestStateGeneration()); + } return claims; } @@ -846,6 +1785,27 @@ private static Snapshot sourceSnapshot( row.get(3, Long.class)); } + private static BareLoginSnapshot bareLoginSnapshot(PreparedAccount prepared, UUID operationId) { + Record row = + prepared + .db() + .dsl() + .resultQuery( + "SELECT operation_id, status, updated_at::text, " + + "(SELECT count(*) FROM account_bare_login_response_envelopes e " + + "WHERE e.operation_id = o.operation_id) " + + "FROM account_bare_login_exchange_operations o WHERE operation_id = ?", + operationId) + .fetchOne(); + return row == null + ? new BareLoginSnapshot(null, null, null, 0L) + : new BareLoginSnapshot( + row.get(0, UUID.class), + row.get(1, String.class), + row.get(2, String.class), + row.get(3, Long.class)); + } + private static boolean awaitAccountFenceBlock( DSLContext dsl, int readerBackendPid, int blockerBackendPid, Duration timeout) throws InterruptedException { @@ -868,6 +1828,29 @@ private static boolean awaitAccountFenceBlock( return false; } + private static boolean awaitRelationLockBlock( + DSLContext dsl, int readerBackendPid, int blockerBackendPid, Duration timeout) + throws InterruptedException { + long deadline = System.nanoTime() + timeout.toNanos(); + while (System.nanoTime() < deadline) { + Boolean blocked = + dsl.resultQuery( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity waiting " + + "JOIN pg_locks waiting_lock ON waiting_lock.pid = waiting.pid " + + "WHERE waiting.pid = ? AND waiting.wait_event_type = 'Lock' " + + "AND waiting_lock.locktype = 'relation' AND NOT waiting_lock.granted " + + "AND ? = ANY(pg_blocking_pids(waiting.pid)))", + readerBackendPid, + blockerBackendPid) + .fetchOne(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + private static boolean await(CountDownLatch latch, long timeout, TimeUnit unit) { try { return latch.await(timeout, unit); @@ -903,6 +1886,194 @@ private static void assertReadRejected( .hasMessageContaining(messageFragment); } + private static void assertHistoricalReadRejected( + PreparedAccount prepared, + SourceFixture source, + Class exceptionType, + String messageFragment) { + assertHistoricalReadRejected( + prepared.reader(), prepared, source, exceptionType, messageFragment); + } + + private static void assertHistoricalReadRejected( + AccountCommittedConnectSourceReader reader, + PreparedAccount prepared, + SourceFixture source, + Class exceptionType, + String messageFragment) { + Snapshot before = sourceSnapshot(prepared, source.identity()); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + reader.readHistorical( + source.identity(), source.gatewayEnvelope())))) + .isInstanceOf(exceptionType) + .hasMessageContaining(messageFragment); + assertThat(sourceSnapshot(prepared, source.identity())).isEqualTo(before); + } + + private static void assertStoredReadRejected( + AccountStoredBareLoginRecoveryReader reader, + PreparedAccount prepared, + StoredBareLoginFixture stored, + byte[] requestDigest, + Class exceptionType, + String messageFragment) { + Snapshot sourceBefore = sourceSnapshot(prepared, stored.sourceIdentity()); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + assertThatThrownBy( + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> reader.readHistorical(stored.identity(), requestDigest)))) + .isInstanceOf(exceptionType) + .hasMessageContaining(messageFragment); + assertThat(sourceSnapshot(prepared, stored.sourceIdentity())).isEqualTo(sourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + } + + private static HistoricalStoredBareLoginCorrelationEvidence readCorrelation( + AccountStoredBareLoginRecoveryReader reader, + PreparedAccount prepared, + StoredBareLoginFixture stored, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext) { + return readCorrelation( + reader, + prepared, + stored.identity(), + stored.requestDigest(), + freshIdentity, + signedFreshGatewayContext); + } + + private static HistoricalStoredBareLoginCorrelationEvidence readCorrelation( + AccountStoredBareLoginRecoveryReader reader, + PreparedAccount prepared, + AccountBareLoginExchangeIdentity originalIdentity, + byte[] originalRequestDigest, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext) { + return withPeer( + peer(WORKLOAD_NAMESPACE, "game-session-service"), + () -> + inTransaction( + prepared.db().transaction(), + () -> + reader.readCorrelation( + originalIdentity, + originalRequestDigest, + freshIdentity, + signedFreshGatewayContext))); + } + + private static void assertCorrelationReadRejected( + PreparedAccount prepared, + AccountStoredBareLoginRecoveryReader reader, + StoredBareLoginFixture stored, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext, + Class exceptionType, + String messageFragment) { + assertCorrelationReadRejected( + prepared, + reader, + stored, + stored.identity(), + stored.requestDigest(), + freshIdentity, + signedFreshGatewayContext, + exceptionType, + messageFragment); + } + + private static void assertCorrelationReadRejected( + PreparedAccount prepared, + AccountStoredBareLoginRecoveryReader reader, + StoredBareLoginFixture stored, + byte[] originalRequestDigest, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext, + Class exceptionType, + String messageFragment) { + assertCorrelationReadRejected( + prepared, + reader, + stored, + stored.identity(), + originalRequestDigest, + freshIdentity, + signedFreshGatewayContext, + exceptionType, + messageFragment); + } + + private static void assertCorrelationReadRejected( + PreparedAccount prepared, + AccountStoredBareLoginRecoveryReader reader, + StoredBareLoginFixture stored, + AccountBareLoginExchangeIdentity originalIdentity, + byte[] originalRequestDigest, + AccountConnectTokenIssuanceIdentity freshIdentity, + String signedFreshGatewayContext, + Class exceptionType, + String messageFragment) { + Snapshot originalSourceBefore = sourceSnapshot(prepared, stored.sourceIdentity()); + Snapshot freshSourceBefore = sourceSnapshot(prepared, freshIdentity); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + assertThatThrownBy( + () -> + readCorrelation( + reader, + prepared, + originalIdentity, + originalRequestDigest, + freshIdentity, + signedFreshGatewayContext)) + .isInstanceOf(exceptionType) + .hasMessageContaining(messageFragment); + assertThat(sourceSnapshot(prepared, stored.sourceIdentity())).isEqualTo(originalSourceBefore); + assertThat(sourceSnapshot(prepared, freshIdentity)).isEqualTo(freshSourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + } + + private static void assertCorrelationIdentityRejected( + PreparedAccount prepared, + AccountStoredBareLoginRecoveryReader reader, + StoredBareLoginFixture stored, + AccountConnectTokenIssuanceIdentity freshIdentity) { + Snapshot originalSourceBefore = sourceSnapshot(prepared, stored.sourceIdentity()); + BareLoginSnapshot exchangeBefore = bareLoginSnapshot(prepared, stored.operationId()); + assertThatThrownBy( + () -> + readCorrelation( + reader, prepared, stored, freshIdentity, "unused-unverified-context")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("same Account and tenant"); + assertThat(sourceSnapshot(prepared, stored.sourceIdentity())).isEqualTo(originalSourceBefore); + assertThat(bareLoginSnapshot(prepared, stored.operationId())).isEqualTo(exchangeBefore); + } + + private static String resignCurrentGatewayContext(PreparedAccount prepared, SourceFixture source) + throws Exception { + Map currentClaims = + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + source.sourceClaims(), + prepared.clock().instant().getEpochSecond(), + "gateway-request-" + UUID.randomUUID()); + byte[] payload = JSON.writeValueAsBytes(currentClaims); + return GatewayConnectContextSignature.sign( + payload, GATEWAY_KEY_ID, prepared.gatewayKeyPair().getPrivate()); + } + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { Context scoped = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); Context previous = scoped.attach(); @@ -931,6 +2102,12 @@ private static byte[] digest(String value) { return sha256(value.getBytes(StandardCharsets.UTF_8)); } + private static byte[] randomDigest() { + byte[] value = new byte[32]; + FIXTURE_RANDOM.nextBytes(value); + return value; + } + private static byte[] sha256(byte[] value) { try { return MessageDigest.getInstance("SHA-256").digest(value); @@ -962,10 +2139,26 @@ private record SourceOptions( new SourceOptions(false, false, false, false, false, false, false); } + private record SourceTarget( + String worldSlug, + String realmSlug, + UUID playtestLifecycleId, + BigInteger playtestStateGeneration) { + private static final SourceTarget NORMAL = new SourceTarget("world", "realm", null, null); + + private SourceTarget { + if ((playtestLifecycleId == null) != (playtestStateGeneration == null)) { + throw new IllegalArgumentException( + "Playtest lifecycle and generation must appear together"); + } + } + } + private record TestContext( DSLContext dsl, TransactionTemplate transaction, AccountConnectTokenIssuanceRepository issuanceRepository, + AccountBareLoginExchangeRepository bareLoginExchangeRepository, AccountEnvelopeCrypto envelopeCrypto) {} private record PreparedAccount( @@ -993,8 +2186,26 @@ private record SourceFixture( Map gatewayClaims, String tokenIdentity) {} + private record StoredBareLoginFixture( + AccountBareLoginExchangeIdentity identity, + byte[] requestDigest, + AccountConnectTokenIssuanceIdentity sourceIdentity, + UUID operationId) { + private StoredBareLoginFixture { + requestDigest = requestDigest.clone(); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + } + private record Snapshot(UUID operationId, String status, String updatedAt, long envelopeCount) {} + private record BareLoginSnapshot( + UUID operationId, String status, String updatedAt, long envelopeCount) {} + private static final class TestClock extends Clock { private volatile Instant now; private final ZoneId zone; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java index 78c39533a4..e322260b65 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountEnvelopeCryptoTest.java @@ -18,6 +18,7 @@ import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException; import net.firedevops.firemud.accountservice.security.AccountEnvelopeCryptoException.Failure; import net.firedevops.firemud.accountservice.security.AccountEnvelopePurpose; +import net.firedevops.firemud.accountservice.security.BareLoginRecoveryPayload; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -41,11 +42,16 @@ void exactEnvelopeBytesDecryptAfterCryptoObjectRecreationForBothPurposes() throw byte[] exactResult = "the exact previously issued result".getBytes(StandardCharsets.UTF_8); AccountEnvelopeBinding loginBinding = loginBinding("login-op-1", "login-request-1"); byte[] exactLoginResult = "the exact bare LOGIN result".getBytes(StandardCharsets.UTF_8); + byte[] exactLoginRecoveryPayload = + BareLoginRecoveryPayload.of( + "original-protected.original-payload.original-signature", exactLoginResult) + .encode(); AccountEncryptedEnvelope envelope = writer.encrypt(AccountEnvelopePurpose.CONNECT_TOKEN_RESPONSE, binding, exactResult); AccountEncryptedEnvelope loginEnvelope = - writer.encrypt(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding, exactLoginResult); + writer.encrypt( + AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding, exactLoginRecoveryPayload); AccountEnvelopeCrypto recoveryReader = new AccountEnvelopeCrypto(manifestPath); assertEquals("k1", envelope.keyId()); @@ -56,9 +62,17 @@ void exactEnvelopeBytesDecryptAfterCryptoObjectRecreationForBothPurposes() throw assertEquals("k1", loginEnvelope.keyId()); assertEquals(AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginEnvelope.purpose()); assertArrayEquals( - exactLoginResult, + exactLoginRecoveryPayload, recoveryReader.decrypt( loginEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding)); + BareLoginRecoveryPayload recoveredLoginPayload = + BareLoginRecoveryPayload.decode( + recoveryReader.decrypt( + loginEnvelope, AccountEnvelopePurpose.BARE_LOGIN_RESPONSE, loginBinding)); + assertEquals( + "original-protected.original-payload.original-signature", + recoveredLoginPayload.originalGatewayContext()); + assertArrayEquals(exactLoginResult, recoveredLoginPayload.originalResultBytes()); assertFailure( Failure.AUTHENTICATION_FAILED, () -> diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java index 546a4a97fd..9014bc01eb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountGameplayConnectSourceVerifierTest.java @@ -1,5 +1,6 @@ package unit.net.firedevops.firemud.accountservice.security; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; @@ -20,6 +21,10 @@ import java.util.List; import java.util.Map; import net.firedevops.firemud.accountservice.security.AccountGameplayConnectSourceVerifier; +import net.firedevops.firemud.accountservice.security.HistoricalAccountGameplayConnectEvidence; +import net.firedevops.firemud.common.security.GatewayConnectContextCodec; +import net.firedevops.firemud.common.security.GatewayConnectContextSignature; +import net.firedevops.firemud.common.security.HistoricalGatewayConnectEvidence; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import tools.jackson.databind.json.JsonMapper; @@ -28,6 +33,7 @@ class AccountGameplayConnectSourceVerifierTest { private static final String ISSUER = "https://account.example.test"; private static final String RSA_KID = "account-rsa-current"; private static final String ED_KID = "account-ed-current"; + private static final String GATEWAY_KID = "gateway-history-test"; private static final int MAX_COMPACT_JWT_BYTES = 16 * 1024; private static final Instant NOW = Instant.parse("2026-04-06T12:00:00Z"); private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); @@ -44,6 +50,7 @@ class AccountGameplayConnectSourceVerifierTest { private KeyPair rsaKeyPair; private KeyPair edKeyPair; + private KeyPair gatewayKeyPair; @BeforeEach void setUp() throws Exception { @@ -51,6 +58,7 @@ void setUp() throws Exception { rsa.initialize(2048); rsaKeyPair = rsa.generateKeyPair(); edKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + gatewayKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); } @Test @@ -176,6 +184,81 @@ void rejectsExpiredFutureAndOverlongSourceTimesBeforeProjection() throws Excepti assertSanitizedFailure(sign(overlong, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate())); } + @Test + void verifiesExpiredSourceOnlyAgainstSignedHistoricalGatewayTime() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 30, NOW_SECONDS - 1); + String compactJwt = sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + HistoricalGatewayConnectEvidence gatewayEvidence = + historicalGatewayEvidence(claims, NOW_SECONDS - 2); + + assertSanitizedFailure(compactJwt); + HistoricalAccountGameplayConnectEvidence evidence = + verifier().verifyHistorical(compactJwt, gatewayEvidence); + + assertEquals(RSA_KID, evidence.accountKeyId()); + assertEquals(claims, evidence.sourceClaims()); + assertEquals(gatewayEvidence.signedEnvelope(), evidence.gatewayEvidence().signedEnvelope()); + assertArrayEquals(gatewayEvidence.signedPayload(), evidence.gatewayEvidence().signedPayload()); + assertEquals(gatewayEvidence.claims(), evidence.gatewayEvidence().claims()); + assertEquals( + LARGE_ACCOUNT_GENERATION, + objectMap(objectMap(evidence.sourceClaims().get("authorityTuple"))) + .get("accountAuthorityGeneration")); + assertFalse(evidence.sourceClaims().containsValue(compactJwt)); + assertFalse(evidence.toString().contains(compactJwt)); + assertThrows(UnsupportedOperationException.class, () -> evidence.sourceClaims().put("x", "y")); + Map tuple = objectMap(evidence.sourceClaims().get("authorityTuple")); + assertThrows( + UnsupportedOperationException.class, + () -> tuple.put("accountAuthorityGeneration", BigInteger.ZERO)); + assertFalse(evidence.gatewayEvidence().signedEnvelope().isEmpty()); + } + + @Test + void rejectsBadAccountSignatureProfileAndHistoricalSourceCorrespondence() throws Exception { + Map claims = sourceClaims(NOW_SECONDS - 30, NOW_SECONDS - 1); + String validCompactJwt = sign(claims, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()); + HistoricalGatewayConnectEvidence validGatewayEvidence = + historicalGatewayEvidence(claims, NOW_SECONDS - 2); + + KeyPair wrongAccountSigner = KeyPairGenerator.getInstance("RSA").generateKeyPair(); + assertHistoricalSanitizedFailure( + sign(claims, "RS256", RSA_KID, "JWT", wrongAccountSigner.getPrivate()), + validGatewayEvidence); + + Map wrongIssuer = new LinkedHashMap<>(claims); + wrongIssuer.put("iss", "https://other-account.example.test"); + assertHistoricalSanitizedFailure( + sign(wrongIssuer, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()), validGatewayEvidence); + + Map wrongAudience = new LinkedHashMap<>(claims); + wrongAudience.put("aud", "player-bootstrap"); + assertHistoricalSanitizedFailure( + sign(wrongAudience, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()), + validGatewayEvidence); + + Map changedTarget = new LinkedHashMap<>(claims); + changedTarget.put("realmId", "00000000-0000-4000-8000-000000000099"); + assertHistoricalSanitizedFailure( + sign(changedTarget, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()), + validGatewayEvidence); + + HistoricalGatewayConnectEvidence changedGatewayEvidence = + historicalGatewayEvidence( + claims, NOW_SECONDS - 2, "realmId", "00000000-0000-4000-8000-000000000099"); + assertHistoricalSanitizedFailure(validCompactJwt, changedGatewayEvidence); + + Map sourceValidAtGatewayTime = sourceClaims(NOW_SECONDS - 29, NOW_SECONDS + 1); + HistoricalGatewayConnectEvidence gatewayAfterSourceExpiry = + historicalGatewayEvidence(sourceValidAtGatewayTime, NOW_SECONDS); + assertHistoricalSanitizedFailure(validCompactJwt, gatewayAfterSourceExpiry); + + Map openProfile = new LinkedHashMap<>(claims); + openProfile.put("unregisteredClaim", "not accepted"); + assertHistoricalSanitizedFailure( + sign(openProfile, "RS256", RSA_KID, "JWT", rsaKeyPair.getPrivate()), validGatewayEvidence); + } + @Test void rejectsNonCanonicalMalformedAndOversizedCompactJwts() throws Exception { Map claims = sourceClaims(NOW_SECONDS - 1, NOW_SECONDS + 29); @@ -300,6 +383,28 @@ private AccountGameplayConnectSourceVerifier verifier() { ISSUER, Map.of(RSA_KID, rsaKeyPair.getPublic()), MAX_COMPACT_JWT_BYTES, CLOCK); } + private HistoricalGatewayConnectEvidence historicalGatewayEvidence( + Map sourceClaims, long verifiedAt) throws Exception { + return historicalGatewayEvidence(sourceClaims, verifiedAt, null, null); + } + + private HistoricalGatewayConnectEvidence historicalGatewayEvidence( + Map sourceClaims, long verifiedAt, String changedField, Object changedValue) + throws Exception { + Map contextClaims = + new LinkedHashMap<>( + GatewayConnectContextCodec.projectVerifiedAccountGameplayConnectClaims( + sourceClaims, verifiedAt, "gateway-history-request")); + if (changedField != null) { + contextClaims.put(changedField, changedValue); + } + String envelope = + GatewayConnectContextSignature.sign( + JSON.writeValueAsBytes(contextClaims), GATEWAY_KID, gatewayKeyPair.getPrivate()); + return GatewayConnectContextCodec.verifyHistoricalEvidence( + envelope, Map.of(GATEWAY_KID, gatewayKeyPair.getPublic())); + } + private void assertSanitizedFailure(String compactJwt) { assertSanitizedFailure(verifier(), compactJwt); } @@ -315,6 +420,19 @@ private void assertSanitizedFailure( } } + private void assertHistoricalSanitizedFailure( + String compactJwt, HistoricalGatewayConnectEvidence gatewayEvidence) { + IllegalArgumentException failure = + assertThrows( + IllegalArgumentException.class, + () -> verifier().verifyHistorical(compactJwt, gatewayEvidence)); + assertEquals("invalid Account gameplay-connect source JWT", failure.getMessage()); + assertNull(failure.getCause()); + if (compactJwt != null) { + assertFalse(failure.getMessage().contains(compactJwt)); + } + } + private static Map sourceClaims(long issuedAt, long expiresAt) { Map claims = new LinkedHashMap<>(); claims.put("iss", ISSUER); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayloadTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayloadTest.java new file mode 100644 index 0000000000..9ed07850e7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/BareLoginRecoveryPayloadTest.java @@ -0,0 +1,207 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import net.firedevops.firemud.accountservice.security.AccountEncryptedEnvelope; +import net.firedevops.firemud.accountservice.security.BareLoginRecoveryPayload; +import org.junit.jupiter.api.Test; + +class BareLoginRecoveryPayloadTest { + private static final String GATEWAY_CONTEXT = "protected.payload.signature"; + private static final byte[] RESULT_BYTES = new byte[] {0, 1, (byte) 0xff, '\n', 42}; + + @Test + void roundTripsExactContextAndOpaqueResultBytes() { + BareLoginRecoveryPayload original = BareLoginRecoveryPayload.of(GATEWAY_CONTEXT, RESULT_BYTES); + byte[] encoded = original.encode(); + + BareLoginRecoveryPayload recovered = BareLoginRecoveryPayload.decode(encoded); + + assertEquals(GATEWAY_CONTEXT, recovered.originalGatewayContext()); + assertArrayEquals( + GATEWAY_CONTEXT.getBytes(StandardCharsets.UTF_8), recovered.originalGatewayContextUtf8()); + assertArrayEquals(RESULT_BYTES, recovered.originalResultBytes()); + assertEquals( + 16 + GATEWAY_CONTEXT.getBytes(StandardCharsets.UTF_8).length + RESULT_BYTES.length, + encoded.length); + assertFalse(recovered.toString().contains(GATEWAY_CONTEXT)); + assertFalse(recovered.toString().contains("signature")); + } + + @Test + void rejectsUnknownVersionTruncationTrailingBytesAndUnknownHeader() { + byte[] valid = BareLoginRecoveryPayload.of(GATEWAY_CONTEXT, RESULT_BYTES).encode(); + + byte[] unknownVersion = valid.clone(); + unknownVersion[7] = 2; + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(unknownVersion)); + + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.decode(Arrays.copyOf(valid, valid.length - 1))); + + byte[] trailingByte = Arrays.copyOf(valid, valid.length + 1); + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(trailingByte)); + + byte[] unknownHeader = valid.clone(); + unknownHeader[0] ^= 1; + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(unknownHeader)); + } + + @Test + void rejectsNegativeAndHugeDeclaredContextAndResultLengths() { + byte[] context = GATEWAY_CONTEXT.getBytes(StandardCharsets.UTF_8); + byte[] valid = rawFrame(context, RESULT_BYTES); + int resultLengthOffset = 12 + context.length; + + byte[] negativeContextLength = valid.clone(); + putInt(negativeContextLength, 8, -1); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.decode(negativeContextLength)); + + byte[] hugeContextLength = valid.clone(); + putInt(hugeContextLength, 8, Integer.MAX_VALUE); + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(hugeContextLength)); + + byte[] negativeResultLength = valid.clone(); + putInt(negativeResultLength, resultLengthOffset, -1); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.decode(negativeResultLength)); + + byte[] hugeResultLength = valid.clone(); + putInt(hugeResultLength, resultLengthOffset, Integer.MAX_VALUE); + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(hugeResultLength)); + } + + @Test + void rejectsContextOnlyFrameTruncatedAtResultLengthBoundary() { + byte[] context = GATEWAY_CONTEXT.getBytes(StandardCharsets.UTF_8); + byte[] contextOnly = contextOnlyFrame(context); + + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(contextOnly)); + } + + @Test + void rejectsEmptyInvalidUtf8AndNonCompactFields() { + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.of("", RESULT_BYTES)); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of(GATEWAY_CONTEXT, new byte[0])); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of(".payload.signature", RESULT_BYTES)); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of("header..signature", RESULT_BYTES)); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of("header.payload.", RESULT_BYTES)); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of("header.payload.signature.extra", RESULT_BYTES)); + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of("header.pΓ€yload.signature", RESULT_BYTES)); + + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.decode(rawFrame(new byte[0], RESULT_BYTES))); + assertThrows( + IllegalArgumentException.class, + () -> + BareLoginRecoveryPayload.decode( + rawFrame(GATEWAY_CONTEXT.getBytes(StandardCharsets.UTF_8), new byte[0]))); + assertThrows( + IllegalArgumentException.class, + () -> + BareLoginRecoveryPayload.decode( + rawFrame(new byte[] {(byte) 0xc3, '.', 'b', '.', 'c'}, RESULT_BYTES))); + } + + @Test + void rejectsFramesBeyondAccountEnvelopePlaintextBound() { + byte[] oversizedResult = new byte[AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES]; + assertThrows( + IllegalArgumentException.class, + () -> BareLoginRecoveryPayload.of(GATEWAY_CONTEXT, oversizedResult)); + + byte[] oversizedFrame = new byte[AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES + 1]; + assertThrows( + IllegalArgumentException.class, () -> BareLoginRecoveryPayload.decode(oversizedFrame)); + } + + @Test + void acceptsFrameAtExactAccountEnvelopePlaintextBound() { + int maxFrameLength = AccountEncryptedEnvelope.MAX_PLAINTEXT_LENGTH_BYTES; + int contextLength = maxFrameLength - 16 - 1; + String context = "a".repeat(contextLength - 4) + ".b.c"; + byte[] result = new byte[] {(byte) 0xff}; + + byte[] encoded = BareLoginRecoveryPayload.of(context, result).encode(); + + assertEquals(maxFrameLength, encoded.length); + BareLoginRecoveryPayload recovered = BareLoginRecoveryPayload.decode(encoded); + assertEquals(context, recovered.originalGatewayContext()); + assertArrayEquals(result, recovered.originalResultBytes()); + } + + @Test + void defensivelyCopiesInputsAndOutputs() { + byte[] result = RESULT_BYTES.clone(); + BareLoginRecoveryPayload payload = BareLoginRecoveryPayload.of(GATEWAY_CONTEXT, result); + Arrays.fill(result, (byte) 0); + + byte[] exposedContext = payload.originalGatewayContextUtf8(); + byte[] exposedResult = payload.originalResultBytes(); + byte[] exposedFrame = payload.encode(); + Arrays.fill(exposedContext, (byte) 0); + Arrays.fill(exposedResult, (byte) 0); + Arrays.fill(exposedFrame, (byte) 0); + + assertArrayEquals(RESULT_BYTES, payload.originalResultBytes()); + assertEquals(GATEWAY_CONTEXT, payload.originalGatewayContext()); + assertArrayEquals( + RESULT_BYTES, BareLoginRecoveryPayload.decode(payload.encode()).originalResultBytes()); + } + + private static byte[] rawFrame(byte[] context, byte[] result) { + ByteBuffer frame = + ByteBuffer.allocate(16 + context.length + result.length).order(ByteOrder.BIG_ENDIAN); + frame.put(new byte[] {'F', 'M', 'B', 'R'}); + frame.putInt(1); + frame.putInt(context.length); + frame.put(context); + frame.putInt(result.length); + frame.put(result); + return frame.array(); + } + + private static byte[] contextOnlyFrame(byte[] context) { + ByteBuffer frame = ByteBuffer.allocate(12 + context.length).order(ByteOrder.BIG_ENDIAN); + frame.put(new byte[] {'F', 'M', 'B', 'R'}); + frame.putInt(1); + frame.putInt(context.length); + frame.put(context); + return frame.array(); + } + + private static void putInt(byte[] frame, int offset, int value) { + ByteBuffer.wrap(frame).order(ByteOrder.BIG_ENDIAN).putInt(offset, value); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java index 4952b4afcf..98af25f4f3 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCommittedConnectSourceReaderGuardTest.java @@ -108,6 +108,42 @@ void exactPeerWithoutOwnerTransactionIsDeniedBeforeAnyRepositoryOrCredentialInte verifyNoCollaboratorInteractions(); } + @Test + void historicalReadRequiresExactPeerAndOwnerTransactionBeforeAnyInteraction() { + AdminAuthorizationException missingPeer = + assertThrows( + AdminAuthorizationException.class, + () -> withoutPeer(() -> reader.readHistorical(IDENTITY, "unparsed-gateway-context"))); + assertEquals( + "Committed Account source readback requires the exact Game Session workload identity", + missingPeer.getMessage()); + verifyNoCollaboratorInteractions(); + + AdminAuthorizationException wrongPeer = + assertThrows( + AdminAuthorizationException.class, + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "world-management-service"), + () -> reader.readHistorical(IDENTITY, "unparsed-gateway-context"))); + assertEquals( + "Committed Account source readback requires the exact Game Session workload identity", + wrongPeer.getMessage()); + verifyNoCollaboratorInteractions(); + + IllegalStateException missingTransaction = + assertThrows( + IllegalStateException.class, + () -> + withPeer( + expectedGameSessionPeer, + () -> reader.readHistorical(IDENTITY, "unparsed-gateway-context"))); + assertEquals( + "Committed Account source readback requires an active owner transaction", + missingTransaction.getMessage()); + verifyNoCollaboratorInteractions(); + } + private void assertPeerDeniedBeforeInteractions(GrpcPeerIdentity peer) { AdminAuthorizationException failure = assertThrows( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReaderGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReaderGuardTest.java new file mode 100644 index 0000000000..fecea5006c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountStoredBareLoginRecoveryReaderGuardTest.java @@ -0,0 +1,175 @@ +package unit.net.firedevops.firemud.accountservice.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import java.security.KeyPairGenerator; +import java.util.Map; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeIdentity; +import net.firedevops.firemud.accountservice.repository.AccountBareLoginExchangeRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectTokenIssuanceIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.security.AccountEnvelopeCrypto; +import net.firedevops.firemud.accountservice.service.AccountCommittedConnectSourceReader; +import net.firedevops.firemud.accountservice.service.AccountStoredBareLoginRecoveryReader; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountStoredBareLoginRecoveryReaderGuardTest { + private static final String WORKLOAD_NAMESPACE = "account-unit"; + private static final AccountBareLoginExchangeIdentity IDENTITY = + new AccountBareLoginExchangeIdentity( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + 101L, + 202L, + "connect-scope-1", + "exchange-request-1"); + private static final byte[] REQUEST_DIGEST = new byte[32]; + + private AccountBareLoginExchangeRepository exchangeRepository; + private AccountJoinOperationRepository joinOperationRepository; + private AccountEnvelopeCrypto envelopeCrypto; + private AccountCommittedConnectSourceReader committedSourceReader; + private AccountStoredBareLoginRecoveryReader reader; + private GrpcPeerIdentity expectedGameSessionPeer; + + @BeforeEach + void setUp() throws Exception { + exchangeRepository = mock(AccountBareLoginExchangeRepository.class); + joinOperationRepository = mock(AccountJoinOperationRepository.class); + envelopeCrypto = mock(AccountEnvelopeCrypto.class); + committedSourceReader = mock(AccountCommittedConnectSourceReader.class); + expectedGameSessionPeer = peer(WORKLOAD_NAMESPACE, "game-session-service"); + var gatewayKey = KeyPairGenerator.getInstance("Ed25519").generateKeyPair().getPublic(); + reader = + new AccountStoredBareLoginRecoveryReader( + exchangeRepository, + joinOperationRepository, + envelopeCrypto, + committedSourceReader, + Map.of("gateway-test", gatewayKey), + WORKLOAD_NAMESPACE); + } + + @Test + void missingPeerIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + AdminAuthorizationException failure = + assertThrows( + AdminAuthorizationException.class, + () -> withoutPeer(() -> reader.readHistorical(IDENTITY, REQUEST_DIGEST.clone()))); + + assertEquals( + "Stored bare LOGIN history readback requires the exact Game Session workload identity", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + @Test + void wrongServiceOrNamespacePeerIsDeniedBeforeAnyInteraction() { + assertPeerDenied(peer(WORKLOAD_NAMESPACE, "account-service")); + assertPeerDenied(peer("other-account-unit", "game-session-service")); + } + + @Test + void exactPeerWithoutOwnerTransactionIsDeniedBeforeAnyRepositoryOrCredentialInteraction() { + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + + IllegalStateException failure = + assertThrows( + IllegalStateException.class, + () -> + withPeer( + expectedGameSessionPeer, + () -> reader.readHistorical(IDENTITY, REQUEST_DIGEST.clone()))); + + assertEquals( + "Stored bare LOGIN history readback requires an active owner transaction", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + @Test + void correlationRequiresExactPeerAndOwnerTransactionBeforeAnyCollaboratorInteraction() { + AccountConnectTokenIssuanceIdentity freshIdentity = + new AccountConnectTokenIssuanceIdentity( + IDENTITY.accountId(), IDENTITY.tenantId(), "fresh-connect-scope", "fresh-request"); + + AdminAuthorizationException peerFailure = + assertThrows( + AdminAuthorizationException.class, + () -> + withPeer( + peer(WORKLOAD_NAMESPACE, "account-service"), + () -> + reader.readCorrelation( + IDENTITY, REQUEST_DIGEST.clone(), freshIdentity, "signed-context"))); + assertEquals( + "Stored bare LOGIN history readback requires the exact Game Session workload identity", + peerFailure.getMessage()); + verifyNoCollaboratorInteractions(); + + IllegalStateException transactionFailure = + assertThrows( + IllegalStateException.class, + () -> + withPeer( + expectedGameSessionPeer, + () -> + reader.readCorrelation( + IDENTITY, REQUEST_DIGEST.clone(), freshIdentity, "signed-context"))); + assertEquals( + "Stored bare LOGIN history readback requires an active owner transaction", + transactionFailure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + private void assertPeerDenied(GrpcPeerIdentity peer) { + AdminAuthorizationException failure = + assertThrows( + AdminAuthorizationException.class, + () -> withPeer(peer, () -> reader.readHistorical(IDENTITY, REQUEST_DIGEST.clone()))); + + assertEquals( + "Stored bare LOGIN history readback requires the exact Game Session workload identity", + failure.getMessage()); + verifyNoCollaboratorInteractions(); + } + + private void verifyNoCollaboratorInteractions() { + verifyNoInteractions( + exchangeRepository, joinOperationRepository, envelopeCrypto, committedSourceReader); + } + + private static GrpcPeerIdentity peer(String namespace, String service) { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + service) + .orElseThrow(); + } + + private static T withPeer(GrpcPeerIdentity peer, Supplier action) { + Context scoped = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = scoped.attach(); + try { + return action.get(); + } finally { + scoped.detach(previous); + } + } + + private static T withoutPeer(Supplier action) { + Context previous = Context.ROOT.attach(); + try { + return action.get(); + } finally { + Context.ROOT.detach(previous); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java index 1b1a3728ce..a6dacf49bc 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayConnectContextCodec.java @@ -177,34 +177,65 @@ public static void requireVerifiedAccountSourceMatchesGatewayContext( Map context = verifiedGatewayContext.claims(); BigInteger verifiedAt = requirePositiveInteger(context, "verifiedAt"); - long gatewayVerifiedAt; try { - gatewayVerifiedAt = verifiedAt.longValueExact(); + long 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"); - } + requireSourceMatchesGatewayProjection(verifiedSourceClaims, context, gatewayVerifiedAt); + } catch (ArithmeticException | java.time.DateTimeException ex) { + throw invalid( + "Gateway context verification time is outside the supported epoch-second range"); + } + } + + /** + * Requires exact correspondence between already-verified Account gameplay-connect claims and a + * signature-verified historical Gateway assertion. This proves only that the signed historical + * assertion carried the complete registered projection of those source claims. Callers must + * independently verify the Account source signature/profile and must not treat this evidence as a + * current Gateway authorization or proof of current Account authority, registry state, or + * recovery eligibility. + */ + public static void requireVerifiedAccountSourceMatchesHistoricalGatewayEvidence( + Map verifiedSourceClaims, + HistoricalGatewayConnectEvidence historicalGatewayEvidence) { + if (historicalGatewayEvidence == null) { + throw invalid("historical Gateway evidence is required"); + } + + Map context = historicalGatewayEvidence.claims(); + BigInteger verifiedAt = requirePositiveInteger(context, "verifiedAt"); + try { + long gatewayVerifiedAt = verifiedAt.longValueExact(); + Instant.ofEpochSecond(gatewayVerifiedAt); + validateShapeAndTimeGeometry(context); + validateSupportedTimestampRange(context); + requireSourceMatchesGatewayProjection(verifiedSourceClaims, context, gatewayVerifiedAt); } catch (ArithmeticException | java.time.DateTimeException ex) { throw invalid( "Gateway context verification time is outside the supported epoch-second range"); } } + private static void requireSourceMatchesGatewayProjection( + Map verifiedSourceClaims, Map context, long gatewayVerifiedAt) { + 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"); + } + } + /** * 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. @@ -223,6 +254,25 @@ public static GatewayConnectContext verifyAndDecode( return new GatewayConnectContext(signedEnvelope, verified.payload(), verified.kid(), claims); } + /** + * Verifies and validates an expired Gateway assertion solely as immutable historical evidence. + * The result is a distinct type and is not accepted by current-context consumers. This method + * does not establish that Gateway actually observed or accepted the assertion at its signed + * times, verify the Account source signature, or establish any current authority or recovery + * eligibility. + */ + public static HistoricalGatewayConnectEvidence verifyHistoricalEvidence( + String signedEnvelope, + Map gatewayVerificationKeys) { + GatewayConnectContextSignature.VerifiedContext verified = + GatewayConnectContextSignature.verify(signedEnvelope, gatewayVerificationKeys); + Map claims = parsePayload(verified.payload()); + validateShapeAndTimeGeometry(claims); + validateSupportedTimestampRange(claims); + return new HistoricalGatewayConnectEvidence( + 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. @@ -274,6 +324,25 @@ private static Map parsePayload(byte[] payload) { } private static void validate(Map claims, Instant now) { + validateShapeAndTimeGeometry(claims); + + BigInteger issuedAt = requirePositiveInteger(claims, "issuedAt"); + BigInteger verifiedAt = requirePositiveInteger(claims, "verifiedAt"); + BigInteger expiresAt = requirePositiveInteger(claims, "expiresAt"); + 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"); + } + validateSupportedTimestampRange(claims); + } + + private static void validateShapeAndTimeGeometry(Map claims) { Set allowed = new java.util.HashSet<>(REQUIRED_FIELDS); allowed.addAll(CONDITIONAL_FIELDS); if (!allowed.containsAll(claims.keySet()) || !claims.keySet().containsAll(REQUIRED_FIELDS)) { @@ -332,20 +401,13 @@ private static void validate(Map claims, Instant now) { > 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"); - } + } + + private static void validateSupportedTimestampRange(Map claims) { try { - Instant.ofEpochSecond(issuedAt.longValueExact()); - Instant.ofEpochSecond(verifiedAt.longValueExact()); - Instant.ofEpochSecond(expiresAt.longValueExact()); + Instant.ofEpochSecond(requirePositiveInteger(claims, "issuedAt").longValueExact()); + Instant.ofEpochSecond(requirePositiveInteger(claims, "verifiedAt").longValueExact()); + Instant.ofEpochSecond(requirePositiveInteger(claims, "expiresAt").longValueExact()); } catch (ArithmeticException | java.time.DateTimeException ex) { throw invalid("Gateway context time is outside the supported epoch-second range"); } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/HistoricalGatewayConnectEvidence.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/HistoricalGatewayConnectEvidence.java new file mode 100644 index 0000000000..712c20a0d8 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/HistoricalGatewayConnectEvidence.java @@ -0,0 +1,96 @@ +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; + +/** + * Immutable proof material for a previously signed Gateway assertion. + * + *

This is deliberately not a {@link GatewayConnectContext}: expired evidence cannot be passed to + * APIs that require a currently valid Gateway context. The original envelope and payload are + * retained exactly for a later exact encrypted-original readback. This type establishes neither + * source issuance nor current authorization, and must not be logged with its retained payload. + */ +public final class HistoricalGatewayConnectEvidence { + private final String signedEnvelope; + private final byte[] signedPayload; + private final String kid; + private final Map claims; + + HistoricalGatewayConnectEvidence( + 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 "HistoricalGatewayConnectEvidence[kid=" + kid + ", historical=true]"; + } + + 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(HistoricalGatewayConnectEvidence::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/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java index 4611b393cf..ad1b020224 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayConnectContextCodecTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -20,6 +21,7 @@ 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.common.security.HistoricalGatewayConnectEvidence; import net.firedevops.firemud.test.SelectedTargetConnectContextTestVectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -482,6 +484,138 @@ void rejectsMillisecondTimesExpiredContextAndClockSkewLifetimeExtension() throws assertRejected(extendsLifetimeWithSkew); } + @Test + void verifiesExpiredAssertionOnlyAsExactImmutableHistoricalEvidence() throws Exception { + Map source = historicalSource(); + Map claims = historicalContext(source); + byte[] payload = json.writeValueAsBytes(claims); + String envelope = GatewayConnectContextSignature.sign(payload, KID, keyPair.getPrivate()); + + HistoricalGatewayConnectEvidence evidence = verifyHistorical(envelope); + + assertEquals(envelope, evidence.signedEnvelope()); + assertArrayEquals(payload, evidence.signedPayload()); + assertEquals(KID, evidence.kid()); + assertEquals(claims, evidence.claims()); + assertEquals(BigInteger.valueOf(NOW.getEpochSecond() - 100L), evidence.integer("issuedAt")); + assertTrue(evidence.integer("expiresAt").longValueExact() < NOW.getEpochSecond()); + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesHistoricalGatewayEvidence( + source, evidence); + + byte[] exposedPayload = evidence.signedPayload(); + exposedPayload[0] ^= 1; + assertArrayEquals(payload, evidence.signedPayload()); + assertThrows( + UnsupportedOperationException.class, () -> evidence.claims().put("audience", "other")); + @SuppressWarnings("unchecked") + Map authorityTuple = + (Map) evidence.claims().get("authorityTuple"); + assertThrows( + UnsupportedOperationException.class, + () -> authorityTuple.put("accountAuthorityGeneration", BigInteger.ZERO)); + assertFalse(evidence.toString().contains(envelope)); + assertFalse(evidence.toString().contains(new String(payload, StandardCharsets.UTF_8))); + + // This is the same old, validly signed assertion: the ordinary reader remains strict. + assertThrows(IllegalArgumentException.class, () -> verify(envelope)); + } + + @Test + void historicalEvidenceRejectsUnknownKeyAndForgedSignatureBeforePayloadInterpretation() + throws Exception { + String malformedJsonEnvelope = + GatewayConnectContextSignature.sign( + "{".getBytes(StandardCharsets.UTF_8), KID, keyPair.getPrivate()); + IllegalArgumentException unknownKey = + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextCodec.verifyHistoricalEvidence( + malformedJsonEnvelope, Map.of("another-key", keyPair.getPublic()))); + assertEquals("unknown Gateway verification key", unknownKey.getMessage()); + + // A different valid signing key gives a well-formed, wrong-key signature. Flipping a + // compressed-point byte can instead fail in the provider's point decoder. + KeyPair wrongKeyPair = KeyPairGenerator.getInstance("Ed25519").generateKeyPair(); + String forgedMalformedJsonEnvelope = + GatewayConnectContextSignature.sign( + "{".getBytes(StandardCharsets.UTF_8), KID, wrongKeyPair.getPrivate()); + IllegalArgumentException invalidSignature = + assertThrows( + IllegalArgumentException.class, () -> verifyHistorical(forgedMalformedJsonEnvelope)); + assertEquals("invalid Gateway context signature", invalidSignature.getMessage()); + } + + @Test + void historicalEvidenceRejectsWrongReceiverAndOpenOrMalformedSchema() throws Exception { + Map wrongAudience = historicalContext(historicalSource()); + wrongAudience.put("audience", "account-service"); + assertHistoricalRejected(wrongAudience); + + Map wrongRecipient = historicalContext(historicalSource()); + wrongRecipient.put("recipient", "another-service"); + assertHistoricalRejected(wrongRecipient); + + Map missingField = historicalContext(historicalSource()); + missingField.remove("realmId"); + assertHistoricalRejected(missingField); + + Map extraField = historicalContext(historicalSource()); + extraField.put("legacyTenantKey", "42"); + assertHistoricalRejected(extraField); + + Map invalidTarget = historicalContext(historicalSource()); + invalidTarget.put("tenantId", "not-a-canonical-uuid"); + assertHistoricalRejected(invalidTarget); + } + + @Test + void historicalEvidenceRejectsInvalidOriginalTimestampAndLifetimeGeometry() throws Exception { + long issuedAt = NOW.getEpochSecond() - 100L; + + Map zeroLifetime = historicalContext(historicalSource()); + zeroLifetime.put("expiresAt", BigInteger.valueOf(issuedAt)); + assertHistoricalRejected(zeroLifetime); + + Map excessiveLifetime = historicalContext(historicalSource()); + excessiveLifetime.put( + "expiresAt", + BigInteger.valueOf(issuedAt + GatewayConnectContextCodec.MAX_CONTEXT_LIFETIME_SECONDS + 1)); + assertHistoricalRejected(excessiveLifetime); + + Map verificationAtExpiry = historicalContext(historicalSource()); + verificationAtExpiry.put("verifiedAt", verificationAtExpiry.get("expiresAt")); + assertHistoricalRejected(verificationAtExpiry); + + Map excessiveFutureIssuedAt = historicalContext(historicalSource()); + excessiveFutureIssuedAt.put( + "issuedAt", + BigInteger.valueOf(issuedAt + GatewayConnectContextCodec.MAX_CLOCK_SKEW_SECONDS + 2)); + assertHistoricalRejected(excessiveFutureIssuedAt); + + Map unsupportedEpoch = historicalContext(historicalSource()); + BigInteger outsideInstantRange = new BigInteger("1000000000000000000000000"); + unsupportedEpoch.put("issuedAt", outsideInstantRange); + unsupportedEpoch.put("verifiedAt", outsideInstantRange); + unsupportedEpoch.put("expiresAt", outsideInstantRange.add(BigInteger.TEN)); + assertHistoricalRejected(unsupportedEpoch); + } + + @Test + void historicalSourceCorrespondenceRejectsChangedSourceAndSelectedTarget() throws Exception { + Map source = historicalSource(); + HistoricalGatewayConnectEvidence original = verifyHistorical(sign(historicalContext(source))); + + Map changedSource = historicalSource(); + changedSource.put("connectScopeId", "different-original-source-scope"); + assertHistoricalSourceMismatch(changedSource, original); + + Map changedTarget = historicalContext(source); + changedTarget.put("realmId", "018f8f0a-8c1d-7f9a-ad6a-bf4a312c0d8e"); + HistoricalGatewayConnectEvidence changedTargetEvidence = verifyHistorical(sign(changedTarget)); + assertHistoricalSourceMismatch(source, changedTargetEvidence); + } + @Test void rejectsUnknownGatewayKeyAndWrongSignature() throws Exception { String envelope = sign(validContext()); @@ -532,6 +666,11 @@ private GatewayConnectContext verify(String envelope) { envelope, Map.of(KID, keyPair.getPublic()), clock); } + private HistoricalGatewayConnectEvidence verifyHistorical(String envelope) { + return GatewayConnectContextCodec.verifyHistoricalEvidence( + envelope, Map.of(KID, keyPair.getPublic())); + } + private String sign(Map claims) throws Exception { return GatewayConnectContextSignature.sign( json.writeValueAsBytes(claims), KID, keyPair.getPrivate()); @@ -541,6 +680,10 @@ private void assertRejected(Map claims) throws Exception { assertThrows(IllegalArgumentException.class, () -> verify(sign(claims))); } + private void assertHistoricalRejected(Map claims) throws Exception { + assertThrows(IllegalArgumentException.class, () -> verifyHistorical(sign(claims))); + } + private void assertSourceMismatch( Map sourceClaims, GatewayConnectContext verifiedContext) { assertThrows( @@ -550,6 +693,15 @@ private void assertSourceMismatch( sourceClaims, verifiedContext)); } + private void assertHistoricalSourceMismatch( + Map sourceClaims, HistoricalGatewayConnectEvidence historicalEvidence) { + assertThrows( + IllegalArgumentException.class, + () -> + GatewayConnectContextCodec.requireVerifiedAccountSourceMatchesHistoricalGatewayEvidence( + sourceClaims, historicalEvidence)); + } + private static BigInteger nested( Map claims, String object, String nestedObject, String key) { @SuppressWarnings("unchecked") @@ -563,6 +715,19 @@ private static Map validContext() { return projectContext(SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims()); } + private static Map historicalSource() { + Map source = SelectedTargetConnectContextTestVectors.sourceConnectTokenClaims(); + long issuedAt = NOW.getEpochSecond() - 100L; + source.put("iat", BigInteger.valueOf(issuedAt)); + source.put("exp", BigInteger.valueOf(issuedAt + 20L)); + return source; + } + + private static Map historicalContext(Map source) { + long issuedAt = ((BigInteger) source.get("iat")).longValueExact(); + return projectContext(source, issuedAt + 1L); + } + private static Map projectContext(Map source) { return projectContext(source, SelectedTargetConnectContextTestVectors.GATEWAY_VERIFIED_AT); }