diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index ee10b7d2a6..95a8acf8e7 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -4,6 +4,18 @@ This document defines the Account Service REST and gRPC contracts, authenticatio The authoritative REST schema source lives in [../../../../services/account-service/src/main/resources/openapi.yaml](../../../../services/account-service/src/main/resources/openapi.yaml). Proto definitions are the authoritative gRPC source. +## Private Current Public-JWKS Read + +The default-off `AccountPublicJwksReadService.GetCurrentPublicJwks` is a private read for the exact same-namespace Game Session mTLS workload. Its closed request and response use `schema_version=2`; the request still accepts no key, issuer, path, URI, or rotation selector. Response fields 1–3 retain the existing exact nine-field Account source identity and bounded public-snapshot semantics. Closed field 4 is the disposition: `UNSPECIFIED` is invalid, and the only valid values are `SNAPSHOT` and `PREPARED_DENY`. A `SNAPSHOT` carries the exact Account public snapshot, at most 256 KiB, and requires optional bool field 5, `committed_recovery_eligible`, to be present. `PREPARED_DENY` carries the canonical exact nine-field identity with zero JWKS bytes and omits field 5. The complete frame remains bounded to 256 KiB plus 2 KiB; unknown fields and other schema versions are refused. The nine-field identity and source provenance are defined by the [JWT verification provenance contract](../../system-architecture-jwt-and-token-contracts.md#signing-key-rotation-contract-normative), not by a raw JWKS controller or a finite readiness-plan read. + +Account returns `PREPARED_DENY` only for one coherent current durable `PREPARED` promotion linked to the exact operation and trusted owner identity, with the live ConfigMap UID, both complete Account-owned JWKS/marker values, public-data digest, and applicable prior receipt and mounted-proof evidence matching across stable owner reads. A live `ACTIVE` marker with a completed `ActiveJwksPromotionReceipt` must match its exact operation, UID, resulting `resourceVersion` and data-marker digest. During that same writer's proven CAS-before-receipt window, a missing ACTIVE receipt may instead support denial only: the exact prior prepublication receipt and mount, dispatched private promotion and full canonical `PrivatePromotionReceipt.fromStored` preimage/linkage/digest must validate, both live owned values must equal this operation's complete intended ACTIVE projection, and the valid opaque observed `resourceVersion` must differ from the exact prior version. A digest-shaped string alone is insufficient; versions are never numerically ordered. Partial, corrupt or mismatched receipt evidence remains terminal. This exception produces zero JWKS bytes and no recovery eligibility, creates no receipt, and grants no publication, promotion, pruning, readiness or admission authority. Serving keys after PREPARED denial and clearing that latch still require the exact completed current ACTIVE receipt, durable COMMITTED owner and protected coherent same-pin mounted bytes. `committed_recovery_eligible` may be true only when the returned projection itself meets that committed receipt-backed boundary. An older committed ACTIVE cannot qualify a newer PREPUBLISHED projection; ordinary receipt-backed PREPUBLISHED bootstrap returns a noneligible snapshot. + +Before PREPARED, a missing prepublication receipt has a separate temporary classification only when the exact current generation and immutable intent plus trusted enrollment or the exact prior committed receipt prove the predecessor. The live UID and complete owned values must prove either that exact prior projection or this operation's exact additive PREPUBLISHED projection, with its closed marker bound to the pending generation, operation, request/receipt digests, trust/API identity and both expected active identities. The supported initial predecessor has canonical empty JWKS and no marker; its full snapshot commitment must match enrollment and intent, including reconstructed unchanged unowned data after CAS. Unknown or unprovable predecessor shapes remain terminal. Additive qualification retains the exact prior keys and adds only the current target. A qualified window returns ordinary unavailable with no snapshot, new keys, repin or cache-age renewal; already cached prior keys remain usable only to their original expiry. It does not install a PREPARED-until-COMMITTED latch before pending-key readiness. The exact publication receipt and mounted correspondence remain prerequisites for normal readiness progression. + +The owner reads through `AccountJwtJwksTrustedSource`, retaining its protected binding, coherent owner projection, and exact live ConfigMap checks. The peer and protected Account binding are checked before and after the read. A public read begins with a locked enrollment row and retains one immutable protected materializer/API/source-UID/pin anchor. Proven owner movement permits at most three complete internal qualification trials under the same incoming deadline and cancellation, without sleeps or a reset. Before retrying, the intervening live bytes must qualify against a complete coherent bracket at that original anchor, including exact UID and complete owned bytes with resource-version-only drift; this justifies only another full bounded trial, never a response from moving brackets. Genuine UID, trust, owned-byte or marker tamper is terminal and is not retried. Only a fully stable trial may return evidence or install the initial pin. Repeated unresolved movement remains terminal and never becomes an ordinary outage or key-serving fallback. Once a call observes owner movement, later API/SQL unavailability, missing resources, cancellation or deadline exhaustion is terminal too; an ordinary first-trial outage retains its existing unavailable behavior. A later fully coherent trial that proves the existing prepublication temporary window or exact-UID and exact-owned-byte resource-version-only drift resolves movement into the existing unavailable classification, after checking the original cancellation/deadline budget. It returns no snapshot, installs no pin and renews no cache age; dependency failure is not that qualification. Established-pin reads do not hold the first-install monitor across remote work; first installation remains synchronized and cannot replace a pin. The ordinary issuance adapter retains its existing retry behavior. A valid `PREPARED_DENY` is a method-response disposition, distinct from transport failure. Missing or wrong workload authority returns `PERMISSION_DENIED`, malformed request frames return `INVALID_ARGUMENT`, temporary source unavailability or an unclassified handler fault returns `UNAVAILABLE`, and typed custody/publication rejection (including failure to encode Account's produced snapshot) returns `FAILED_PRECONDITION`. The private trusted-source rejection category remains terminal; a generic handler exception is not custody evidence. A coherent owner projection with the exact ConfigMap UID and Account-owned JWKS/marker bytes but a different `resourceVersion` remains unavailable: no unreceipted snapshot is returned and the immutable receipt is not rewritten. Recovery requires a later exact owner-receipted publication. This preserves ordinary resource-version-only, transport, and issuance behavior; unproved pruning and ambiguous, unqualified unreceipted, tampered, or unsupported lifecycle evidence remain terminal. Consumers do not infer retryability from generic transport status codes without exact authenticated peer and server-origin proof. No private keys or credentials are returned, and no signing, registry, readiness, promotion, or admission authority is granted. Composition and the exact bearer-exempt method classification are recorded in [configuration](./configuration.md#private-current-public-jwks-read); Game Session's cache and deny-latch consequences are defined in its [JWKS consumer contract](../game-session-service/api-contracts.md#steady-state-account-public-jwks-provenance), while focused proof and deployed prerequisites belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-and-game-session-steady-state-jwks-deny-gate). + +Public pruning is not implemented by this receiving boundary: it supplies no authorized Account public-pruning producer, pruning receipt, or current-read pruning projection. Same-UID removal of an owned public key without matching owner evidence remains terminal; restored bytes cannot clear an already terminal consumer. The [writer-window inventory and proof](../../../project-management/implementation-tracking/player-access-and-session.md#actual-public-jwks-writer-windows-and-pruning-limit) record supported writer-window qualification and retained limitations. No receipt-less snapshot, pruning fallback, or runtime activation is defined here. + ## Normative Target Contract Account is the API boundary for platform identity, durable membership, entitlement authority, and Account-owned authentication mutations. This document retains endpoint and transport consequences; gameplay admission and JOIN identity binding are defined by [Authentication](../../system-architecture-authentication.md), while token refresh, replacement, generation, revocation, fencing, and logout are defined by [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index ce8775571a..da7982e6f6 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -68,3 +68,23 @@ The source-only Control-UI issuance preparation reads the configured margin thro ## Proto Files The gRPC schemas for this service live in [`protos/account/v1`](../../../../protos/account/v1). Use `./gradlew generateProto` to regenerate Java stubs when the definitions change. + +## Canonical Gameplay LOGIN Receiving + +Canonical credential envelopes and exact-original retirement share the existing AccountService registration through `AccountGameplayAuthenticateReceiver`. The receiver, complete initial-LOGIN source graph and protected source selection all require `firemud.account.gameplay-login.enabled=true`; they are absent by default. `AccountGameplayLoginSourceConfiguration` composes the existing issuance/evidence/encrypted-response repositories, protected signer and trusted JWKS reader, issuer/account projection publisher, token registry, commit, activation and exact response-recovery owners. Registration supplies no synthetic owner evidence and performs no enrollment, key generation, publication or Redis mutation. + +The enabled composition requires these explicitly delivered inputs: + +- `firemud.grpc.workload-namespace` and `firemud.account.public-jwks.api-binding-path=/etc/firemud/account-jwt-api/binding.json`. The existing protected API binding and enabled `firemud.account.jwt-signer.materialization` trust binding must be readable and agree on environment, cluster, namespace and cluster/namespace incarnations. Their namespace must equal the configured workload namespace. The API identity is pinned at composition and rechecked by the existing owners on use; this does not create the enrolled signer, committed promotion or Account-owned public publication evidence. +- `firemud.account.gameplay-login.coordination.uri`, delivered through protected application configuration, selects only the dedicated standalone Coordination endpoint. Its shape is `rediss://account_coord_app:@:/0`; missing credentials, another principal/database, plaintext, URI query options and fragments are rejected. TLS peer verification remains enabled against the platform-provisioned JVM trust anchors. Do not put this credential-bearing value in diagnostics or substitute generic `firemud.redis.*` configuration. The dedicated Lettuce provider disables automatic reconnect and closes with the application; the existing Redis owner independently checks the live ACL identity. +- `firemud.account.gameplay-login.coordination.command-timeout-millis`, `required-local-aof-count`, `required-replica-aof-count` and `acknowledgement-timeout-millis` under that same `coordination` prefix. Both timeouts must be between 1 and 60,000 milliseconds; the local AOF count must be one, and the replica count must be between one and sixteen. Game Session's separate qualified single-node exception does not apply to Account. No timeout or ACK policy is inherited from the ambient Redis client. +- `firemud.account.gameplay-login.registry-cleanup-margin-millis`, explicitly between zero and 300,000 milliseconds. The registered record byte ceiling remains the fixed approved delegation profile limit; this margin does not authorize cleanup of held disposal markers or retained SQL evidence. +- The absolute normalized `firemud.account.gameplay-login.request-digest-keyring-path` and `firemud.account.response-envelope.keyring-path` mounts. Existing mounted-key readers retain their active/retained-key, freshness and withdrawal checks; configuration does not create keys or replace absent mounted material. + +Missing or mismatched protected trust, absent selectors and invalid explicit policy prevent enabled composition. Missing current key, enrollment, publication, authority or Redis evidence still denies the existing owner operation. Source-bearing requests never fall back to legacy Authenticate. This configuration does not provision credentials, qualify external Redis reset/restore/promotion continuity, register Game Session's separate initial-context authority or enable gameplay admission. Source and proof status belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). + +## Private Current Public-JWKS Read + +`firemud.account.public-jwks-read.enabled=true` separately composes the private [current-publication read](./api-contracts.md#private-current-public-jwks-read); it is disabled by default. `AccountPublicJwksSourceConfiguration` selects this read or canonical gameplay LOGIN and explicitly imports the pure `AccountProtectedJwksSourceConfiguration` owner. The latter supplies one protected API/client/trusted-source graph without a component-scanned stereotype or consumer-selection condition; another independently selected Account consumer imports that same owner without selecting LOGIN or the private public-read receiver. The read alone requires the workload namespace, fixed `firemud.account.public-jwks.api-binding-path=/etc/firemud/account-jwt-api/binding.json`, enabled existing materializer trust binding, Account signer/publication repositories and transaction manager. It does not require LOGIN Coordination Redis or request/response keyrings. Enabling both consumers does not create duplicate trust sources. + +The existing ordinary gRPC listener registers the receiver under that opt-in. The exact `account.v1.AccountPublicJwksReadService/GetCurrentPublicJwks` entry in both application profiles exempts only bearer authentication; the global TLS peer identity interceptor and method-local same-namespace Game Session workload guard remain mandatory. A current protected publication must already exist. Configuration performs no enrollment, publication, credential provisioning, runtime activation or traffic opening. Proof status and remaining custody requirements belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index fe28cf005a..bf2f6cc6f2 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -26,7 +26,7 @@ The additive [V1003 source-protection storage](../../../../services/account-serv The manually composed admission acquisition owner reads the retained original Account participation and Game Session attempt in a short transaction, obtains a fresh authenticated Game Session current-attempt read with no Account transaction open, then uses Account's existing currentness callback and source-key-before-protection lock order to install or replay the immutable protection. A separate committed read verifies the exact current protection bytes. The settlement owner reads the retained protection, obtains the exact Game Session terminal through its purpose-specific authenticated read outside SQL, stores the matching immutable Account settlement, and independently reads that receipt back. A missing, pending, unavailable, expired, or mismatched result does not release Account's source-writer exclusion; neither acquisition nor settlement renews the original lease. These source owners remain unregistered and provide no production admission or activation path. The [API contract](./api-contracts.md#startsession-admission-protection-acquisition) owns the transport boundary, and the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) owns proof status. -Account has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. It adds no endpoint or runtime registration; deployed ACL/TLS, signer-key custody, caller authentication, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. +Account's initial private gameplay LOGIN source graph has an explicit default-off composition for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. The [configuration owner](./configuration.md#canonical-gameplay-login-receiving) specifies its required protected delivery and policy inputs. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. Conditional registration through the existing Account gRPC service does not provision signer enrollment, committed publication, key material or Redis custody; deployed ACL/TLS, consumer authorization, gameplay admission and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. Account's unregistered original-ACK owner preserves the original physical COMMIT and its separately committed receipt. Forward V1013 extends historical receipt recovery to PostgreSQL 18 while retaining V144/V146 and the original evidence. The private owner captures one fixed snapshot and WAL fence, releases its SQL locks, positively observes coverage of that unchanged fence, and independently compares the exact receipt. Focused PostgreSQL 18 proof covers this recovery boundary. The manually composed Java owner and current full migration lineage require PostgreSQL 18; the retained SQL reader’s historical PostgreSQL 16 predicate does not establish Java-owner or full-lineage support on that major. This source remains unregistered and supplies no caller authentication or gameplay admission. Migration provenance, proof and remaining gaps belong to the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). @@ -36,6 +36,8 @@ Proof qualification: the earlier `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` run Account V99–V125 adds passive owner-storage foundations for signer desired state, mounted-material readback evidence, Account-owned JWKS publication, readiness/promotion receipts, and validator-inventory snapshots, together with strict bindings, typed evidence carriers, and focused repository/profile proof sources. The mounted-bundle signing and readiness-owner code in this source preparation is not registered to an RPC, coordinator, scheduler, or runtime consumer; promotion execution, receiver invocation, startup readiness, and validator currentness enforcement remain inactive. These storage and source-proof additions do not establish a runtime issuer/readiness path or close `PLAY`, admission, or activation. The canonical token and signer contract remains [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); this document records only Account-local implementation consequences. +The private current-public-JWKS read classifies responses from Account's current durable publication state and exact owner, receipt, and projected-mount evidence. It is a read path: it does not advance key-ring lifecycle, promote a signer, prune material, or activate token use. The [Account API contract](./api-contracts.md#private-current-public-jwks-read) owns the response disposition and recovery-eligibility rules; the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-and-game-session-steady-state-jwks-deny-gate) owns proof status and activation limits. + The current Account owner-source preparation adds V126 storage, default-inactive StartSession operator authorization composition, Control-UI issuance and Redis coordination sources, Account-owned JWKS and signer-materialization adapters, and readiness-probe sources. V126.2 records one immutable cleanup deadline on new Control-UI owner rows, separate from JWT `exp`, and requires the same value in owner readback, registry bytes, and Redis physical-expiry readback. Retained rows without that evidence remain unchanged and are denied for current-source use or recovery; no TTL rewrite or identity reissue is performed. The V126.2 retained-row migration fixture is defined in `AccountControlUiIssuancePostgresIntegrationTest`; direct PostgreSQL tamper proof for changing a newly written cleanup deadline remains missing. StartSession response recovery retains the raw AAD v1 byte grammar, accepts a 128 KiB authority bundle and 144 KiB total binding/response, and stores envelopes up to 160 KiB. V126.3 replaces only the old size constraint; it does not rewrite ciphertext or alter V126.1 erasure and immutable-evidence guards. StartSession composition defaults off. Materializer trust defaults off, and missing trust denies every materializer RPC. Missing bootstrap-coordinator composition denies enrollment and promotion operations; trusted generation requests, observations, and result reads remain available. No runtime issuer, promotion coordinator, or consumer coordinator is registered. The earlier Hosted Validation run `38113324723` at `f6d34031221a3337e7a958ac4b085554460668c9` is historical owner-workflow fixture proof. Current exact-head Account fixture results and limits are recorded in the [AA-1.3 tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-operation-and-signer-source-preparation); they do not establish overall CI success (aggregate validation remains red on an unrelated Gateway fixture), deployed mTLS, the complete Logging & Admin/Game Session/World flow, player-facing JWT readiness, full-service boot, trusted deployment, or activation. Direct PostgreSQL proof that a newly written cleanup deadline cannot be changed remains missing. JWT and signer behavior remains canonical in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). V126.1 adds an owner-transaction-only erasure primitive for the encrypted StartSession operator response after its already-recorded response-recovery deadline. Database wall time decides eligibility and stamps the one-way erasure marker. The compact tuple, fingerprint, authority and exact redemption evidence remain immutable; deletion, early erasure, deadline changes and ciphertext resurrection remain denied. ISSUE and RECOVER fail closed after erasure instead of rebuilding the response. This preserves V126's checksum and does not select a new retention interval, erase compact evidence, register a cleanup scheduler, or enable runtime composition. Fresh-install and retained-V126 migration test definitions cover the boundary; replacement physical PostgreSQL execution remains required. @@ -82,7 +84,7 @@ Current public bootstrap, direct-scope, JOIN, connect-token and numeric entitlem The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). -The unregistered canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). No runtime bean, RPC, authenticated caller or signer/registry composition is activated; deployed timing parity remains unproved. +The canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. The adapter participates only in the explicitly enabled protected LOGIN composition; default deployment behavior remains unchanged. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). Deployed authenticated issuance and timing parity remain unproved. Local unregistered Account owners now cover tenant-creation intent, admission, current authorization, and final initial-owner consent/reauthentication completion; the private Game Design receiver is also present. The dispatch and original read/close/recovery composition is present locally, while physical cross-owner qualification and public/default registration remain incomplete; creation and runtime admission are not enabled. The normative admission and recovery ordering belongs to [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md#account-tenant-creation-admission-receipt); implementation and proof status remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-tenant-creation-admission-preparation). @@ -180,7 +182,7 @@ If you change Redis usage for this service, you must read and apply: ## Session and Token Model -Initial LOGIN disposal uses forward V1005 `account_initial_gameplay_login_disposals` as immutable purpose identity, durable intent, closed owner-proof storage and original-request anti-resurrection guard. Account first locks the original Account when present, then the shared request advisory lock; a no-row race that discovers a newly inserted original retries in Account-first order. The new issuance writer trigger and repository/recovery/fence checks deny guarded original operations without modifying V150/V151, completing public logout, deleting issuance evidence or changing unrelated generations. Exact known hashes receive the single-key denied tombstone, pinned durability/readback and immutable physical proof described in the [token owner contract](../../system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal). No-row/unbound guard and complete current shape are independently read back from the durable primary with no Redis lookup. They remain `PENDING` because the protected retained binding-history/restore qualifier needed to produce the distinct `NO_ISSUANCE_BINDING` terminal proof is absent; bare current shape cannot replace it. Retention is held in SQL and denied Redis markers until explicit owner horizons and safe cleanup exist. These sources register no Spring bean or endpoint and provide no runtime activation proof. +Initial LOGIN disposal uses forward V1005 `account_initial_gameplay_login_disposals` as immutable purpose identity, durable intent, closed owner-proof storage and original-request anti-resurrection guard. Account first locks the original Account when present, then the shared request advisory lock; a no-row race that discovers a newly inserted original retries in Account-first order. The new issuance writer trigger and repository/recovery/fence checks deny guarded original operations without modifying V150/V151, completing public logout, deleting issuance evidence or changing unrelated generations. Exact known hashes receive the single-key denied tombstone, pinned durability/readback and immutable physical proof described in the [token owner contract](../../system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal). No-row/unbound guard and complete current shape are independently read back from the durable primary with no Redis lookup. They remain `PENDING` because the protected retained binding-history/restore qualifier needed to produce the distinct `NO_ISSUANCE_BINDING` terminal proof is absent; bare current shape cannot replace it. Retention is held in SQL and denied Redis markers until explicit owner horizons and safe cleanup exist. The explicit default-off LOGIN composition includes this disposal owner through the existing Account service; it supplies neither the missing history qualifier nor runtime activation proof. **Target state:** Authentication generates a `control-ui`, player-bootstrap, or receiver-specific private player-delegation JWT and establishes exactly one server-side `session:auth:token:` registry record before returning it, following [ADR 0035](../../decisions/adr-0035-single-record-issued-token-registry.md). The record proves exact issuance and active state; signed claims plus Account-owned revocation/version state determine tenant and global authority without scope-duplicated token keys. **Current runtime:** it still uses the legacy Account session key and does not yet provide this registry proof. diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 15ae05a054..f7f629e831 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -2,6 +2,14 @@ Player-facing controller binding and takeover are owned by [Session Behavior](../../system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02), fresh-edge reconstruction is owned by [Reconnection](../../system-architecture-reconnection.md#client-reconnection-behaviour), and versioned output/late rendering are owned by [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#output-model). The APIs below record only Game Session's local control-plane and forwarding consequences; they do not duplicate those player-facing contracts. +## Steady-State Account Public-JWKS Provenance + +The separately disabled [current-publication consumer](./configuration.md#steady-state-account-public-jwks) authenticates the exact same-namespace Account workload before consuming the private [Account public-JWKS response](../account-service/api-contracts.md#private-current-public-jwks-read). Before interpreting either disposition, it validates the response's exact nine-field source identity against the existing pin. It compares a bounded `SNAPSHOT` with exact protected projected bytes before and after the read and pins the actual returned source identity for its lifetime. It accepts no alternate file, URL, or inline-key authority. After qualification, a different valid public snapshot from authenticated Account under the unchanged pinned identity is retryable while protected mount reads remain stable and exactly equal this instance's last accepted bytes. A publication transition between two intact protected reads is also retryable only when the first mounted bytes equal the last accepted snapshot and exactly match the first authenticated Account snapshot, the second mounted bytes exactly match the second authenticated Account snapshot under the same pinned identity, both public-key profiles are valid, and a custody recheck still matches the second mounted bytes. Neither case installs a snapshot or renews the cache age; a later stable exact comparison is required before installing the new keys. Startup mismatch, arbitrary local changes, outage with changed local bytes, unsafe or missing projection, source-identity or namespace replacement, authentication/schema/custody/profile failure, and an AtomicWriter change during a protected read still refuse the consumer until explicit requalification. Successful recovery requires the usual exact coherent Account and mounted-byte comparison; it never repins the source. + +A `PREPARED_DENY` response atomically sets the verifier's prepared-deny latch and immediately blocks every cached key, regardless of cache age. Startup qualification and proactive refresh handle this typed disposition before cached-key use, so the deny takes effect even when no player request is waiting on the Account read. The latch never renews snapshot age or repins the Account identity. It clears only after both later coherent Account reads return same-pin `SNAPSHOT` responses with `committed_recovery_eligible=true` and stable protected mounted bytes exactly equal those snapshots. A local monotonic denial counter also prevents a refresh begun before the deny from installing an older snapshot after a separate source recovery. Until both the Account snapshot and protected bytes satisfy that predicate, all cached keys remain blocked. A noneligible `SNAPSHOT`, resource-version-only change, transport retry, or repeated deny cannot clear the latch; outside the latch, ordinary receipt-backed `PREPUBLISHED` bootstrap and the existing cache behavior remain unchanged. Ambiguous, unreceipted, tampered, wrong-peer, changed-pin, or unsupported pruning/lifecycle evidence remains terminal and never falls back to cached keys while latched. + +The existing public-only cache and explicit-profile asymmetric verifier supply cryptographic evidence only. Finite rotation-readiness metadata and its plan lifetime are not dependencies. Initial LOGIN still requires its independent Redis/reset qualification and all current registry, caller, and authority evidence. This consumer does not expose a gameplay endpoint, complete admission, or enable LOGIN/PLAY; Account and Game Session compositions remain default-off. No deployment or activation is claimed. Current proof limits belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-and-game-session-steady-state-jwks-deny-gate). + ## Target Control-Plane Summary Target state makes Game Session the authoritative owner of region/tick coordination, each instance's exact owner tuple `(scriptPatchVersion, scriptPinEpoch, controlPlaneRequestId)`, and append-only script rollout history. The request ID is owner-grounded transition/readback evidence; the patch and epoch remain the execution fence. Owner mutations are fenced and idempotent; Logging & Admin is the external operator ingress, and session front ends forward region work without writing lease-owned state directly. Authoritative owner reads gate script admission and convergence. See [Scripting Control-Plane API](../../system-architecture-scripting-control-plane-api.md#game-session-patch-pinning). diff --git a/design/architecture/microservices/game-session-service/configuration.md b/design/architecture/microservices/game-session-service/configuration.md index 9e594b15da..b10f6718c4 100644 --- a/design/architecture/microservices/game-session-service/configuration.md +++ b/design/architecture/microservices/game-session-service/configuration.md @@ -84,4 +84,31 @@ The generated reference carries the current defaults, descriptions, valid values ## Authenticated TCP Receiving -The [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving) owns the dedicated Gateway-to-Game Session mTLS configuration and custody contract. This receiver requires distinct same-namespace workload leaves and a separately reachable internal TLS port; the ordinary HTTP/WebSocket route and shared legacy TLS leaf cannot supply its authority. Public receiving accepts only actual protected LOGIN/lobby source owners. Their runtime and protected-source composition is a separate successor boundary; absent owners or source qualification remain unavailable rather than selecting numeric entitlement or legacy credential fallback. See the [player access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) for current proof and missing provider boundaries. +The [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving) owns the dedicated Gateway-to-Game Session mTLS configuration and custody contract. This receiver requires distinct same-namespace workload leaves and a separately reachable internal TLS port; the ordinary HTTP/WebSocket route and shared legacy TLS leaf cannot supply its authority. Public receiving composes only actual protected LOGIN/lobby source owners. Missing source qualification remains unavailable rather than selecting numeric entitlement or legacy credential fallback. See the [player access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) for current proof and missing provider boundaries. + +`AuthenticatedGameplayRuntimeConfiguration` is separately disabled unless `firemud.game-session.authenticated-gameplay.enabled=true`. When explicitly selected, ordinary dependency injection requires an independently delivered `InitialGameplayLoginRedisBinding`, `InitialGameplayLoginCoordinationQualification`, `AccountAsymmetricJwtVerifier` and `CanonicalPlayerRouteReadService`, together with the receiving owners' SQL, transaction and client dependencies. Missing authority fails startup rather than silently skipping composition based on component-scan order. Neither source opt-in below selects this runtime composition. No deployment enables this selector, and no production external maintenance qualifier exists, so authenticated LOGIN remains unavailable. + +### Initial LOGIN protected sources + +`InitialGameplayLoginProtectedSourcesConfiguration` is disabled unless `firemud.game-session.initial-gameplay-login.protected-sources.enabled=true` is explicitly delivered. It composes only the dedicated initial-context Coordination connection provider and binding over independently delivered inputs. It does not register a public-key source, JWT cache or verifier. + +The remaining required properties share the `firemud.game-session.initial-gameplay-login.protected-sources` prefix: + +- `coordination.uri` is an independently delivered Secret-backed value with the exact `rediss` scheme, explicit host/port, `gamesession_coord_app` principal, nonempty credential and `/0` database. Query and fragment options are rejected. TLS peer/hostname verification is enabled, and the provider never consumes the ambient Redis factory or its endpoint. +- `coordination.command-timeout-millis` is explicit and between 1 and 60,000 milliseconds. +- `coordination.protected-binding-id` must identify the independently protected deployment binding. Configuration does not attest that identity or create maintenance authority. +- `coordination.profile`, `coordination.required-local-aof-count`, `coordination.required-replica-aof-count` and `coordination.acknowledgement-timeout-millis` select the existing [initial-context acknowledgement policy](../../system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy). Selecting `SINGLE_NODE_NO_FAILOVER` does not qualify the deployment as no-failover. + +The owner-local Lettuce provider disables reconnect before opening any binary connection and owns its dedicated client lifecycle. Each initial-context invocation owns its physical connection; the existing helper retains live principal, registered-script, same-connection acknowledgement and readback enforcement. Endpoint/TLS/ACL provisioning and deployment custody remain external prerequisites. + +This Redis source opt-in supplies neither a steady-state asymmetric verifier nor `InitialGameplayLoginCoordinationQualification`; the existing authenticated runtime composition requires both. The separately configured steady-state consumer below supplies only the former, while the external maintenance qualification remains unavailable. Account's `GetCurrentReadinessReceiverMetadata` and the Game Session protected readiness identity/JWKS readers belong to finite rotation-readiness operations with complete, unexpired plans. They are not ordinary LOGIN trust sources and are not composed here. The steady-state consumer below obtains Account-owned current publication provenance independently of readiness-plan lifetime under the [JWT verification and rotation contract](../../system-architecture-jwt-and-token-contracts.md#signing-key-rotation-contract-normative). This configuration registers no readiness receiver or gameplay endpoint, provisions no source, and establishes no LOGIN success, protected admission or runtime activation. Detailed current proof and remaining qualification belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). + +### Steady-state Account public-JWKS + +`firemud.game-session.account-public-jwks.enabled=true` explicitly composes the private Account read client, protected public projection source, `AccountPublicJwksCache` and `AccountAsymmetricJwtVerifier`. It is disabled by default and independent of the initial-context Redis configuration. `maximum-cache-age-millis` under that prefix is explicit and bounded to 2,000 through 300,000 milliseconds. A lifecycle-owned fixed-delay task refreshes at half that age and stops with the context; outages never renew the cached snapshot's age. The retryable qualified-mount publication-lag boundary is defined in [Steady-State Account Public-JWKS Provenance](./api-contracts.md#steady-state-account-public-jwks-provenance). It installs no mismatched snapshot and never renews cache age or admits an unknown key. Other invalid source or key evidence refuses cached keys until explicit requalification; remembered fingerprints and hard-denied keys retain their existing cache enforcement. A terminal scheduled refresh refusal logs `SOURCE_REJECTED` once at ERROR for that cache lifecycle; temporary unavailability escaping the finite fresh-cache allowance logs `SOURCE_UNAVAILABLE` at WARN and remains retryable. Neither diagnostic includes source evidence or exception details. + +Size `maximum-cache-age-millis` to at least twice the expected maximum projection propagation delay, plus margin for scheduling and the two sequential Account source reads. The fixed-delay refresh runs at half that age, so a publication just before refresh may leave only about half the original cache lifetime for convergence. The 300,000 ms upper bound may prevent this sizing for a slower environment; known-key verification then refuses with `SOURCE_UNAVAILABLE` after the original snapshot expires until a stable refresh succeeds. Unknown keys remain unavailable during publication lag even while the old snapshot is fresh. + +Enabling this consumer couples Game Session startup to Account availability: both initial source qualification and the initial cache refresh must succeed before the context starts. Each successful source load, including every scheduled refresh, performs two sequential Account reads around protected projection checks. Each Account read checks current owner/publication state and performs at least one Kubernetes principal review, two namespace reads and a ConfigMap read. Size refresh intervals and deployment rollout concurrency for that Account and Kubernetes API load. Cache refreshes share one in-flight source load without holding the cache monitor during I/O; still-fresh known-key lookups and hard-cutover invalidation remain available while it runs, and stale lookups wait for that load rather than using expired keys. + +The client requires existing non-plaintext workload certificate/key/CA settings, a valid `firemud.grpc.workload-namespace`, and the Account endpoint from ordinary service discovery. The protected public projection remains fixed at `/var/run/secrets/firemud/jwks/jwks.json`, with the [infrastructure public projection modes and delivery rules](../../infrastructure/environment-and-secrets-overview.md#authentication--jwt). Reads use a finite deadline and response-message limit, attach no bearer token, and verify the exact Account workload URI. Missing or contradictory custody fails closed; the mounted path is not provenance by itself. The [API consequence](./api-contracts.md#steady-state-account-public-jwks-provenance) and [implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) distinguish source composition from deployed trust, external maintenance qualification and gameplay activation. No deployment enables this feature in this slice. diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index ae4a0a4a80..cbb533f566 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -63,6 +63,7 @@ The sections below define the target-state runtime contract. Current implementat - The current `IpConnectionLimiter` stores the source address directly in `ipconn:
` keys and `sessionip:` values, and registration passes both keys to one Lua invocation without a shared hash slot, so it fails with `CROSSSLOT` on Redis Cluster. This is not the ADR 0087 opaque-HMAC subject contract and has no evidenced tenant/policy scope or current Cache/Rate-Limit loss profile. The limiter remains a current heuristic seam; convergence requires one mutation on one opaque subject bucket, session lifecycle correlation outside exact cross-key atomicity, an owner-declared subject scope, opaque full-digest mapping, and focused privacy, isolation, eviction, reset, clustered, and unavailable-store proof; no final reverse-index design is implied. - Current Redis session-context and movement writers persist a projection without the raw `game-session-account-delegation` JWT, preserving other binding fields. Canonical/index and movement legacy reads return the same non-secret projection without rewriting retained values or extending their lifetime. Existing stored bytes are not globally erased: owner-fenced retained-value cleanup, complete rotation/rebind metadata and the rest of [ADR 0031](../../decisions/adr-0031-revocation-safe-session-token-rotation-and-logout.md) remain incomplete. Focused receiving proof and limits are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#session-secret-and-presence-containment). - An unregistered initial-LOGIN journal, cleanup owner and exact-context Redis CAS/closure adapter are prepared independently of that legacy handler. The adapter follows the [initial-context owner](../../system-architecture-redis.md#initial-login-context-aggregate) and requires the separately supplied protected binding and external qualification; it does not implement legacy Redis context save/delete, trusted TCP custody or runtime LOGIN. Qualified source and physical proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). +- The default-off [initial LOGIN protected-source composition](./configuration.md#initial-login-protected-sources) supplies only a dedicated no-reconnect, verified-TLS Coordination client and binding over independently delivered inputs. It does not use the generic Redis factory or provide JWT trust or maintenance qualification. The separately default-off [steady-state Account public-JWKS consumer](./configuration.md#steady-state-account-public-jwks) supplies the asymmetric verifier; the real external maintenance qualifier remains absent, so the separately default-off [authenticated LOGIN runtime composition](./configuration.md#authenticated-tcp-receiving) remains unavailable. Finite rotation-readiness metadata and its protected projection readers cannot supply ordinary LOGIN provenance. Deployed Redis/source custody and live cross-owner proof remain separate prerequisites; no runtime activation or LOGIN success is established by this source preparation. - Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and durable logout invalidation remain implementation/proof gaps. Current reconnect suppresses private-context presentation without deleting retained rows; bounded receiving proof and the remaining episode/generation limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#reconnect-and-continuity). - Current live-presence registration, returned legacy projections and ordinary activity updates use `PLAYER`: no independently verified gameplay-grant carrier is available. JWT global/scoped roles and retained cached elevation grant no gameplay capability. Read projection does not persist the demotion or refresh TTL; ordinary activity writes retain their existing lifetime behavior and preserve other fields. The [authentication owner](../../system-architecture-authentication.md#global-role-to-route-class-matrix-normative) defines grant authority; [Player Experience](../../../project-management/implementation-tracking/player-experience-commands-and-communication.md#communication-social-and-presence) records implementation/proof limits. - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index 0de1aed2a0..8e43c48fbf 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -411,8 +411,9 @@ JWT verification model (normative): - Account Service remains authoritative for signing-generation validation, token-validation semantics, signer promotion, initial and subsequent JWKS publication, and public/private pruning. Account owns the desired per-environment key-ring state and the pruning decision, including which private-material slots may be pruned. In target non-exportable-signer mode, Account delegates only explicitly authorized private-key operations to the approved signer boundary; the signer may not validate tokens, promote a signer, publish JWKS, or prune key material, and no application workload outside that boundary mounts or receives private key material. In the interim Account-only mounted fallback, Account is the only application workload that mounts or uses private material; validators receive only public JWKS, and rotation automation cannot access signing material. - Target non-exportable-signer mode is ADR 0014's target private-key backend under the same Account authority model: signer custody replaces application private-key distribution and is not a second Kubernetes Secret writer or issuer. The fixed `jwt-signing-keys` Secret, its materialization-controller write/prune path, `FIREMUD_AUTH_JWT_SECRET_PATH`, the associated private/public projection proof, and Account-mounted private material are only the interim Account-only mounted fallback described by [ADR 0014](./decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md). The materialization controller has sole name-scoped authority to generate and `resourceVersion`-CAS-write that private signing Secret. It may execute only an Account-authorized private-slot pruning operation during reconciliation; it may not independently decide that pruning is due, choose private slots, or mutate desired key-ring state. Its CAS/pruning result is execution evidence for Account reconciliation, not an authority decision or desired-state update. None of these Secret, mount, or path requirements applies to target non-exportable-signer mode. Shared HMAC remains limited to local/dev or explicitly ephemeral CI compatibility and is not a player-facing fallback. Every issued JWT carries a stable `kid`. - Initial JWKS publication uses Account's normal publication authority; it is not a separate bootstrap writer or one-time authority. In target non-exportable-signer mode, readiness, token issuance, validator readiness, and protected traffic require authenticated signer health and generation/challenge-signature correspondence, convergence of the Account-owned public JWKS, and proof that no private key is mounted or distributed to application workloads outside the approved signer boundary. Hard-cutover readiness additionally consumes the Account-authorized signer retirement evidence defined below to prove disablement of the affected `kid`; a signer acknowledgement alone is insufficient. In the interim Account-only mounted fallback, those paths remain quarantined until the private/public projection proof succeeds. +- Ordinary validator trust is independent of finite rotation-readiness plans. The private Game Session current-publication read exposes the schema-2 snapshot or prepared-deny disposition with the exact nine-field source identity under the [Account read contract](./microservices/account-service/api-contracts.md#private-current-public-jwks-read). The authenticated same-namespace Account peer supplies provenance; a snapshot still requires comparison with the exact protected mounted public-JWKS bytes and coherent before/after evidence. PREPARED_DENY carries no JWKS bytes and blocks all cached keys regardless of freshness. Recovery follows the [Game Session owning contract](./microservices/game-session-service/api-contracts.md#steady-state-account-public-jwks-provenance): both later coherent eligible same-pin Account reads must agree with stable protected bytes. A file layout, raw JWKS endpoint, caller-supplied source label or readiness result cannot substitute for provenance, and source-identity replacement requires explicit requalification rather than silently changing the pin. This read grants no signing, registry, readiness, promotion or admission authority. - Validators cache known keys for a configured bounded maximum age and refresh proactively. An unknown `kid` triggers one forced JWKS refresh and one validation retry, then fails closed. -- A temporary JWKS outage may not invalidate a known key whose bounded cache entry remains fresh, except that current compromise-mode and post-restore deny markers plus local cache eviction always take precedence: a quarantined or denied `kid` is rejected even while JWKS refresh is unavailable. Validators must not extend cache age or accept an unknown key to preserve availability; this exception covers public-key retrieval only and never substitutes for an unavailable issued-token registry, issuer/generation authority, lease, binding, or other required Account evidence. +- A temporary JWKS outage may not invalidate a known key whose bounded cache entry remains fresh, except that PREPARED_DENY, current compromise-mode and post-restore deny markers plus local cache eviction always take precedence: a quarantined or denied `kid` is rejected even while JWKS refresh is unavailable. Validators must not extend cache age or accept an unknown key to preserve availability; this exception covers public-key retrieval only and never substitutes for an unavailable issued-token registry, issuer/generation authority, lease, binding, or other required Account evidence. ### Signing-Key Rotation Contract (Normative) 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 649e872d33..9b7a31ce69 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -446,7 +446,17 @@ The passive Account source-fence seam leaves Draft source mutation and abort pen ### Initial private gameplay LOGIN issuance source intake -Account's private gameplay LOGIN has fail-closed dispatch through the existing Account gRPC registration, but its issuer, response-recovery, registry, evidence-repository, trusted-JWKS and disposal graph remains unregistered. Canonical envelopes and exact-original retirement are unavailable without an independently supplied receiver and never select legacy credential fallback. The protected-source and runtime composition, including its configuration and focused proof, belongs to the successor source-composition boundary in [#3409](https://github.com/benhook1013/FireMUD/pull/3409). Game Session's protected Coordination binding, LOGIN/lobby runtime graph, external maintenance qualification and trusted Account verifier remain absent here; the authenticated receiver fails closed without them. The targeted source and fixture results, including their historical baselines and limits, are collected in [Initial private gameplay LOGIN source proof](#initial-private-gameplay-login-source-proof). +Account's private gameplay LOGIN has dispatch through the existing Account gRPC registration and an explicit default-off composition of the complete existing issuer, response-recovery, registry, evidence-repository, trusted-JWKS and disposal graph. Its protected configuration requires the independently delivered Account Coordination URI/principal, bounded explicit command/ACK policy with a positive replica minimum, canonical JWKS API binding, matching materializer/workload namespace identities and existing request-digest/response key mounts. Both initial issuer/account projection script contributions are installed; enabling a property does not create signer enrollment, committed publication or external custody evidence. Focused configuration tests use real intermediate implementations with controlled SQL, primary-credential, Redis transport and protected API/trust edges and therefore cannot qualify deployed custody or genuine LOGIN. Game Session still requires its independently supplied protected Redis binding, external qualification and trusted Account verifier; neither composition establishes playable LOGIN or canonical PLAY. The targeted source and fixture results, including their historical baselines and limits, are collected in [Initial private gameplay LOGIN source proof](#initial-private-gameplay-login-source-proof). + +The default-off Game Session source composition supplies a dedicated verified-TLS, no-reconnect Coordination client and explicit initial-context binding/ACK policy over independently delivered inputs. It supplies no JWT verifier, readiness client or maintenance qualifier. The finite operation-scoped readiness graph remains separate from steady-state LOGIN provenance. Account's explicit-import `AccountProtectedJwksSourceConfiguration` shares the protected trust graph across independently selected LOGIN and public-read consumers without requiring LOGIN Redis for the read. The steady-state consumer, cache/verifier and bounded refresh implement the [Game Session publication-transition contract](../../architecture/microservices/game-session-service/api-contracts.md#steady-state-account-public-jwks-provenance) and the [Account current-publication API](../../architecture/microservices/account-service/api-contracts.md#private-current-public-jwks-read). + +At correction source `f5ef41f9f17f5f6545e791eb5012ca8be3f85cf5`, focused local proof passes 107 cases with zero failures, errors or skips: 19 Account trusted-source and 6 current-read owner units; 4 Account ordinary-listener mTLS cases; 1 physical PostgreSQL immutable publication-receipt case; 23 Common Security cache, 4 read-codec and 11 asymmetric-verifier units; 23 Game Session projection-source and 9 consumer-lifecycle units; and 7 Game Session client mTLS cases. This selection covers RV-only refusal, forward recovery through a later exact owner operation, terminal UID/owned-byte tamper, bounded cache expiry and unchanged generic transport-status denial. Enabled Account main/unit/integration Checkstyle and SpotBugs, Java formatting and documentation checks pass. Thirty Account cases ran fresh; Gradle reused 77 unchanged Common Security and Game Session cases with matching inputs and retained their original XML timestamps. The source/transport fixtures use controlled protected and publication inputs; the PostgreSQL case proves receipt storage, not a live Kubernetes publication lifecycle. + +Historical proof at `231414edb5d16f4d6d9a8c4a80d5f03cc0dbd74b` passed 104 selected cases before the RV-only correction. The 70-case run at `a1817ef38b062c44614821524751e55d4f712ea7` and the 34-case Common Security run at `0f54a4a0a0c939704dc3ec00594d96afcabff6a7` cover earlier source boundaries; the latter predates the cache I/O and concurrency corrections. Earlier extraction/composition figures and their intermediate Markdown failures are superseded and are not current proof. + +At the earlier correction source, PREPARED promotion-window qualification remained open: the committed-signer reader refused PREPARED before active-fence and receipt checks. The fresh public-only typed-deny implementation and its separate proof are tracked under [the steady-state JWKS deny gate](#account-and-game-session-steady-state-jwks-deny-gate), without attributing that behavior to the historical run or changing issuance quarantine. Public pruning has no implemented producer/receipt/current-read projection in this source; changed pruning bytes remain unqualified. No automatic repair of an existing immutable receipt is demonstrated: without a later exact owner-receipted publication, RV-only reads remain unavailable and the existing bounded cache eventually expires. Generic `UNKNOWN`, `CANCELLED` and `ABORTED` recovery remains unproved without exact peer and server-origin evidence. Deployed custody, fresh-image runtime proof, reset/restore/promotion exclusion and LOGIN/PLAY activation remain unqualified; the authenticated runtime gate remains held. + +The predecessor protected-source graph at `66ebbd06` passed 187 cases with zero failures, errors or skips: 7 core evidence, 103 Account source/selector and 77 Game Session source/owner/client cases, together with Account and Game Session main/unit static, formatting, affected compilation and Markdown checks. Those results predate the current shared-source extraction and steady-state consumer; replacement proof for the changed source graph is recorded above. Controlled sources do not establish deployed Redis, PKI or maintenance custody. Canonical disposal and original-attempt rules belong to [JWT and token contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal), the [Redis initial-context acknowledgement owner](../../architecture/system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy), and [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status). Protected binding-history/restore qualification, production trust and custody, and runtime activation remain gaps; source fixtures do not establish authenticated intake or playable LOGIN. @@ -462,7 +472,7 @@ The checked-in local Compose, base and Kustomize configurations do not enable th The latest completed focused gate passes 54 Gateway and 94 Game Session cases with zero failures, errors or skips, including actual mutual-TLS WebSocket upgrade, wrong-workload/namespace refusal before HTTP origin headers, exact-result custody, overlapping replacement drain, shutdown revocation and friendly JOIN wire routing. These cases use controlled upstream Account/result sources and are not genuine end-to-end Account issuance or public LOGIN-to-PLAY proof. The first Account dispatch run preserved 144 passing cases and four failed reject-before-payload assertions. After moving canonical selector dispatch behind the existing peer guard, the exact 148-case Account suite passes with zero failures, errors or skips. The physical Tomcat connector case requires client TLS, accepts only the exact Gateway namespace/workload, denies forged headers over public HTTP and limits the dedicated listener to the gameplay path. -Affected main, unit and integration sources compile. The initial nine Checkstyle scopes and three Gateway SpotBugs scopes passed, while four Game Session static findings required correction. The corrected source snapshots singleton header values and retains the canonical parsed literal address with an IPv6 regression case. The later Game Session main/unit/integration and Account static recovery scopes pass; its Markdown environment failure is retained separately from the subsequent successful formatting and Markdown checks. The earlier complete source-composition graph has separately recorded Account and Game Session main/unit static proof in the successor; that historical result does not qualify this narrower patch boundary. Base NetworkPolicy contract passes; hosted chart and deployment preflight contracts remain locally unrun because Helm and kubectl are unavailable. Protected Redis client and runtime composition is retained in the successor; deployed Redis binding, external reset/restore/promotion exclusion, signing/currentness/source custody, final admission and real preview/CI LOGIN-to-PLAY remain incomplete. No fixture, mounted URI or process-local flag qualifies those authorities. +Affected main, unit and integration sources compile. The initial nine Checkstyle scopes and three Gateway SpotBugs scopes passed, while four Game Session static findings required correction. The corrected source snapshots singleton header values and retains the canonical parsed literal address with an IPv6 regression case. The later Game Session main/unit/integration and Account static recovery scopes pass; its Markdown environment failure is retained separately from the subsequent successful formatting and Markdown checks. The current-parent Account and Game Session main/unit static graph also passes as recorded above. Base NetworkPolicy contract passes; hosted chart and deployment preflight contracts remain locally unrun because Helm and kubectl are unavailable. Protected Redis client composition now exists, but deployed Redis binding, external reset/restore/promotion exclusion, signing/currentness/source custody, final admission and real preview/CI LOGIN-to-PLAY remain incomplete. No fixture, mounted URI or process-local flag qualifies those authorities. ### Account signer/currentness storage evidence preparation @@ -488,6 +498,30 @@ The #3038 warm-cache source-binding gap is corrected in the local receiver imple R1398 qualifies the subsequent review fixes with 64 fresh unit cases and 12 fresh controlled mTLS cases, all without failures, errors or skips; selected static analysis, full formatting, canonical documentation checks and the rendered Helm JWKS contract pass. The checks exercise response digest correlation, actual server-handler authentication context, caller drift and pre-effect denial, owner-coordinate binding, and readable but noncanonical projected-file refusal. Existing Account JWKS volumes now declare the required read-only file mode, without adding a Game Session or Pod-identity mount. This remains controlled preparation proof; production mount provenance, registration, custody, activation and current full CI are not established. +### Account and Game Session steady-state JWKS deny gate + +The default-off Account private current-public-JWKS read and Game Session consumer now have a typed prepared-deny path. Account returns that disposition only from coherent current durable PREPARED promotion evidence; committed recovery eligibility is limited to the returned projection when it is itself exact current committed ACTIVE and receipt-backed. Game Session authenticates the exact Account mTLS workload and pinned source identity before interpreting a disposition, then latches the deny across all cached keys regardless of cache age. Deny recovery follows the [Game Session owning gate](../../architecture/microservices/game-session-service/api-contracts.md#steady-state-account-public-jwks-provenance), which requires both later coherent eligible same-pin Account reads to agree with stable protected bytes. Canonical wire rules and local consumer consequences are owned by the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#private-current-public-jwks-read) and [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#steady-state-account-public-jwks-provenance); the [Account runtime](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) records its storage consequence. + +At implementation source `236bd229fdeab20980d62f786bda145d85096b4a`, the fresh local #3409 implementation based on `9bace990` has a focused selection of 122 passing cases with zero failures, errors or skips: 27 Common Security cache, 6 wire-codec, 27 Account trusted-source, 7 Account read-owner, 4 Account ordinary-listener mTLS, 32 Game Session projection-source, 10 consumer-composition and 9 Game Session client mTLS cases. Account and Game Session supply 89 fresh cases on the final source; Gradle reuses 33 unchanged Common Security cases with matching task inputs, source hashes and retained original XML timestamps. The prior 121-case run remains attributed to its own verified program-source patch and XML. The initial Account tamper-fixture failure and the SpotBugs volatile-increment finding are retained; corrected stubbing and an AtomicLong counter replace them without a suppression. Generated protobuf and main/unit/integration compilation prerequisites complete. Coverage includes receipt-present/absent PREPARED ACTIVE outcomes, current committed versus PREPUBLISHED eligibility, public moving-owner-bracket terminal refusal with unchanged ordinary retry, warm-key denial across outages, pre-deny refresh and hard-invalidation races, direct terminal-custody observation, both same-pin Account reads and coherent protected-mount recovery, and unchanged default-off composition. The exact affected formatting, Checkstyle, SpotBugs and documentation command outcomes are retained in the final local checkpoint receipt. No `c79` byte-proof is attributed to this work. The earlier `a1d983` index-1 scope remains partial and is not closed by this change. Account and Game Session compositions remain default-off; no deployment, LOGIN/PLAY activation, or broader finding-closure claim is made. + +### Actual public JWKS writer windows and pruning limit + +The actual Account-owner mutation inventory has two prepared source paths: [the prepublication owner](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java) calls its fixed-name ConfigMap CAS through `prepublishCurrentGeneration/publishAndRecord`, while [the bootstrap coordinator](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java) calls `publishActiveProjection` through `reconcilePreparedPromotionOnce`. Prepublication records its intent before API mutation, then persists the exact publication receipt in a separate transaction after CAS/readback. ACTIVE publication similarly updates the ConfigMap before the separate ActiveJwksPromotionReceipt transaction and final signer commit. Neither API acknowledgement nor pending owner intent authorizes a snapshot or clears a deny latch. + +Historical source `88512bd10f3de8d93aeffcb7474dc0fc40a6429f` established the real a1d983 index-1 defect: successful ConfigMap CAS followed by missing/rolled-back SQL receipt caused terminal public refusal, and later owner replay could restore Account's source while leaving the observing consumer permanently quarantined. Its 34 fresh cases and passed scoped statics belong to that test/docs-only source; the earlier 6-fresh/28-reused run, fixture diagnostics and unreachable next-generation attempt remain attributed to their retained source/XML. That witness did not correct the defect. + +The subsequent local source correction implements the approved separate writer-window classifications at [the Account contract owner](../../architecture/microservices/account-service/api-contracts.md#private-current-public-jwks-read). [The trusted source](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java) can qualify denial during the exact PREPARED ACTIVE receipt gap and ordinary temporary unavailability during the exact prepublication receipt gap. [The desired-state repository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java) exposes only the existing canonical private-receipt validation through a locked read-only recovery helper. No receipt is fabricated, no new producer or source activation is added, and ordinary issuance behavior is unchanged. Present receipt, trust, pin, tamper and unsupported-pruning refusal remain exact. The a1d983 fix is recorded at published source `8870a062`; subsequent source movement/concurrency and documentation/test obligations remain subject to parent integration and adjudication. + +Post-bootstrap planned rotation has another explicit capability gap: [the desired-state repository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java) refuses generation creation when a signer is already committed and no durable rotation request exists. The only generation-creation entry is guarded by absence of an active signer; the materialization service delegates to it and no supported rotation-request intake was found. A mock next-generation record does not establish that producer. The attempted physical second-generation setup is retained as a failed reachability witness; the corrected negative case proves unchanged owner/receipt/history evidence, no API mutation and continued use of the already committed cached key. Post-committed next-generation publication and the pruning lifecycle remain unimplemented and physically unqualified, without fabricating a generation pointer or bypassing the guard. + +The two owners are not composed as production beans by this source preparation; materialization entry points use an optional supplied coordinator. Diagnostic delivery is a separate trust boundary. Standalone/hosted-demo Helm can manage the diagnostic public ConfigMap; hosted PR rendering filters that ConfigMap before deployment, and credential provisioning creates it only when absent. The checked-in preview deployment principal has broad namespaced ConfigMap permissions, so Account-exclusive deployed custody is not established by the Java call inventory. Legacy player-facing Kustomize still names a JWKS Secret rather than this canonical ConfigMap. These paths grant no canonical pruning authority. + +The finite tracked-file search covered all service API/JWKS writes, Account caller symbols, ConfigMap references, kubectl mutation verbs, and Helm install/upgrade paths. No authorized Account public-pruning producer, durable pruning receipt, or pruning current-read projection was found. The [low-level fixed-name CAS](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java) can mechanically accept a reduced valid public key set from a trusted caller, but that capability is not an authorized pruning workflow. The prepublication owner retains existing keys and appends the pending key; readers require exact owner-recorded bytes and retained-key correspondence. A same-UID unowned removal is terminal and later byte convergence cannot restore an already terminal cache. + +The current correction's initial focused selection passes 71 fresh cases with zero failures, errors or skips: trusted-source 35, desired-state repository 16, publication repository 6, prepublication owner 7 and PostgreSQL persistence/writer windows 7. Parent integration then identified a missing semantic marker gate in the new additive path; the existing exact PREPUBLISHED validator is reused for that branch, with recomputed self-consistent malformed/ACTIVE/unknown marker controls. The final affected selection passes all 72 cases fresh with zero failures, errors or skips: trusted-source 36, desired-state repository 16, publication repository 6, prepublication owner 7 and PostgreSQL persistence/writer windows 7. The prior 71-case run remains attributed to its earlier source/XML. Exact formatter and required static/documentation outcomes are retained with the local checkpoint. Physical cases retain the same bounded reader's actual PostgreSQL blocking PID and absent committed receipt assertions, rollback, both writers' lost API replies and durable SQL-commit acknowledgement loss, exact replay and normal pending-key readiness. They qualify deny across cached-key outages and later committed owner/mount recovery, preserve original cache expiry during temporary prepublication failure, and retain terminal tamper. Corrupt stored private-receipt digest is tested through the repository unit seam; immutable physical rows are not bypassed. The Account/cache harness is not fresh Game Session transport/protected-mount proof; unchanged Game Session/Common implementation proof remains separately attributed to `236bd229`. Production custody, post-committed rotation/pruning lifecycle, deployment and LOGIN/PLAY activation remain unqualified. + +The local follow-up on `8870a062` qualifies bounded complete public-read requalification for proven owner movement under one immutable anchor and incoming deadline, locked first enrollment and independent established-pin reads. It preserves terminal genuine tamper, the exact three-trial exhaustion boundary, writer-window receipt/deny behavior and default-off composition. After observed owner movement, retry API/SQL outage, missing resource, cancellation or deadline expiry is terminal; ordinary first-trial outages retain their previous behavior. Queued initial readers leave the monitor once another caller has installed the immutable pin. The historical-key fingerprint case now pins and positively loads the valid source before testing actual missing/substituted retained keys with a newly generated same-kid modulus; earlier passing selections did not prove that substitution. Final affected focused qualification passed 84 fresh cases: 47 trusted-source, 17 desired-state repository, 6 publication repository, 7 prepublication service and 7 physical PostgreSQL cases. The earlier 81-case run remains attributed to its earlier source; initial fixture failures are retained separately. The 84-case checkpoint is retained as its own source baseline. A bounded continuation distinguishes fully verified stable prepublication and exact-owned-data resource-version-only temporary classifications from dependency failure after movement; final affected continuation qualification passed 87 fresh cases (50 trusted-source, 17 desired-state repository, 6 publication repository, 7 prepublication service and 7 physical PostgreSQL), including both stable temporary controls, version-only moving-bracket requalification and retained terminal outage/cancellation, three-trial and tamper controls. Current LOGIN status is selectable default-off dispatch/composition, and prepared-deny recovery follows the linked two-read Game Session owning gate; historical source proof retains its original registration scope. + ### Direct-text JOIN client and command receiving preparation The local preparation adds a typed `JOIN` command/parser, Account scope/JOIN clients, immutable request retry, response-bound world selection, observed proxy UUID and separate numeric transport-session correlation, a bounded original-menu snapshot, and the [authenticated lobby SQL companion](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion). These are manually composed sources; no production receiving registration or admission authority is established. The [Authentication contract](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) owns caller-bound scope and logical JOIN attempts, the [Redis menu contract](../../architecture/system-architecture-redis.md#direct-text-worlds-ui-menu) owns menu storage and recovery, and [Redis Ops Access](../../architecture/system-architecture-redis-ops-access.md) records the missing protected-connection binding and deployed ACL. The [Game Session runtime owner](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion) owns SQL retention and ordering consequences. @@ -599,7 +633,7 @@ With canonical scope consumers absent from the default composition, Account conn | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal retained numeric subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; the canonical UUID billing-owner detection gap is recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving), and retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [StripeHostingSubscriptionProvisioner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java); [AccountHostingSubscriptionProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java); [StripeHostingSubscriptionProvisionerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java); [AccountHostingSubscriptionProvisioningServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java); [AccountHostingSubscriptionDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [Authenticated TCP receiver](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java); [live LOGIN custody](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java); [verified TCP origin](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedTcpProxyOrigin.java); [dedicated mTLS Gateway client](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java); [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [authenticated receiver units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java); [live custody units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java); [Gateway mTLS client units](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java); [TCP listener admission integration](../../../services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Authenticated TCP receiving preserves the Gateway-verified origin over the dedicated exact-namespace mTLS hop and retains LOGIN custody on the original live backend generation. Missing protected owners or custody fail closed as `UNAVAILABLE`; malformed commands and missing local LOGIN/WORLDS/REALMS steps return bounded actionable errors. Source and controlled-component proof do not qualify a deployed authenticated LOGIN-to-PLAY chain, canonical admission, fresh-image runtime behavior, or production Redis/PKI/source custody. Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [Authenticated TCP receiver](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java); [live LOGIN custody](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java); [verified TCP origin](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedTcpProxyOrigin.java); [dedicated mTLS Gateway client](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java); [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [authenticated receiver units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java); [live custody units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java); [Gateway mTLS client units](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java); [TCP listener admission integration](../../../services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Authenticated TCP receiving preserves the Gateway-verified origin over the dedicated exact-namespace mTLS hop and retains LOGIN custody on the original live backend generation. Missing protected owners or custody fail closed as `UNAVAILABLE`; malformed commands and missing local LOGIN/WORLDS/REALMS steps return bounded actionable errors. Source and controlled-component proof do not qualify a deployed authenticated LOGIN-to-PLAY chain, canonical admission, fresh-image runtime behavior, or production Redis/PKI/source custody. Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN has selectable default-off dispatch through the existing Account gRPC service and composition of its existing owner graph; genuine runtime caller authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | @@ -874,7 +908,7 @@ After the narrow static-analysis corrections, 30 focused Account receiver cases This preparation is owned by `AA-2.1` in [Capability Status](#capability-status). -Account now contains an unregistered initial private gameplay LOGIN source slice: request-bound credential digests, the canonical LOGIN owner, Account signing and JWKS trust sources, pending and committed issuance owners, bounded issuance repositories and DTOs with V147–V157.1 migrations, pinned Coordination Redis registry/projection scripts, and encrypted response-envelope recovery. It uses the explicit initial `game-session-account-delegation` profile only; caller-selected profile/property bypasses, new endpoints, Spring runtime registration, remote credential provisioning, and consumer activation are outside this cut. The existing mounted signer bundle retains its stronger Control-UI/readiness and callback-redaction behavior, while authority reads are added around the receiving canonical sourceVersion/issuanceFence projection encoder. At original source head `8df6c870801f96a902742da0223f42cd1cfe527f`, consolidated local Account/Common checks, jOOQ generation, migration-version checks, integration-source compilation, formatting, static analysis and documentation checks passed (135 tasks, 2m 21s). Its Account XML reports 1,152 unit cases with no failures/errors and four skips, plus 178 integration cases with no failures/errors and 175 skips; the skipped PostgreSQL/Redis cases are not physical execution proof. At reconciled head `996959aa2477890ec901154e2c2376538da9012a`, consolidated Account formatting/fullCheck, static analysis, integration-source compilation and documentation checks passed in 1m 59s (93 tasks). Its XML reports 1,187 unit cases with four skips and 191 integration cases with 188 skips, with zero failures/errors; the skipped PostgreSQL/Redis cases remain unproved physically. Those historical local runs did not establish physical PostgreSQL/Redis proof. The later published source at `f9922f2b6c59b836c730bcb47100719c3498dbe0` passed fresh exact-head Account CI with 1,194 unit cases (four skips) and 207 PostgreSQL/Redis integration cases with zero failures, errors or skips (Validation `38247785958`, Account job `114806613509`, artifact `11747377390`); that exact-head proof includes the required V157.1 guard and physical TRUNCATE rejection coverage. This is bounded fixture proof; it does not establish caller authorization, deployed ACL/TLS or authority custody, gameplay admission, runtime activation, or end-to-end consumers. The later retained tenant/member replay proof is recorded in the later replay-proof paragraph below. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) and [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#implementation-status). +At the historical initial source baseline, Account contained an unregistered private gameplay LOGIN source slice: request-bound credential digests, the canonical LOGIN owner, Account signing and JWKS trust sources, pending and committed issuance owners, bounded issuance repositories and DTOs with V147–V157.1 migrations, pinned Coordination Redis registry/projection scripts, and encrypted response-envelope recovery. It uses the explicit initial `game-session-account-delegation` profile only; caller-selected profile/property bypasses, new endpoints, Spring runtime registration, remote credential provisioning, and consumer activation were outside that historical cut. Current selectable default-off Account dispatch/composition is recorded above; genuine custody, caller/deployment qualification, gameplay admission and activation remain unproved. The existing mounted signer bundle retains its stronger Control-UI/readiness and callback-redaction behavior, while authority reads are added around the receiving canonical sourceVersion/issuanceFence projection encoder. At original source head `8df6c870801f96a902742da0223f42cd1cfe527f`, consolidated local Account/Common checks, jOOQ generation, migration-version checks, integration-source compilation, formatting, static analysis and documentation checks passed (135 tasks, 2m 21s). Its Account XML reports 1,152 unit cases with no failures/errors and four skips, plus 178 integration cases with no failures/errors and 175 skips; the skipped PostgreSQL/Redis cases are not physical execution proof. At reconciled head `996959aa2477890ec901154e2c2376538da9012a`, consolidated Account formatting/fullCheck, static analysis, integration-source compilation and documentation checks passed in 1m 59s (93 tasks). Its XML reports 1,187 unit cases with four skips and 191 integration cases with 188 skips, with zero failures/errors; the skipped PostgreSQL/Redis cases remain unproved physically. Those historical local runs did not establish physical PostgreSQL/Redis proof. The later published source at `f9922f2b6c59b836c730bcb47100719c3498dbe0` passed fresh exact-head Account CI with 1,194 unit cases (four skips) and 207 PostgreSQL/Redis integration cases with zero failures, errors or skips (Validation `38247785958`, Account job `114806613509`, artifact `11747377390`); that exact-head proof includes the required V157.1 guard and physical TRUNCATE rejection coverage. This is bounded fixture proof; it does not establish caller authorization, deployed ACL/TLS or authority custody, gameplay admission, runtime activation, or end-to-end consumers. The later retained tenant/member replay proof is recorded in the later replay-proof paragraph below. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) and [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#implementation-status). At exact source head `50c22969698303ffdc6f3aab42d19dc499e47c5d`, the consolidated local full gate passed in 10m57s: 1,202 Account unit cases with four skips and 208 physical PostgreSQL/Redis integration cases with zero failures, errors, or skips, including the new 129 captured-head-loss/gap proof. This gate provides retained-source replay and fixture evidence for that exact head. It predates the subsequent projection republish/compare and bounded-page transport corrections. Their later local gate executed 1,207 unit cases with four skips and zero failures/errors, plus 208 physical PostgreSQL/Redis cases with zero skips; 206 passed, including all five delegation Redis cases for real commit-time publication and the 128+1 retained-page replay. The two `AccountAuthorityCurrentnessIntegrationTest` cases failed acquiring `localhost:53626` before Flyway migration (`SQLState 08001`, connection refused). Captured PostgreSQL logs show final TCP readiness before test startup and normal cleanup after the failures; the host-endpoint refusal cause remains unknown. The full local Account gate therefore failed despite the focused correction proof, and current published-head CI remains separate. At published source `1620a15e4a93461da5107aa940aaf41860f37cfd`, CI executed all 1,207 unit cases (four skips) and 208 physical integration cases with zero failures or errors; the Validation gate failed on a redundant-null-check static-analysis finding instead. The subsequent issuer-TTL and integer-transport corrections passed 1,210 unit cases (four skips), then a focused physical rerun passed all 21 cases across issuance persistence, response recovery and real delegation Redis, alongside Account/Common Security static, formatting and documentation checks (1m40s). That rerun was filtered; it does not claim a newer unfiltered 208-case pass. The earlier full local run of this correction batch passed 200 of 208 physical cases; the eight failures were the two Redis fixture mocks that lacked the exact issuer no-TTL stub, corrected before the focused rerun. Neither this source replay nor its fixture proof establishes deployed ACL/TLS, signer-key custody, caller authentication, gameplay admission, runtime activation, or authenticated full-owner physical composition. diff --git a/protos/account/v1/account_public_jwks_read.proto b/protos/account/v1/account_public_jwks_read.proto new file mode 100644 index 0000000000..3f43003854 --- /dev/null +++ b/protos/account/v1/account_public_jwks_read.proto @@ -0,0 +1,44 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Private, read-only same-namespace Game Session workload boundary. No key selector, signing, +// registry, rotation/readiness-plan, or admission authority is accepted or returned. +service AccountPublicJwksReadService { + rpc GetCurrentPublicJwks(GetCurrentAccountPublicJwksRequest) + returns (GetCurrentAccountPublicJwksResponse); +} + +message GetCurrentAccountPublicJwksRequest { + int32 schema_version = 1; +} + +// Exact identity derived by Account's protected receipt-backed current publication source. +message AccountPublicJwksSourceIdentity { + string environment_id = 1; + string cluster_id = 2; + string cluster_incarnation_uid = 3; + string namespace = 4; + string namespace_uid = 5; + string config_map_uid = 6; + string binding_revision = 7; + string api_server_origin = 8; + string serving_ca_sha256 = 9; +} + +message GetCurrentAccountPublicJwksResponse { + enum Disposition { + UNSPECIFIED = 0; + SNAPSHOT = 1; + PREPARED_DENY = 2; + } + int32 schema_version = 1; + AccountPublicJwksSourceIdentity source_identity = 2; + bytes public_jwks = 3; + Disposition disposition = 4; + // Presence is mandatory on SNAPSHOT and forbidden on PREPARED_DENY. + optional bool committed_recovery_eligible = 5; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfiguration.java new file mode 100644 index 0000000000..7e9c22fc36 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfiguration.java @@ -0,0 +1,111 @@ +package net.firedevops.firemud.accountservice.config; + +import io.lettuce.core.RedisCredentials; +import io.lettuce.core.RedisCredentialsProvider; +import io.lettuce.core.RedisURI; +import java.net.URI; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Arrays; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.LettuceAccountCoordinationPinnedConnectionProvider; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +/** Selects delivered protected sources; never enrolls a signer or provisions Redis or keys. */ +@Import(AccountPublicJwksSourceConfiguration.class) +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.account.gameplay-login", + name = "enabled", + havingValue = "true") +public class AccountGameplayLoginProtectedSourcesConfiguration { + static final String COORDINATION_CONNECTIONS = "accountGameplayLoginCoordinationConnections"; + static final String ACKNOWLEDGEMENT_REQUIREMENTS = "accountGameplayLoginAcknowledgements"; + + @Bean(name = COORDINATION_CONNECTIONS, destroyMethod = "close") + LettuceAccountCoordinationPinnedConnectionProvider accountGameplayLoginCoordinationConnections( + @Value("${firemud.account.gameplay-login.coordination.uri:}") String configuredUri, + @Value("${firemud.account.gameplay-login.coordination.command-timeout-millis:0}") + int commandTimeoutMillis) { + try { + return new LettuceAccountCoordinationPinnedConnectionProvider( + requiredCoordinationUri(configuredUri, commandTimeoutMillis)); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + @Bean(name = ACKNOWLEDGEMENT_REQUIREMENTS) + AcknowledgementRequirements accountGameplayLoginAcknowledgements( + @Value("${firemud.account.gameplay-login.coordination.required-local-aof-count:0}") + int localAof, + @Value("${firemud.account.gameplay-login.coordination.required-replica-aof-count:0}") + int replicaAof, + @Value("${firemud.account.gameplay-login.coordination.acknowledgement-timeout-millis:0}") + int timeoutMillis) { + return new AcknowledgementRequirements(localAof, replicaAof, timeoutMillis); + } + + static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) { + char[] password = null; + try { + if (configuredUri == null + || configuredUri.length() > 4096 + || timeoutMillis < 1 + || timeoutMillis > 60_000) { + throw unavailable(); + } + URI uri = URI.create(configuredUri); + String userInfo = uri.getUserInfo(); + String principal = AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY; + if (!"rediss".equals(uri.getScheme()) + || uri.getHost() == null + || uri.getHost().isBlank() + || uri.getPort() < 1 + || uri.getPort() > 65_535 + || !"/0".equals(uri.getRawPath()) + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || userInfo == null + || !userInfo.startsWith(principal + ":") + || userInfo.length() == principal.length() + 1 + || userInfo.chars().anyMatch(Character::isISOControl)) { + throw unavailable(); + } + password = userInfo.substring(principal.length() + 1).toCharArray(); + var credentials = RedisCredentials.just(principal, password); + return RedisURI.Builder.redis(uri.getHost(), uri.getPort()) + .withSsl(true) + .withVerifyPeer(true) + .withAuthentication(RedisCredentialsProvider.from(() -> credentials)) + .withDatabase(0) + .withTimeout(Duration.ofMillis(timeoutMillis)) + .build(); + } catch (RuntimeException failure) { + // In particular, do not retain URI/parser causes containing the delivered password. + throw unavailable(); + } finally { + if (password != null) Arrays.fill(password, '\0'); + } + } + + static Path requiredMount(String value) { + if (value == null || value.isBlank()) throw unavailable(); + try { + Path path = Path.of(value); + if (!path.isAbsolute() || !path.equals(path.normalize())) throw unavailable(); + return path; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static IllegalArgumentException unavailable() { + return new IllegalArgumentException("Protected Account gameplay LOGIN configuration required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfiguration.java new file mode 100644 index 0000000000..c1ae881f81 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfiguration.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.accountservice.config; + +import java.time.Clock; +import java.util.List; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.transaction.PlatformTransactionManager; + +/** Complete initial-LOGIN owner graph over the existing protected source implementations. */ +@Import(AccountPublicJwksSourceConfiguration.class) +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.account.gameplay-login", + name = "enabled", + havingValue = "true") +public class AccountGameplayLoginSourceConfiguration { + @Bean + AccountAuthEvidenceBundleRepository accountGameplayLoginEvidenceBundles( + DSLContext dsl, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox) { + return new AccountAuthEvidenceBundleRepository(dsl, generations, outbox); + } + + @Bean + AccountGameplayDelegationIssuanceRepository accountGameplayLoginIssuanceRepository( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sources, + AccountAuthEvidenceBundleRepository bundles) { + return new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); + } + + @Bean + AccountGameplayDelegationResponseEnvelopeRepository accountGameplayLoginResponseEnvelopes( + DSLContext dsl, + AccountAuthoritySourceEvidenceRepository sources, + AccountAuthEvidenceBundleRepository bundles, + AccountGameplayDelegationIssuanceRepository issuance, + @Qualifier("accountResponseEnvelopeCryptography") AccountResponseEnvelopeCryptography crypto, + @Value("${firemud.account.response-envelope.keyring-path:}") String responseKeyring) { + AccountGameplayLoginProtectedSourcesConfiguration.requiredMount(responseKeyring); + return new AccountGameplayDelegationResponseEnvelopeRepository( + dsl, sources, bundles, issuance, crypto); + } + + @Bean + AccountGameplayDelegationResponseEnvelopeService accountGameplayLoginResponseEnvelopeService( + AccountGameplayDelegationResponseEnvelopeRepository envelopes) { + return new AccountGameplayDelegationResponseEnvelopeService(envelopes); + } + + @Bean + AccountGameplayDelegationSigner accountGameplayLoginSigner( + AccountGameplayDelegationIssuanceRepository issuance, + AccountJwtSignerDesiredStateRepository signers, + AccountJwtSignerMaterializerTrustBinding trust, + AccountJwtJwksApiBinding api, + AccountJwtJwksTrustedSource jwks, + AccountGameplayDelegationResponseEnvelopeService envelopes, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountGameplayDelegationSigner( + issuance, signers, trust, api, jwks, envelopes, transactions, Clock.systemUTC()); + } + + @Bean + AccountGameplayDelegationRedisClient accountGameplayLoginRedis( + @Qualifier(AccountGameplayLoginProtectedSourcesConfiguration.COORDINATION_CONNECTIONS) + AccountCoordinationPinnedConnectionProvider connections, + @Qualifier(AccountGameplayLoginProtectedSourcesConfiguration.ACKNOWLEDGEMENT_REQUIREMENTS) + AcknowledgementRequirements acknowledgements) { + return new AccountGameplayDelegationRedisClient( + connections, + RedisScriptCatalog.fromContributions( + List.of( + new AccountGameplayDelegationRedisScriptContribution(), + new AccountGenerationProjectionRedisScriptContribution())), + acknowledgements, + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + AccountGameplayDelegationRedisClient.class.getClassLoader()); + } + + @Bean + AccountGameplayDelegationAuthorityProjection accountGameplayLoginAuthorityProjection( + AccountAuthoritySourceEvidenceRepository sources, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + AccountGameplayDelegationRedisClient redis) { + return new AccountGameplayDelegationAuthorityProjection(sources, transactions, redis); + } + + @Bean + AccountGameplayDelegationTokenRegistry accountGameplayLoginTokenRegistry( + AccountGameplayDelegationIssuanceRepository issuance, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + AccountGameplayDelegationRedisClient redis, + @Value("${firemud.account.gameplay-login.registry-cleanup-margin-millis}") + long cleanupMargin) { + return new AccountGameplayDelegationTokenRegistry( + issuance, + transactions, + redis, + Clock.systemUTC(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + cleanupMargin); + } + + @Bean + AccountGameplayDelegationIssuanceCommitService accountGameplayLoginCommits( + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry registry, + AccountGameplayDelegationAuthorityProjection projections, + AccountGameplayDelegationIssuanceRepository issuance, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountGameplayDelegationIssuanceCommitService( + signer, registry, projections, issuance, transactions, Clock.systemUTC()); + } + + @Bean + AccountGameplayDelegationCommittedIssuanceOwner accountGameplayLoginCommittedIssuance( + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry registry, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountGameplayDelegationCommittedIssuanceOwner( + issuance, signer, registry, transactions, Clock.systemUTC()); + } + + @Bean + AccountGameplayDelegationResponseRecoveryOwner accountGameplayLoginResponseRecovery( + AccountGameplayDelegationResponseEnvelopeRepository envelopes, + AccountGameplayDelegationCommittedIssuanceOwner committed, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountGameplayDelegationResponseRecoveryOwner(envelopes, committed, transactions); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java new file mode 100644 index 0000000000..938fc490d9 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountProtectedJwksSourceConfiguration.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.accountservice.config; + +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Explicit-import owner of Account's single protected public-JWKS source graph. This lite bean + * owner is not component-scanned and selects no gameplay, public-read or other consumer. Each + * independently selected consumer imports this same owner; repeated imports share the graph. + */ +public class AccountProtectedJwksSourceConfiguration { + private static final String JWKS_API_BINDING_PATH = "/etc/firemud/account-jwt-api/binding.json"; + + @Bean + AccountJwtJwksApiBinding accountPublicJwksApiBinding( + AccountJwtSignerMaterializerTrustBinding materializerTrust, + @Value("${firemud.account.public-jwks.api-binding-path:}") String bindingPath, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + if (!JWKS_API_BINDING_PATH.equals(bindingPath) + || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw unavailable(); + } + try { + var api = new AccountJwtJwksApiBinding(true, bindingPath); + var materializer = materializerTrust.current().orElseThrow(); + var current = api.current(); + if (!namespace.equals(materializer.namespace()) + || !namespace.equals(current.namespace()) + || !materializer.environmentId().equals(current.environmentId()) + || !materializer.clusterId().equals(current.clusterId()) + || !materializer + .expectedClusterIncarnationUid() + .equals(current.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(current.expectedNamespaceUid())) { + throw unavailable(); + } + // current() pins the protected API identity. Existing owners reread and compare both trust + // sources on use; a later materializer namespace cannot replace this accepted API identity. + return api; + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + @Bean + AccountJwtJwksConfigMapClient accountPublicJwksClient(AccountJwtJwksApiBinding api) { + return new AccountJwtJwksConfigMapClient(api); + } + + @Bean + AccountJwtJwksTrustedSource accountPublicTrustedJwks( + AccountJwtJwksConfigMapClient client, + AccountJwtSignerMaterializerTrustBinding trust, + AccountJwtSignerDesiredStateRepository signers, + AccountJwtJwksPublicationRepository publications, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountJwtJwksTrustedSource(client, trust, signers, publications, transactions); + } + + private static IllegalArgumentException unavailable() { + return new IllegalArgumentException("Protected Account public JWKS configuration required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPublicJwksReadWorkloadGuard.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPublicJwksReadWorkloadGuard.java new file mode 100644 index 0000000000..ef0031f909 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPublicJwksReadWorkloadGuard.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.accountservice.config; + +import java.util.Objects; +import java.util.Optional; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.SessionContext; + +/** Exact method-local workload authorization, independent of finite rotation-readiness plans. */ +public final class AccountPublicJwksReadWorkloadGuard { + private final Supplier> materializer; + private final Supplier api; + private final String namespace; + + public AccountPublicJwksReadWorkloadGuard( + AccountJwtSignerMaterializerTrustBinding materializer, + AccountJwtJwksApiBinding api, + String namespace) { + this( + Objects.requireNonNull(materializer)::current, + Objects.requireNonNull(api)::current, + namespace); + } + + AccountPublicJwksReadWorkloadGuard( + Supplier> materializer, + Supplier api, + String namespace) { + this.materializer = Objects.requireNonNull(materializer); + this.api = Objects.requireNonNull(api); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Protected Account workload namespace required"); + } + this.namespace = namespace; + } + + /** Called before and after the owner source read; no header or bearer establishes identity. */ + public ProtectedCaller requireCaller() { + try { + Binding trust = materializer.get().orElseThrow(ReadDeniedException::new); + var currentApi = Objects.requireNonNull(api.get()); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !("spiffe://firemud/ns/" + namespace + "/sa/game-session-service").equals(peer.uri()) + || !namespace.equals(trust.namespace()) + || !namespace.equals(currentApi.namespace()) + || !trust.environmentId().equals(currentApi.environmentId()) + || !trust.clusterId().equals(currentApi.clusterId()) + || !trust + .expectedClusterIncarnationUid() + .equals(currentApi.expectedClusterIncarnationUid()) + || !trust.expectedNamespaceUid().equals(currentApi.expectedNamespaceUid()) + || SessionContext.getAccountId() != null + || !SessionContext.getGlobalRoles().isEmpty() + || !SessionContext.getScopedRolesMap().isEmpty() + || SessionContext.isInternalService() + || SessionContext.getServiceName() != null + || SessionContext.getServiceInstanceId() != null) { + throw new ReadDeniedException(); + } + return new ProtectedCaller(trust, currentApi); + } catch (RuntimeException denied) { + throw new ReadDeniedException(); + } + } + + /** Invocation-local protected correspondence, never transported to a consumer. */ + public record ProtectedCaller(Binding materializer, AccountJwtJwksApiBinding.ParsedBinding api) { + public void requireSource(SourceIdentity source) { + if (source == null + || !materializer.environmentId().equals(source.environmentId()) + || !materializer.clusterId().equals(source.clusterId()) + || !materializer.namespace().equals(source.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(source.clusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(source.namespaceUid()) + || !api.configRevision().equals(source.bindingRevision()) + || !api.apiServer().toString().equals(source.apiServerOrigin()) + || !api.servingCaSha256().equals(source.servingCaSha256())) { + throw new InvalidJwksException(); + } + } + } + + public static final class ReadDeniedException extends SecurityException { + public ReadDeniedException() { + super("Authenticated same-namespace Game Session public JWKS reader required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPublicJwksSourceConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPublicJwksSourceConfiguration.java new file mode 100644 index 0000000000..28ccf3da3d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountPublicJwksSourceConfiguration.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.accountservice.config; + +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountPublicJwksReadService; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + +/** Selects the existing LOGIN/public-read consumers of the explicitly imported protected source. */ +@Configuration(proxyBeanMethods = false) +@Import(AccountProtectedJwksSourceConfiguration.class) +@ConditionalOnExpression( + "${firemud.account.gameplay-login.enabled:false} or ${firemud.account.public-jwks-read.enabled:false}") +public class AccountPublicJwksSourceConfiguration { + @Configuration(proxyBeanMethods = false) + @ConditionalOnProperty( + prefix = "firemud.account.public-jwks-read", + name = "enabled", + havingValue = "true") + static class CurrentPublicRead { + @Bean + AccountPublicJwksReadWorkloadGuard accountPublicJwksReadWorkloadGuard( + AccountJwtSignerMaterializerTrustBinding trust, + AccountJwtJwksApiBinding api, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountPublicJwksReadWorkloadGuard(trust, api, namespace); + } + + @Bean + AccountPublicJwksReadService accountPublicJwksReadService( + AccountJwtJwksTrustedSource source, AccountPublicJwksReadWorkloadGuard guard) { + return new AccountPublicJwksReadService(source, guard); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java new file mode 100644 index 0000000000..36447ee6cd --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.accountservice.config; + +import java.time.Clock; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAuthenticateReceiver; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayPrimaryCredentialVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountInitialGameplayLoginDisposalOwner; +import net.firedevops.firemud.accountservice.service.session.AccountMountedGameplayCredentialDigestKeySource; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** Receiving composition over the actual protected issuance, recovery and registry owners. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.account.gameplay-login", + name = "enabled", + havingValue = "true") +public class CanonicalGameplayRuntimeConfiguration { + @Bean + AccountGameplayAuthenticateReceiver canonicalGameplayAuthenticateReceiver( + AccountRepository accounts, + AccountGameplayDelegationIssuanceRepository issuance, + AccountGameplayDelegationIssuanceCommitService commits, + AccountGameplayDelegationResponseRecoveryOwner recovery, + AccountGameplayDelegationTokenRegistry registry, + AccountServiceImpl primary, + DSLContext dsl, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + @Value("${firemud.account.gameplay-login.request-digest-keyring-path:}") String digestKeyring, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + var clock = Clock.systemUTC(); + var digestKeys = + new AccountMountedGameplayCredentialDigestKeySource( + AccountGameplayLoginProtectedSourcesConfiguration.requiredMount(digestKeyring), clock); + var owner = + new AccountGameplayCanonicalLoginOwner( + accounts, issuance, digestKeys, commits, recovery, transactions, clock); + var disposal = + new AccountInitialGameplayLoginDisposalOwner( + new AccountInitialGameplayLoginDisposalRepository(dsl), registry, transactions); + return new AccountGameplayAuthenticateReceiver( + owner, new AccountGameplayPrimaryCredentialVerifier(primary), namespace, disposal); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java index f5f3e9043b..f79bc88cde 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -170,8 +170,19 @@ public DesiredState initialize(Binding binding, EnrollmentIdentity enrollmentIde @Transactional(propagation = Propagation.MANDATORY, readOnly = true) public Optional readEnrollmentState(Binding expectedBinding) { requireAccountTransaction(); + return readEnrollmentState(expectedBinding, false); + } + + /** Pins the enrollment row before a writable recovery read; it never changes owner state. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readLockedEnrollmentState(Binding expectedBinding) { + requireWritableAccountTransaction(); + return readEnrollmentState(expectedBinding, true); + } + + private Optional readEnrollmentState(Binding expectedBinding, boolean lock) { Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); - Record row = selectState(expectedBinding.environmentId(), false); + Record row = selectState(expectedBinding.environmentId(), lock); if (row == null) { return Optional.empty(); } @@ -490,6 +501,21 @@ public PreparedGenerationEvidence readPreparedGenerationForRecovery( return new PreparedGenerationEvidence(state, promotion.publicEvidence(), result); } + /** + * Validates the complete private receipt for the exact locked PREPARED owner. This read does not + * advance promotion or substitute for its separate completed public receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PrivatePromotionReceipt readPreparedPrivatePromotionReceiptForRecovery( + Binding expectedBinding, TrustFence trust) { + PreparedGenerationEvidence prepared = readPreparedGenerationForRecovery(expectedBinding, trust); + StoredPromotion promotion = selectPromotion(prepared.promotion().operationId(), true); + if (promotion == null) { + throw new QuarantinedStateException("Account PREPARED private promotion is missing"); + } + return PrivatePromotionReceipt.fromStored(promotion); + } + /** * Atomically records that the authenticated materializer may receive the immutable private-slot * promotion operation. This marker is deliberately sticky: after it is committed, a lost RPC @@ -4079,6 +4105,33 @@ public record ActiveJwksPromotionObservation( } } + /** + * Computes only the fixed ACTIVE receipt grammar; callers retain owner and observation + * validation. The supplied UID and versions are the writer's exact observation, not substituted + * owner fields. + */ + public static String activeJwksPromotionReceiptDigest( + PromotionOperationEvidence promotion, + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String dataDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("receiptVersion", "account-jwt-active-jwks-promotion-receipt/v1"); + preimage.put("promotionOperationId", promotion.operationId().toString()); + preimage.put("promotionRequestDigest", promotion.requestDigest()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("configMapName", PUBLIC_JWKS_CONFIG_MAP_NAME); + preimage.put("configMapUid", configMapUid); + preimage.put("priorResourceVersion", priorResourceVersion); + preimage.put("observedResourceVersion", observedResourceVersion); + preimage.put("action", "MARK_ACTIVE"); + preimage.put("publicDataDigest", dataDigest); + return digest(preimage); + } + public record ActiveJwksPromotionReceipt( UUID promotionOperationId, String configMapUid, @@ -4139,26 +4192,18 @@ private static ActiveJwksPromotionReceipt create( String priorResourceVersion, String observedResourceVersion, String dataDigest) { - Map preimage = new LinkedHashMap<>(); - preimage.put("receiptVersion", "account-jwt-active-jwks-promotion-receipt/v1"); - preimage.put("promotionOperationId", promotion.operationId().toString()); - preimage.put("promotionRequestDigest", promotion.requestDigest()); - preimage.put("generationOperationId", promotion.generationOperationId().toString()); - preimage.put("generationOperationDigest", promotion.generationOperationDigest()); - preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); - preimage.put("configMapName", PUBLIC_JWKS_CONFIG_MAP_NAME); - preimage.put("configMapUid", configMapUid); - preimage.put("priorResourceVersion", priorResourceVersion); - preimage.put("observedResourceVersion", observedResourceVersion); - preimage.put("action", "MARK_ACTIVE"); - preimage.put("publicDataDigest", dataDigest); return new ActiveJwksPromotionReceipt( promotion.operationId(), configMapUid, priorResourceVersion, observedResourceVersion, dataDigest, - digest(preimage)); + activeJwksPromotionReceiptDigest( + promotion.publicEvidence(), + configMapUid, + priorResourceVersion, + observedResourceVersion, + dataDigest)); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPublicJwksReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPublicJwksReadGrpcService.java new file mode 100644 index 0000000000..e9293c60b3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountPublicJwksReadGrpcService.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import net.firedevops.firemud.account.v1.AccountPublicJwksReadServiceGrpc; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksRequest; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksResponse; +import net.firedevops.firemud.accountservice.config.AccountPublicJwksReadWorkloadGuard; +import net.firedevops.firemud.accountservice.service.session.AccountPublicJwksReadService; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.grpc.server.service.GrpcService; + +/** Registered on the ordinary listener only under the separate, default-off public-read opt-in. */ +@GrpcService +@ConditionalOnProperty( + prefix = "firemud.account.public-jwks-read", + name = "enabled", + havingValue = "true") +public final class AccountPublicJwksReadGrpcService + extends AccountPublicJwksReadServiceGrpc.AccountPublicJwksReadServiceImplBase { + private final AccountPublicJwksReadService owner; + + public AccountPublicJwksReadGrpcService(AccountPublicJwksReadService owner) { + this.owner = java.util.Objects.requireNonNull(owner); + } + + @Override + public void getCurrentPublicJwks( + GetCurrentAccountPublicJwksRequest request, + StreamObserver observer) { + try { + observer.onNext(owner.read(request)); + observer.onCompleted(); + } catch (AccountPublicJwksReadWorkloadGuard.ReadDeniedException denied) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Authorized Game Session workload required") + .asRuntimeException()); + } catch (AccountPublicJwksReadCodec.InvalidFrameException invalid) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Current public JWKS request invalid") + .asRuntimeException()); + } catch (AccountPublicJwksCache.SourceUnavailableException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Current Account public JWKS unavailable") + .asRuntimeException()); + } catch (AccountPublicJwksCache.InvalidJwksException rejected) { + // Typed custody/provenance and producer-frame failures remain hard denials. + observer.onError( + Status.FAILED_PRECONDITION + .withDescription("Current Account public JWKS rejected") + .asRuntimeException()); + } catch (RuntimeException unavailable) { + // An unclassified handler fault supplies no evidence of custody rejection. + observer.onError( + Status.UNAVAILABLE + .withDescription("Current Account public JWKS unavailable") + .asRuntimeException()); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java index 5b724600b8..48de813354 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java @@ -312,6 +312,12 @@ private void verifyEnvironment(ApiSession operation) { ParsedBinding binding = operation.binding(); ApiResponse selfReview = send(operation, ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, SELF_SUBJECT_REVIEW_REQUEST); + if (selfReview.statusCode() == 408 + || selfReview.statusCode() == 429 + || (selfReview.statusCode() >= 500 && selfReview.statusCode() < 600)) { + // An unavailable principal review proves no identity and must not become custody rejection. + throw new ApiFailureException(selfReview.statusCode()); + } if ((selfReview.statusCode() != 200 && selfReview.statusCode() != 201) || !binding.expectedApiUsername().equals(parseAuthenticatedUsername(selfReview.body()))) { throw new BindingRejectedException(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java index 5f1c502a44..df2a7f5a17 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java @@ -24,6 +24,7 @@ import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; @@ -33,6 +34,7 @@ import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec.ReadResult; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -60,6 +62,7 @@ public final class AccountJwtJwksTrustedSource private static final String ACCOUNT_SERVICE_USERNAME_PREFIX = "system:serviceaccount:"; private static final String ACCOUNT_SERVICE_NAME = "account-service"; private static final int MAX_KEYS = 64; + private static final int MAX_PUBLIC_READ_TRIALS = 3; private static final java.util.Set JWKS_FIELDS = java.util.Set.of("keys"); private static final java.util.Set REQUIRED_JWK_FIELDS = java.util.Set.of("kty", "use", "alg", "kid", "n", "e"); @@ -154,64 +157,199 @@ public PublicJwksSnapshot load() { return new PublicJwksSnapshot(expected.sourceIdentity(), verified.jwksBytes()); } - private VerifiedSource readVerifiedSource() { - Binding materializerBefore = currentMaterializerBinding(); - BindingIdentity apiBefore = currentApiIdentity(); - requireBindingsAgree(materializerBefore, apiBefore); - TrustedPin alreadyPinned = trustedPin; - if (alreadyPinned != null - && (!alreadyPinned.materializerBinding().equals(materializerBefore) - || !alreadyPinned.apiIdentity().equals(apiBefore))) { - throw rejected(); + /** Reads the public-only disposition; PREPARED denial grants no cached-key authority. */ + public ReadResult currentPublicRead() { + io.grpc.Context incoming = io.grpc.Context.current(); + TrustedPin expected = trustedPin; + if (expected == null) { + synchronized (pinMonitor) { + expected = trustedPin; + if (expected == null) { + VerifiedSource verified = readVerifiedSource(true, incoming); + requirePublicReadActive(true, incoming, verified.ownerMovementObserved()); + trustedPin = verified.pin(); + return publicReadResult(verified.pin(), verified, incoming); + } + } } + return publicReadResult(expected, readVerifiedSource(true, incoming), incoming); + } - OwnerProjection ownerBefore = currentOwnerProjection(materializerBefore, apiBefore); - SourceIdentity pinnedIdentity = - sourceIdentity(materializerBefore, apiBefore, ownerBefore.projection().configMapUid()); - if (alreadyPinned != null && !alreadyPinned.sourceIdentity().equals(pinnedIdentity)) { - throw rejected(); - } + private static ReadResult publicReadResult( + TrustedPin expected, VerifiedSource verified, io.grpc.Context incoming) { + requirePublicReadActive(true, incoming, verified.ownerMovementObserved()); + if (!expected.equals(verified.pin())) throw rejected(); + return new ReadResult( + verified.pin().sourceIdentity(), + verified.jwksBytes(), + verified.preparedDeny(), + verified.committedRecoveryEligible()); + } - ConfigMapSnapshot live; - try { - live = configMapClient.observe(); - } catch (AccountJwtJwksConfigMapClient.ResourceMissingException unavailable) { - requireUnchangedProtectedTrust(materializerBefore, apiBefore); - throw unavailable(); - } catch (AccountJwtJwksConfigMapClient.ApiFailureException failure) { - requireUnchangedProtectedTrust(materializerBefore, apiBefore); - if (isTemporaryApiFailure(failure.statusCode())) { + private VerifiedSource readVerifiedSource() { + return readVerifiedSource(false); + } + + private VerifiedSource readVerifiedSource(boolean allowPreparedDeny) { + return readVerifiedSource(allowPreparedDeny, io.grpc.Context.current()); + } + + private VerifiedSource readVerifiedSource(boolean allowPreparedDeny, io.grpc.Context incoming) { + TrustedPin anchor = trustedPin; + boolean ownerMovementObserved = false; + int totalTrials = allowPreparedDeny ? MAX_PUBLIC_READ_TRIALS : 1; + for (int trial = 0; trial < totalTrials; trial++) { + try { + requirePublicReadActive(allowPreparedDeny, incoming, ownerMovementObserved); + Binding materializerBefore = currentMaterializerBinding(); + BindingIdentity apiBefore = currentApiIdentity(); + requireBindingsAgree(materializerBefore, apiBefore); + if (anchor != null + && (!anchor.materializerBinding().equals(materializerBefore) + || !anchor.apiIdentity().equals(apiBefore))) { + throw rejected(); + } + requirePublicReadActive(allowPreparedDeny, incoming, ownerMovementObserved); + OwnerProjection ownerBefore = + currentOwnerProjection(materializerBefore, apiBefore, allowPreparedDeny); + SourceIdentity identity = + sourceIdentity(materializerBefore, apiBefore, ownerBefore.projection().configMapUid()); + if (anchor == null) anchor = new TrustedPin(materializerBefore, apiBefore, identity); + if (!anchor.sourceIdentity().equals(identity)) throw rejected(); + requirePublicReadActive(allowPreparedDeny, incoming, ownerMovementObserved); + + ConfigMapSnapshot live; + try { + live = configMapClient.observe(); + } catch (AccountJwtJwksConfigMapClient.ResourceMissingException unavailable) { + requireUnchangedProtectedTrust(materializerBefore, apiBefore); + throw unavailable(); + } catch (AccountJwtJwksConfigMapClient.ApiFailureException failure) { + requireUnchangedProtectedTrust(materializerBefore, apiBefore); + if (isTemporaryApiFailure(failure.statusCode())) throw unavailable(); + throw rejected(); + } catch (AccountJwtJwksConfigMapClient.BindingRejectedException trustRejected) { + throw rejected(); + } catch (RuntimeException unexpected) { + throw rejected(); + } + requirePublicReadActive(allowPreparedDeny, incoming, ownerMovementObserved); + Binding materializerAfter = currentMaterializerBinding(); + BindingIdentity apiAfter = currentApiIdentity(); + if (!materializerBefore.equals(materializerAfter) || !apiBefore.equals(apiAfter)) { + throw rejected(); + } + if (allowPreparedDeny && !anchor.sourceIdentity().configMapUid().equals(live.uid())) { + throw rejected(); + } + requirePublicReadActive(allowPreparedDeny, incoming, ownerMovementObserved); + OwnerProjection ownerAfter = + currentOwnerProjection(materializerAfter, apiAfter, allowPreparedDeny); + boolean ownerMoved = !ownerBefore.equals(ownerAfter); + if (allowPreparedDeny && ownerMoved) ownerMovementObserved = true; + requirePublicReadActive(allowPreparedDeny, incoming, ownerMovementObserved); + if (allowPreparedDeny + && !anchor + .sourceIdentity() + .equals( + sourceIdentity( + materializerAfter, apiAfter, ownerAfter.projection().configMapUid()))) { + throw rejected(); + } + if (ownerMoved) { + if (!allowPreparedDeny) throw unavailable(); + // Movement alone cannot qualify the intervening API bytes. Requalify the complete read + // only when at least one coherent bracket proves those exact bytes at the original pin. + if ((!qualifiesMovingProjection(ownerBefore, live) + && !qualifiesMovingProjection(ownerAfter, live)) + || trial + 1 == totalTrials) { + throw rejected(); + } + continue; + } + PublishedProjection projection = qualifiedProjection(ownerAfter, live); + if (projection == null) { + // This complete stable trial qualified prepublication without serving unreceipted keys. + throw new QualifiedTemporaryRead(); + } + byte[] jwks = + live.data() + .get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY) + .getBytes(StandardCharsets.UTF_8); + if (jwks.length == 0 || jwks.length > MAX_JWKS_BYTES) throw rejected(); + boolean preparedDeny = ownerAfter.preparedPromotion() != null; + boolean committedRecoveryEligible = + !preparedDeny + && ownerAfter.committedSigner() != null + && projection.equals(committedProjection(ownerAfter.committedSigner())); + return new VerifiedSource( + anchor, + preparedDeny ? new byte[0] : jwks, + preparedDeny, + committedRecoveryEligible, + ownerMovementObserved); + } catch (QualifiedTemporaryRead qualifiedTemporary) { + // Only complete local qualification resolves movement; dependency failure never does. + requirePublicReadActive(allowPreparedDeny, incoming, ownerMovementObserved); throw unavailable(); + } catch (SourceUnavailableException unavailableAfterObservation) { + if (ownerMovementObserved) throw rejected(); + throw unavailableAfterObservation; } - throw rejected(); - } catch (AccountJwtJwksConfigMapClient.BindingRejectedException trustRejected) { - throw rejected(); - } catch (RuntimeException unexpected) { - throw rejected(); } + throw rejected(); + } - Binding materializerAfter = currentMaterializerBinding(); - BindingIdentity apiAfter = currentApiIdentity(); - if (!materializerBefore.equals(materializerAfter) || !apiBefore.equals(apiAfter)) { - throw rejected(); + private static void requirePublicReadActive( + boolean publicRead, io.grpc.Context incoming, boolean ownerMovementObserved) { + if (publicRead + && (Thread.currentThread().isInterrupted() + || incoming.isCancelled() + || (incoming.getDeadline() != null && incoming.getDeadline().isExpired()))) { + if (ownerMovementObserved) throw rejected(); + throw unavailable(); } + } - OwnerProjection ownerAfter = currentOwnerProjection(materializerAfter, apiAfter); - if (!ownerBefore.equals(ownerAfter)) { - // A concurrent Account lifecycle/publication change is not a coherent source snapshot. - throw unavailable(); + private boolean qualifiesMovingProjection(OwnerProjection owner, ConfigMapSnapshot live) { + try { + qualifiedProjection(owner, live); + return true; + } catch (QualifiedTemporaryRead qualifiedVersionOnly) { + // Exact UID and complete owned bytes qualify another trial, never a moving-bracket response. + return true; + } catch (SourceRejectedException | SourceUnavailableException unqualified) { + return false; } - requireExactReadback(ownerAfter.projection(), live); + } - byte[] jwks = - live.data() - .get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY) - .getBytes(StandardCharsets.UTF_8); - if (jwks.length == 0 || jwks.length > MAX_JWKS_BYTES) { - throw rejected(); + private PublishedProjection qualifiedProjection(OwnerProjection owner, ConfigMapSnapshot live) { + PublishedProjection projection = owner.projection(); + if (owner.pendingPrepublication() != null) { + try { + requireUnreceiptedPrepublicationReadback(owner, live); + } catch (RuntimeException malformedOrUnproven) { + throw rejected(); + } + return null; + } + if (owner.preparedPromotion() != null + && owner + .preparedPromotion() + .expectedActiveMarkerJson() + .equals( + live.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY))) { + PromotionOperationEvidence promotion = owner.preparedPromotion(); + if (promotion.activeJwksObservedResourceVersion().isEmpty() + && promotion.activeJwksPublicDataDigest().isEmpty() + && promotion.activeJwksReceiptDigest().isEmpty()) { + projection = unreceiptedPreparedActiveProjection(owner, live); + } else { + projection = preparedActiveProjection(promotion); + } } - TrustedPin pin = new TrustedPin(materializerBefore, apiBefore, pinnedIdentity); - return new VerifiedSource(pin, jwks); + requireExactReadback(projection, live); + return projection; } private Binding currentMaterializerBinding() { @@ -226,7 +364,8 @@ private BindingIdentity currentApiIdentity() { } } - private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity api) { + private OwnerProjection currentOwnerProjection( + Binding binding, BindingIdentity api, boolean allowPreparedDeny) { if (TransactionSynchronizationManager.isActualTransactionActive()) { throw rejected(); } @@ -234,12 +373,17 @@ private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity OwnerProjection result = accountTransaction.execute( status -> { + Optional enrollment = + allowPreparedDeny + ? desiredStateRepository.readLockedEnrollmentState(binding.accountBinding()) + : desiredStateRepository.readEnrollmentState(binding.accountBinding()); DesiredState enrolled = - desiredStateRepository - .readEnrollmentState(binding.accountBinding()) - .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + enrollment.orElseThrow(() -> allowPreparedDeny ? rejected() : unavailable()); + if (allowPreparedDeny && enrolled.preparedOperationId().isPresent()) { + return preparedProjection(enrolled, binding, api); + } if (enrolled.durableActive().isEmpty() && enrolled.publishedActive().isEmpty()) { - return initialPrepublicationProjection(enrolled, binding, api); + return initialPrepublicationProjection(enrolled, binding, api, allowPreparedDeny); } CommittedSignerEvidence committed = desiredStateRepository @@ -248,7 +392,7 @@ private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity trustFence(binding), api.bindingDigest(), api.configRevision()) - .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + .orElseThrow(() -> allowPreparedDeny ? rejected() : unavailable()); ActiveSigner currentActive = new ActiveSigner( committed.promotion().targetGeneration(), @@ -274,8 +418,8 @@ private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity PublicationEvidence evidence = currentPublication.orElseThrow(); requirePublicationBinding(evidence, binding, api); PrepublicationIntent intent = evidence.intent(); - var receipt = - evidence.receipt().orElseThrow(AccountJwtJwksTrustedSource::unavailable); + PublicationReceipt receipt = evidence.receipt().orElse(null); + if (receipt == null && !allowPreparedDeny) throw unavailable(); if (!intent.operationId().equals(request.operationId()) || !intent.operationDigest().equals(request.operationDigest()) || !intent.generationRequestDigest().equals(request.generationRequestDigest()) @@ -286,12 +430,22 @@ private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity || !intent.expectedDurableActive().equals(Optional.of(currentActive)) || !intent.expectedPublishedActive().equals(Optional.of(currentActive)) || !intent.configMapUid().equals(committed.promotion().publicConfigMapUid()) - || !receipt.configMapUid().equals(committed.promotion().publicConfigMapUid()) + || (receipt != null + && !receipt + .configMapUid() + .equals(committed.promotion().publicConfigMapUid())) || !intent.apiBindingDigest().equals(api.bindingDigest()) || !intent.apiConfigRevision().equals(api.configRevision())) { throw rejected(); } requireRetainedPublicKeySet(committed, intent); + if (receipt == null) { + requirePrepublicationMarker(intent, binding, api); + if (!intent.expectedResourceVersion().equals(projection.resourceVersion())) { + throw rejected(); + } + return new OwnerProjection(committed, projection, null, null, intent); + } return new OwnerProjection( committed, new PublishedProjection( @@ -320,13 +474,176 @@ private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity } } + private OwnerProjection preparedProjection( + DesiredState enrolled, Binding binding, BindingIdentity api) { + var prepared = + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding)); + var publication = + publicationRepository.readPreparedPublicationForRecovery( + binding.accountBinding(), trustFence(binding)); + PromotionOperationEvidence promotion = prepared.promotion(); + GenerationResult generation = prepared.generationResult(); + PrepublicationIntent intent = publication.intent(); + PublicationReceipt receipt = publication.receipt(); + var mount = publication.mountedCorrespondence(); + requirePublicationBinding( + new PublicationEvidence(intent, Optional.of(receipt), Optional.of(mount)), binding, api); + EnrollmentIdentity enrollment = enrolled.enrollmentIdentity().orElseThrow(); + if (!enrolled.equals(prepared.desiredState()) + || !enrolled.binding().equals(binding.accountBinding()) + || !enrolled.preparedOperationId().equals(Optional.of(promotion.operationId())) + || enrolled.generationOperationId().isPresent() + || promotion.expectedRecordVersion() == Long.MAX_VALUE + || enrolled.recordVersion() != promotion.expectedRecordVersion() + 1 + || !enrolled.durableActive().equals(promotion.expectedPreviousActive()) + || !enrolled.publishedActive().equals(promotion.expectedPublishedActive()) + || !enrollment + .expectedClusterIncarnationUid() + .equals(binding.expectedClusterIncarnationUid()) + || !enrollment.expectedNamespaceUid().equals(binding.expectedNamespaceUid()) + || !enrollment.materializerTrustBindingDigest().equals(binding.bindingDigest()) + || !enrollment.materializerTrustConfigRevision().equals(binding.configRevision()) + || !enrollment.apiBindingDigest().equals(api.bindingDigest()) + || !enrollment.apiConfigRevision().equals(api.configRevision()) + || !enrollment.publicConfigMapUid().equals(intent.configMapUid()) + || !"PREPARED".equals(promotion.status()) + || !promotion.binding().equals(binding.accountBinding()) + || !promotion.trustFence().equals(trustFence(binding)) + || !promotion.apiBindingDigest().equals(api.bindingDigest()) + || !promotion.apiConfigRevision().equals(api.configRevision()) + || !promotion.generationOperationId().equals(generation.operationId()) + || !generation.operationId().equals(intent.operationId()) + || !generation.binding().equals(binding.accountBinding()) + || !generation.trustFence().equals(trustFence(binding)) + || !promotion.generationOperationDigest().equals(generation.operationDigest()) + || !generation.operationDigest().equals(intent.operationDigest()) + || !generation.generationRequestDigest().equals(intent.generationRequestDigest()) + || !promotion.generationReceiptDigest().equals(generation.receiptDigest()) + || !generation.receiptDigest().equals(intent.generationReceiptDigest()) + || !promotion.targetGeneration().equals(generation.targetGeneration()) + || !promotion.targetGeneration().equals(intent.targetGeneration()) + || !promotion.targetKid().equals(generation.targetKid()) + || !promotion.targetKid().equals(intent.targetKid()) + || !"RS256".equals(promotion.targetAlgorithm()) + || !"RS256".equals(generation.targetAlgorithm()) + || !promotion.targetPublicKeyFingerprint().equals(generation.publicKeyFingerprint()) + || !promotion.targetPublicKeyFingerprint().equals(intent.publicKeyFingerprint()) + || !promotion.publicConfigMapUid().equals(intent.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(receipt.observedResourceVersion()) + || !promotion.expectedPublicJwksJson().equals(intent.jwksJson()) + || !promotion.expectedPreviousActive().equals(intent.expectedDurableActive()) + || !promotion.expectedPublishedActive().equals(intent.expectedPublishedActive()) + || !promotion.prepublicationIntentDigest().equals(intent.intentDigest()) + || !promotion.prepublicationReceiptDigest().equals(receipt.receiptDigest()) + || !promotion.mountedObservationDigest().equals(mount.observationDigest()) + || !mount.operationId().equals(intent.operationId()) + || !mount.intentDigest().equals(intent.intentDigest()) + || !mount.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !mount.generationMarkerDigest().equals(intent.generationMarkerDigest()) + || !mount.publicDataDigest().equals(intent.publicDataDigest()) + || !mount.publicKeyFingerprint().equals(intent.publicKeyFingerprint()) + || !promotion + .targetPublicKeyFingerprint() + .equals(publicKeyFingerprints(intent.jwksJson()).get(promotion.targetKid()))) { + throw rejected(); + } + PrivatePromotionReceipt privateReceipt = null; + if (promotion.privatePromotionObservedResourceVersion().isPresent() + || promotion.privatePromotionReceiptDigest().isPresent()) { + privateReceipt = + desiredStateRepository.readPreparedPrivatePromotionReceiptForRecovery( + binding.accountBinding(), trustFence(binding)); + if (privateReceipt == null + || !privateReceipt.promotionOperationId().equals(promotion.operationId()) + || !privateReceipt.generationOperationId().equals(promotion.generationOperationId()) + || !promotion + .privatePromotionObservedResourceVersion() + .equals(Optional.of(privateReceipt.observedResourceVersion())) + || !promotion + .privatePromotionReceiptDigest() + .equals(Optional.of(privateReceipt.receiptDigest()))) { + throw rejected(); + } + } + return new OwnerProjection( + null, + new PublishedProjection( + intent.configMapUid(), + receipt.observedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + receipt.publicDataDigest()), + promotion, + privateReceipt, + null); + } + + /** Exact writer intent/private proof can deny keys while its ACTIVE receipt is not committed. */ + private static PublishedProjection unreceiptedPreparedActiveProjection( + OwnerProjection owner, ConfigMapSnapshot live) { + PromotionOperationEvidence promotion = owner.preparedPromotion(); + if (owner.preparedPrivateReceipt() == null + || !promotion.privatePromotionDispatched() + || !validResourceVersion(live.resourceVersion()) + || live.resourceVersion().equals(promotion.expectedPublicResourceVersion())) { + throw rejected(); + } + return new PublishedProjection( + promotion.publicConfigMapUid(), + live.resourceVersion(), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson(), + AccountJwtJwksPublicationRepository.publicDataDigest( + promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson())); + } + + private static boolean validResourceVersion(String value) { + return value != null && value.matches("[!-~]{1,256}"); + } + + /** Reconstructs the exact owner-bound ACTIVE receipt without mutating lifecycle state. */ + private static PublishedProjection preparedActiveProjection( + PromotionOperationEvidence promotion) { + String resourceVersion = + promotion + .activeJwksObservedResourceVersion() + .orElseThrow(AccountJwtJwksTrustedSource::rejected); + String dataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson()); + String digest; + try { + digest = + AccountJwtSignerDesiredStateRepository.activeJwksPromotionReceiptDigest( + promotion, + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + resourceVersion, + dataDigest); + } catch (IllegalStateException malformed) { + throw rejected(); + } + if (resourceVersion.equals(promotion.expectedPublicResourceVersion()) + || !promotion.activeJwksPublicDataDigest().equals(Optional.of(dataDigest)) + || !promotion.activeJwksReceiptDigest().equals(Optional.of(digest))) { + throw rejected(); + } + return new PublishedProjection( + promotion.publicConfigMapUid(), + resourceVersion, + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson(), + dataDigest); + } + /** * The first exact Account-receipted PREPUBLISHED set is visible to validator probes before any * signer is committed. It is never represented as an active signer and remains unavailable during * PREPARED or after any active fence appears. */ private OwnerProjection initialPrepublicationProjection( - DesiredState enrolled, Binding binding, BindingIdentity api) { + DesiredState enrolled, Binding binding, BindingIdentity api, boolean publicRead) { if (!enrolled.binding().equals(binding.accountBinding()) || enrolled.preparedOperationId().isPresent() || enrolled.generationOperationId().isEmpty() @@ -373,10 +690,11 @@ private OwnerProjection initialPrepublicationProjection( PublicationEvidence evidence = publicationRepository .readCurrentPublication(binding.accountBinding(), trustFence(binding)) - .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + .orElseThrow(() -> publicRead ? rejected() : unavailable()); requirePublicationBinding(evidence, binding, api); PrepublicationIntent intent = evidence.intent(); - var receipt = evidence.receipt().orElseThrow(AccountJwtJwksTrustedSource::unavailable); + PublicationReceipt receipt = evidence.receipt().orElse(null); + if (receipt == null && !publicRead) throw unavailable(); if (!intent.operationId().equals(result.operationId()) || !intent.operationDigest().equals(result.operationDigest()) || !intent.generationRequestDigest().equals(result.generationRequestDigest()) @@ -385,7 +703,7 @@ private OwnerProjection initialPrepublicationProjection( || !intent.expectedDurableActive().isEmpty() || !intent.expectedPublishedActive().isEmpty() || !intent.configMapUid().equals(enrollment.publicConfigMapUid()) - || !receipt.configMapUid().equals(enrollment.publicConfigMapUid()) + || (receipt != null && !receipt.configMapUid().equals(enrollment.publicConfigMapUid())) || !intent.apiBindingDigest().equals(enrollment.apiBindingDigest()) || !intent.apiConfigRevision().equals(enrollment.apiConfigRevision()) || !intent.targetGeneration().equals(result.targetGeneration()) @@ -398,7 +716,24 @@ private OwnerProjection initialPrepublicationProjection( || !result.publicKeyFingerprint().equals(publicKeys.get(result.targetKid()))) { throw rejected(); } - requireInitialPrepublicationMarker(intent, result, binding, api); + requirePrepublicationMarker(intent, binding, api); + if (receipt == null) { + if (!intent.expectedResourceVersion().equals(enrollment.publicConfigMapResourceVersion()) + || !intent.expectedSnapshotDigest().equals(enrollment.publicConfigMapSnapshotDigest())) { + throw rejected(); + } + return new OwnerProjection( + null, + new PublishedProjection( + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest()), + null, + null, + intent); + } return new OwnerProjection( null, new PublishedProjection( @@ -409,8 +744,70 @@ private OwnerProjection initialPrepublicationProjection( receipt.publicDataDigest())); } - private static void requireInitialPrepublicationMarker( - PrepublicationIntent intent, GenerationResult result, Binding binding, BindingIdentity api) { + /** Qualifies only an exact prior projection or this operation's exact additive intended set. */ + private static void requireUnreceiptedPrepublicationReadback( + OwnerProjection owner, ConfigMapSnapshot live) { + PrepublicationIntent intent = owner.pendingPrepublication(); + if (!intent.configMapUid().equals(live.uid()) + || !validResourceVersion(live.resourceVersion())) { + throw rejected(); + } + String jwks = live.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY); + String marker = live.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY); + boolean prior = + intent.expectedResourceVersion().equals(live.resourceVersion()) + && intent + .expectedSnapshotDigest() + .equals(AccountJwtJwksPublicationRepository.snapshotDigest(live.data())); + boolean intended = + !intent.expectedResourceVersion().equals(live.resourceVersion()) + && intent.jwksJson().equals(jwks) + && intent.generationMarkerJson().equals(marker) + && intent + .publicDataDigest() + .equals(AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker)); + if (!prior && !intended) throw rejected(); + if (owner.committedSigner() != null) { + PublishedProjection previous = committedProjection(owner.committedSigner()); + Map previousKeys = publicKeyFingerprints(previous.jwksJson()); + Map intendedKeys = publicKeyFingerprints(intent.jwksJson()); + if (previousKeys.containsKey(intent.targetKid()) + || intendedKeys.size() != previousKeys.size() + 1) throw rejected(); + Map previousData = new LinkedHashMap<>(live.data()); + previousData.put(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, previous.jwksJson()); + previousData.put( + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, previous.markerJson()); + if (!intent + .expectedSnapshotDigest() + .equals(AccountJwtJwksPublicationRepository.snapshotDigest(previousData))) + throw rejected(); + if (prior) requireExactReadback(previous, live); + return; + } + // Initial serving supports the first generated key only. Reconstruct the known empty + // predecessor from unchanged unowned data and prove it against enrollment's exact digest. + if (prior) { + if (marker != null || jwks == null || jwks.isBlank()) throw rejected(); + try { + JsonNode empty = STRICT_JSON.readTree(jwks); + if (!hasExactFields(empty, JWKS_FIELDS) + || !empty.get("keys").isArray() + || !empty.get("keys").isEmpty()) throw rejected(); + } catch (RuntimeException malformed) { + throw rejected(); + } + return; + } + Map previousData = new LinkedHashMap<>(live.data()); + previousData.remove(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY); + previousData.put(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, "{\"keys\":[]}"); + if (!intent + .expectedSnapshotDigest() + .equals(AccountJwtJwksPublicationRepository.snapshotDigest(previousData))) throw rejected(); + } + + private static void requirePrepublicationMarker( + PrepublicationIntent intent, Binding binding, BindingIdentity api) { try { JsonNode marker = STRICT_JSON.readTree(intent.generationMarkerJson()); JsonNode markerBinding = marker == null ? null : marker.get("binding"); @@ -475,12 +872,12 @@ private static void requireInitialPrepublicationMarker( requiredText(publicConfigMap, "name")) || !hasExactFields( pending, java.util.Set.of("generation", "kid", "algorithm", "publicKeyFingerprint")) - || !result.targetGeneration().equals(requiredText(pending, "generation")) - || !result.targetKid().equals(requiredText(pending, "kid")) + || !intent.targetGeneration().equals(requiredText(pending, "generation")) + || !intent.targetKid().equals(requiredText(pending, "kid")) || !"RS256".equals(requiredText(pending, "algorithm")) - || !result.publicKeyFingerprint().equals(requiredText(pending, "publicKeyFingerprint")) - || !inactiveMarker(durable) - || !inactiveMarker(published)) { + || !intent.publicKeyFingerprint().equals(requiredText(pending, "publicKeyFingerprint")) + || !activeMarkerMatches(durable, intent.expectedDurableActive()) + || !activeMarkerMatches(published, intent.expectedPublishedActive())) { throw rejected(); } } catch (RuntimeException malformed) { @@ -488,6 +885,15 @@ private static void requireInitialPrepublicationMarker( } } + private static boolean activeMarkerMatches(JsonNode marker, Optional expected) { + if (expected.isEmpty()) return inactiveMarker(marker); + return hasExactFields(marker, java.util.Set.of("present", "generation", "kid")) + && marker.get("present").isBoolean() + && marker.get("present").booleanValue() + && expected.orElseThrow().generation().equals(requiredText(marker, "generation")) + && expected.orElseThrow().kid().equals(requiredText(marker, "kid")); + } + private static boolean inactiveMarker(JsonNode marker) { return hasExactFields(marker, java.util.Set.of("present")) && marker.get("present").isBoolean() @@ -709,7 +1115,6 @@ private static void requireExactReadback(PublishedProjection projection, ConfigM String jwks = live.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY); String marker = live.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY); if (!projection.configMapUid().equals(live.uid()) - || !projection.resourceVersion().equals(live.resourceVersion()) || !projection.jwksJson().equals(jwks) || !projection.markerJson().equals(marker) || marker == null @@ -718,6 +1123,11 @@ private static void requireExactReadback(PublishedProjection projection, ConfigM .equals(projection.publicDataDigest())) { throw rejected(); } + if (!projection.resourceVersion().equals(live.resourceVersion())) { + // Exact owned bytes and UID do not authorize serving a different, unreceipted version. + // The stable caller distinguishes this exact local result from dependency unavailability. + throw new QualifiedTemporaryRead(); + } } private static SourceIdentity sourceIdentity( @@ -762,10 +1172,20 @@ private static SourceUnavailableException unavailable() { return new SourceUnavailableException(); } + /** Keeps the private custody category distinct at the Account public-read boundary. */ + static boolean isSourceRejected(RuntimeException failure) { + return failure instanceof SourceRejectedException; + } + private static SourceRejectedException rejected() { return new SourceRejectedException(); } + /** Internal control flow for the two fully qualified, no-snapshot temporary windows only. */ + private static final class QualifiedTemporaryRead extends RuntimeException { + private static final long serialVersionUID = 1L; + } + private static final class SourceRejectedException extends IllegalStateException { private SourceRejectedException() { super("Account trusted public JWKS source was rejected"); @@ -776,7 +1196,16 @@ private record TrustedPin( Binding materializerBinding, BindingIdentity apiIdentity, SourceIdentity sourceIdentity) {} private record OwnerProjection( - CommittedSignerEvidence committedSigner, PublishedProjection projection) {} + CommittedSignerEvidence committedSigner, + PublishedProjection projection, + PromotionOperationEvidence preparedPromotion, + PrivatePromotionReceipt preparedPrivateReceipt, + PrepublicationIntent pendingPrepublication) { + private OwnerProjection( + CommittedSignerEvidence committedSigner, PublishedProjection projection) { + this(committedSigner, projection, null, null, null); + } + } private record PublishedProjection( String configMapUid, @@ -785,5 +1214,10 @@ private record PublishedProjection( String markerJson, String publicDataDigest) {} - private record VerifiedSource(TrustedPin pin, byte[] jwksBytes) {} + private record VerifiedSource( + TrustedPin pin, + byte[] jwksBytes, + boolean preparedDeny, + boolean committedRecoveryEligible, + boolean ownerMovementObserved) {} } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadService.java new file mode 100644 index 0000000000..70f7688c98 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadService.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksRequest; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksResponse; +import net.firedevops.firemud.accountservice.config.AccountPublicJwksReadWorkloadGuard; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Public-only read through Account's actual current receipt-backed publication authority. */ +public final class AccountPublicJwksReadService { + private final AccountJwtJwksTrustedSource source; + private final AccountPublicJwksReadWorkloadGuard guard; + + public AccountPublicJwksReadService( + AccountJwtJwksTrustedSource source, AccountPublicJwksReadWorkloadGuard guard) { + this.source = Objects.requireNonNull(source); + this.guard = Objects.requireNonNull(guard); + } + + public GetCurrentAccountPublicJwksResponse read(GetCurrentAccountPublicJwksRequest request) { + var caller = guard.requireCaller(); + AccountPublicJwksReadCodec.requireRequest(request); + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new AccountPublicJwksCache.SourceUnavailableException(); + } + try { + return currentResponse(caller); + } catch (RuntimeException failure) { + if (AccountJwtJwksTrustedSource.isSourceRejected(failure) + || failure instanceof AccountPublicJwksReadCodec.InvalidFrameException) { + throw new AccountPublicJwksCache.InvalidJwksException(); + } + throw failure; + } + } + + private GetCurrentAccountPublicJwksResponse currentResponse( + AccountPublicJwksReadWorkloadGuard.ProtectedCaller caller) { + var snapshot = source.currentPublicRead(); + if (snapshot == null) { + throw new AccountPublicJwksCache.InvalidJwksException(); + } + var identity = snapshot.sourceIdentity(); + caller.requireSource(identity); + if (!identity.equals(source.sourceIdentity())) { + throw new AccountPublicJwksCache.InvalidJwksException(); + } + if (!caller.equals(guard.requireCaller())) { + throw new AccountPublicJwksCache.InvalidJwksException(); + } + try { + return AccountPublicJwksReadCodec.response(snapshot); + } catch (AccountPublicJwksReadCodec.InvalidFrameException producerRejected) { + // The caller's request already passed validation; this is our publication's failure. + throw new AccountPublicJwksCache.InvalidJwksException(); + } + } +} diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 07b28a5463..398e261710 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -68,6 +68,7 @@ firemud: path-pattern: /.well-known/** grpc: public-methods: + - account.v1.AccountPublicJwksReadService/GetCurrentPublicJwks - account.v1.AccountService/Authenticate - account.v1.AccountService/RequestEmailLoginOtp - account.v1.AccountService/VerifyEmailLoginOtp diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 99eadbdc10..8cb3e8e012 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -103,6 +103,7 @@ firemud: path-pattern: /.well-known/** grpc: public-methods: + - account.v1.AccountPublicJwksReadService/GetCurrentPublicJwks - account.v1.AccountService/Authenticate - account.v1.AccountService/RequestEmailLoginOtp - account.v1.AccountService/VerifyEmailLoginOtp diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadRegistrationMtlsIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadRegistrationMtlsIntegrationTest.java new file mode 100644 index 0000000000..7e79c48e34 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadRegistrationMtlsIntegrationTest.java @@ -0,0 +1,683 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.stub.MetadataUtils; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.math.BigInteger; +import java.net.ServerSocket; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.interfaces.RSAPublicKey; +import java.time.Instant; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AccountPublicJwksReadServiceGrpc; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksRequest; +import net.firedevops.firemud.account.v1.GetProfileRequest; +import net.firedevops.firemud.account.v1.GetProfileResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.config.AccountPublicJwksReadWorkloadGuard; +import net.firedevops.firemud.accountservice.service.impl.AccountPublicJwksReadGrpcService; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki.IssuedIdentity; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki.TestCertificateAuthority; +import net.firedevops.firemud.common.config.CommonGrpcRequestBoundsAutoConfiguration; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.grpc.BoundedGrpcServerFactory; +import net.firedevops.firemud.common.grpc.CommonGrpcServerConfiguration; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec.ReadResult; +import net.firedevops.firemud.common.security.AuthTokenInterceptor; +import net.firedevops.firemud.common.security.GrpcAuthProperties; +import net.firedevops.firemud.common.security.JwtUtil; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerAutoConfiguration; +import org.springframework.boot.grpc.server.autoconfigure.GrpcServerFactoryAutoConfiguration; +import org.springframework.boot.ssl.DefaultSslBundleRegistry; +import org.springframework.boot.ssl.SslBundle; +import org.springframework.boot.ssl.SslBundles; +import org.springframework.boot.ssl.SslStoreBundle; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.core.io.FileSystemResource; +import org.springframework.grpc.server.GrpcServerFactory; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.grpc.server.service.GrpcService; + +/** + * Ordinary-listener registration proof: real Spring gRPC discovery, production global bearer and + * TLS identity interceptors, genuine receiver/owner/guard, and physical loopback mutual TLS. + * Protected provisioning is a controlled binding input, and only the trusted-publication source is + * mocked. This does not prove the live Account database/Kubernetes publication source, production + * PKI, signer custody, validator convergence, or gameplay LOGIN/admission. + */ +class AccountPublicJwksReadRegistrationMtlsIntegrationTest { + private static final String NAMESPACE = "test"; + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String METHOD = + "account.v1.AccountPublicJwksReadService/GetCurrentPublicJwks"; + private static final String PROFILE_METHOD = "account.v1.AccountService/GetProfile"; + private static final String GAME_SESSION_URI = + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-session-service"; + private static final String PASSWORD = "test-only-current-public-jwks-password"; + @TempDir static Path directory; + private static TestCertificateAuthority authority; + private static Identity server; + private static Identity gameSession; + private static List rejectedPeers; + private static byte[] publicJwks; + + @BeforeAll + static void createControlledCertificates() throws Exception { + authority = + AccountStartSessionReservationProofPki.createCertificateAuthority( + directory, "ca.p12", "ca.crt", "ca", "CN=Account public JWKS listener CA", PASSWORD); + server = issue("account", "spiffe://firemud/ns/test/sa/account-service", true); + gameSession = issue("game-session", GAME_SESSION_URI, false); + Identity wrongService = + issue("wrong-service", "spiffe://firemud/ns/test/sa/account-service", false); + Identity crossNamespace = + issue("other-namespace", "spiffe://firemud/ns/other/sa/game-session-service", false); + Identity multipleUris = + issue( + "multiple-uris", + GAME_SESSION_URI + ",URI:spiffe://firemud/ns/test/sa/account-service", + false); + Identity noUri = issue("no-uri", GAME_SESSION_URI, false); + // Re-sign the fixture CSR without SAN extensions. keytool does not honor requested extensions + // unless explicitly selected, so this trusted client certificate contains no workload URI. + AccountStartSessionReservationProofPki.runKeytool( + directory, + "-gencert", + "-alias", + authority.alias(), + "-keystore", + authority.keyStore().toString(), + "-storetype", + "PKCS12", + "-storepass", + PASSWORD, + "-infile", + directory.resolve("no-uri.csr").toString(), + "-outfile", + noUri.certificate().toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=clientAuth"); + try (var input = Files.newInputStream(noUri.certificate())) { + var certificate = + (java.security.cert.X509Certificate) + java.security.cert.CertificateFactory.getInstance("X.509").generateCertificate(input); + assertThat(certificate.getSubjectAlternativeNames()).isNull(); + } + rejectedPeers = List.of(wrongService, crossNamespace, noUri, multipleUris); + var rsa = (RSAPublicKey) server.issued().identity().certificate().getPublicKey(); + publicJwks = + ("{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"listener-proof\",\"use\":\"sig\"," + + "\"alg\":\"RS256\",\"n\":\"" + + unsigned(rsa.getModulus()) + + "\",\"e\":\"" + + unsigned(rsa.getPublicExponent()) + + "\"}]}") + .getBytes(StandardCharsets.UTF_8); + } + + @ParameterizedTest + @ValueSource(strings = {"application.yml", "application-prod.yml"}) + void actualRegistrationUsesExactTlsWorkloadRatherThanBearerOrRequestClaims(String resource) + throws Exception { + var protectedBinding = new ControlledProtectedBinding(); + var source = mock(AccountJwtJwksTrustedSource.class); + var snapshot = new ReadResult(sourceIdentity(), publicJwks, false, false); + when(source.sourceIdentity()).thenReturn(snapshot.sourceIdentity()); + when(source.currentPublicRead()) + .thenAnswer( + ignored -> { + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_SESSION_URI); + assertEmptyBearerContext(); + return snapshot; + }); + int port = unusedLoopbackPort(); + runner(resource, port, source, protectedBinding) + .withPropertyValues("firemud.account.public-jwks-read.enabled=true") + .run( + context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(AccountPublicJwksReadGrpcService.class); + assertThat(context).hasSingleBean(AccountPublicJwksReadService.class); + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context).hasSingleBean(GrpcPeerIdentityInterceptor.class); + assertThat(context.getBean(GrpcServerFactory.class)) + .isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThat(context.getBean(GrpcServerLifecycle.class).isRunning()).isTrue(); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(METHOD) + .doesNotContain(PROFILE_METHOD, "account.v1.AccountPublicJwksReadService/*"); + String accountId = "44444444-4444-4444-8444-444444444444"; + String token = + context + .getBean(JwtUtil.class) + .generateToken( + accountId, + Map.of("accountId", accountId, "globalRoles", List.of("platformAdmin"))); + try (var client = new Client(port, gameSession)) { + var response = + client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request()); + assertThat(response).isEqualTo(AccountPublicJwksReadCodec.response(snapshot)); + assertThat(AccountPublicJwksReadCodec.snapshot(response).jwksBytes()) + .isEqualTo(publicJwks); + assertThat(response.getSourceIdentity().getAllFields()).hasSize(9); + // A valid privileged bearer is ignored for this exact method. The actual guard + // still sees empty SessionContext in source.currentPublicRead(), not the bearer + // claims. + assertThat( + client + .withBearer(token) + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) + .isEqualTo(response); + var adjacent = context.getBean(AdjacentAccountProfileService.class); + assertCode( + Status.Code.UNAUTHENTICATED, + () -> + AccountServiceGrpc.newBlockingStub(client.channel) + .getProfile(GetProfileRequest.getDefaultInstance())); + assertThat(adjacent.calls).hasValue(0); + assertThat( + AccountServiceGrpc.newBlockingStub(client.channel) + .withInterceptors( + MetadataUtils.newAttachHeadersInterceptor(headers(token))) + .getProfile(GetProfileRequest.getDefaultInstance()) + .getProfileJson()) + .isEqualTo("registered non-exempt handler"); + assertThat(adjacent.calls).hasValue(1); + // The authenticated adjacent call cannot contaminate the following exempt read. + assertThat(client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) + .isEqualTo(response); + } + clearInvocations(source); + for (Identity peer : rejectedPeers) { + try (var client = new Client(port, peer)) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + client + .withBearer(token) + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + } + verifyNoInteractions(source); + } + try (var client = new Client(port, null)) { + assertCode( + Status.Code.UNAVAILABLE, + () -> + client + .withBearer(token) + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + } + verifyNoInteractions(source); + try (var client = new Client(port, gameSession)) { + for (var malformed : + List.of( + GetCurrentAccountPublicJwksRequest.getDefaultInstance(), + AccountPublicJwksReadCodec.request().toBuilder() + .setSchemaVersion(1) + .build(), + AccountPublicJwksReadCodec.request().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertCode( + Status.Code.INVALID_ARGUMENT, + () -> client.stub().getCurrentPublicJwks(malformed)); + verifyNoInteractions(source); + } + doThrow(new IllegalStateException("private internal handler fault")) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.UNAVAILABLE, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + doThrow(new AccountPublicJwksReadCodec.InvalidFrameException()) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + var deny = new ReadResult(sourceIdentity(), new byte[0], true, false); + doReturn(deny).when(source).currentPublicRead(); + assertThat( + AccountPublicJwksReadCodec.result( + client + .stub() + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) + .preparedDeny()) + .isTrue(); + var committed = new ReadResult(sourceIdentity(), publicJwks, false, true); + doReturn(committed).when(source).currentPublicRead(); + assertThat( + AccountPublicJwksReadCodec.result( + client + .stub() + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) + .committedRecoveryEligible()) + .isTrue(); + doReturn(snapshot).when(source).currentPublicRead(); + assertThat(client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) + .isEqualTo(AccountPublicJwksReadCodec.response(snapshot)); + doThrow(new AccountPublicJwksCache.InvalidJwksException()) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + doThrow(new AccountPublicJwksCache.SourceUnavailableException()) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.UNAVAILABLE, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + doReturn( + new ReadResult( + new SourceIdentity( + "test", + "cluster-a", + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + "55555555-5555-4555-8555-555555555555", + "api-r1", + "https://kubernetes.test:6443", + "b".repeat(64)), + publicJwks, + false, + false)) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + for (String mismatch : List.of("api-origin", "binding-revision")) { + var expected = sourceIdentity(); + var changed = + new SourceIdentity( + expected.environmentId(), + expected.clusterId(), + expected.clusterIncarnationUid(), + expected.namespace(), + expected.namespaceUid(), + expected.configMapUid(), + mismatch.equals("binding-revision") + ? "api-r2" + : expected.bindingRevision(), + mismatch.equals("api-origin") + ? "https://different-api.test:6443" + : expected.apiServerOrigin(), + expected.servingCaSha256()); + doReturn(new ReadResult(changed, publicJwks, false, false)) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + } + doAnswer( + ignored -> { + protectedBinding.trust.set(Optional.empty()); + return snapshot; + }) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + clearInvocations(source); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + verifyNoInteractions(source); + } + }); + } + + @ParameterizedTest + @ValueSource(strings = {"application.yml", "application-prod.yml"}) + void publicReadReceiverIsAbsentWithoutItsSeparateExplicitOptIn(String resource) throws Exception { + var source = mock(AccountJwtJwksTrustedSource.class); + int port = unusedLoopbackPort(); + runner(resource, port, source, new ControlledProtectedBinding()) + .run( + context -> { + assertThat(context) + .hasNotFailed() + .doesNotHaveBean(AccountPublicJwksReadGrpcService.class); + assertThat(context.getBean(GrpcServerLifecycle.class).isRunning()).isTrue(); + try (var client = new Client(port, gameSession)) { + assertCode( + Status.Code.UNIMPLEMENTED, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + } + verifyNoInteractions(source); + }); + } + + private static ApplicationContextRunner runner( + String resource, + int port, + AccountJwtJwksTrustedSource source, + ControlledProtectedBinding protectedBinding) + throws Exception { + SslBundles bundles = sslBundles(); + var yaml = + new YamlPropertySourceLoader() + .load( + "actual-account-" + resource, + new FileSystemResource(Path.of("src/main/resources").resolve(resource))); + return new ApplicationContextRunner() + .withInitializer( + context -> + yaml.forEach( + propertySource -> + context.getEnvironment().getPropertySources().addLast(propertySource))) + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class, + CommonGrpcRequestBoundsAutoConfiguration.class, + GrpcServerFactoryAutoConfiguration.class, + GrpcServerAutoConfiguration.class)) + .withUserConfiguration( + CommonGrpcServerConfiguration.class, + AccountPublicJwksReadGrpcService.class, + AccountPublicJwksReadService.class, + AdjacentAccountProfileService.class) + .withBean(AccountJwtJwksTrustedSource.class, () -> source) + .withBean(AccountPublicJwksReadWorkloadGuard.class, protectedBinding::guard) + .withBean(SslBundles.class, () -> bundles) + .withBean(io.micrometer.core.instrument.MeterRegistry.class, SimpleMeterRegistry::new) + .withBean( + RuntimeIdentity.class, + () -> + new RuntimeIdentity( + "account-service", + "public-jwks-listener-test", + "localhost", + Instant.EPOCH, + "test", + "test", + "test")) + .withPropertyValues( + "spring.grpc.server.address=127.0.0.1:" + port, + "spring.grpc.server.port=" + port, + "spring.grpc.server.shutdown-grace-period=0s", + "spring.grpc.server.ssl.enabled=true", + "firemud.auth.jwt-secret=test-only-public-jwks-listener-secret-32-bytes", + "firemud.account.gameplay-login.enabled=false"); + } + + /** + * Supplies no owner business behavior; this generated non-exempt descriptor tests global auth. + */ + @GrpcService + static class AdjacentAccountProfileService extends AccountServiceGrpc.AccountServiceImplBase { + final AtomicInteger calls = new AtomicInteger(); + + @Override + public void getProfile(GetProfileRequest request, StreamObserver observer) { + calls.incrementAndGet(); + observer.onNext( + GetProfileResponse.newBuilder().setProfileJson("registered non-exempt handler").build()); + observer.onCompleted(); + } + } + + /** Controlled independent protected inputs, not a production file-provisioning proof. */ + private static final class ControlledProtectedBinding { + final AtomicReference> trust = new AtomicReference<>(Optional.of(binding())); + final AtomicReference api = + new AtomicReference<>( + new AccountJwtJwksApiBinding.ParsedBinding( + "api-r1", + "test", + "cluster-a", + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + directory.resolve("stipulated-serving-ca.pem"), + "b".repeat(64), + directory.resolve("stipulated-api-token"), + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:test:account-service", + "c".repeat(64))); + + AccountPublicJwksReadWorkloadGuard guard() { + try { + // Use the production guard's existing controlled-input seam without mocking its decisions + // or changing public access to that seam merely for a differently packaged proof. + var constructor = + AccountPublicJwksReadWorkloadGuard.class.getDeclaredConstructor( + Supplier.class, Supplier.class, String.class); + constructor.setAccessible(true); + return constructor.newInstance( + (Supplier>) trust::get, + (Supplier) api::get, + NAMESPACE); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException( + "Could not construct controlled production workload guard", failure); + } + } + } + + private static Binding binding() { + String peer = "spiffe://firemud/ns/test/sa/jwt-signer-materializer"; + List pins = List.of("a".repeat(64)); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "materializer-r1", + "test", + "cluster-a", + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + peer, + pins); + return new Binding( + "test", + "cluster-a", + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + peer, + pins, + "materializer-r1", + digest); + } + + private static SourceIdentity sourceIdentity() { + return new SourceIdentity( + "test", + "cluster-a", + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + CONFIG_MAP_UID, + "api-r1", + "https://kubernetes.test:6443", + "b".repeat(64)); + } + + private static void assertEmptyBearerContext() { + assertThat(SessionContext.getAccountId()).isNull(); + assertThat(SessionContext.getGlobalRoles()).isEmpty(); + assertThat(SessionContext.getScopedRolesMap()).isEmpty(); + assertThat(SessionContext.isInternalService()).isFalse(); + assertThat(SessionContext.getServiceName()).isNull(); + assertThat(SessionContext.getServiceInstanceId()).isNull(); + } + + private static Metadata headers(String bearer) { + var headers = new Metadata(); + headers.put( + Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER), "Bearer " + bearer); + headers.put( + Metadata.Key.of("x-firemud-peer-uri", Metadata.ASCII_STRING_MARSHALLER), GAME_SESSION_URI); + return headers; + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static int unusedLoopbackPort() throws Exception { + try (var socket = new ServerSocket(0, 50, java.net.InetAddress.getByName("127.0.0.1"))) { + return socket.getLocalPort(); + } + } + + private static SslBundles sslBundles() throws Exception { + KeyStore keys = KeyStore.getInstance("PKCS12"); + keys.load(null, null); + keys.setKeyEntry( + "account", + server.issued().identity().privateKey(), + PASSWORD.toCharArray(), + new java.security.cert.Certificate[] { + server.issued().identity().certificate(), authority.certificate() + }); + KeyStore trust = KeyStore.getInstance("PKCS12"); + trust.load(null, null); + trust.setCertificateEntry("ca", authority.certificate()); + var bundles = new DefaultSslBundleRegistry(); + bundles.registerBundle("firemud-grpc", SslBundle.of(SslStoreBundle.of(keys, PASSWORD, trust))); + return bundles; + } + + private static Identity issue(String alias, String workloadUri, boolean isServer) + throws Exception { + var issued = + AccountStartSessionReservationProofPki.issueIdentity( + directory, + authority, + alias, + alias + ".p12", + alias + ".csr", + alias + ".crt", + workloadUri, + isServer, + true, + false); + Path key = directory.resolve(alias + ".key"); + byte[] encoded = issued.identity().privateKey().getEncoded(); + try { + Files.writeString( + key, + "-----BEGIN PRIVATE KEY-----\n" + + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(encoded) + + "\n-----END PRIVATE KEY-----\n", + StandardCharsets.US_ASCII); + } finally { + java.util.Arrays.fill(encoded, (byte) 0); + } + return new Identity(issued, issued.certificateFile(), key); + } + + private static String unsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + if (bytes[0] == 0) bytes = java.util.Arrays.copyOfRange(bytes, 1, bytes.length); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private record Identity(IssuedIdentity issued, Path certificate, Path key) {} + + private static final class Client implements AutoCloseable { + final ManagedChannel channel; + + Client(int port, Identity identity) throws Exception { + var tls = GrpcSslContexts.forClient().trustManager(authority.certificateFile().toFile()); + if (identity != null) + tls.keyManager(identity.certificate().toFile(), identity.key().toFile()); + channel = + NettyChannelBuilder.forAddress("127.0.0.1", port) + .sslContext(tls.build()) + .maxInboundMessageSize(AccountPublicJwksReadCodec.MAX_RESPONSE_BYTES) + .build(); + } + + AccountPublicJwksReadServiceGrpc.AccountPublicJwksReadServiceBlockingStub stub() { + return AccountPublicJwksReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(10, TimeUnit.SECONDS); + } + + AccountPublicJwksReadServiceGrpc.AccountPublicJwksReadServiceBlockingStub withBearer( + String bearer) { + return stub().withInterceptors(MetadataUtils.newAttachHeadersInterceptor(headers(bearer))); + } + + @Override + public void close() throws Exception { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java new file mode 100644 index 0000000000..dab77470c5 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java @@ -0,0 +1,1383 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import io.grpc.Context; +import java.math.BigInteger; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.IntConsumer; +import java.util.function.Supplier; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountPublicJwksReadWorkloadGuard; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PublicKeyIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.repository.AccountJwtValidatorInventoryRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourcePreparedDenyException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec.ReadResult; +import org.awaitility.Awaitility; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DataSourceUtils; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Physical PostgreSQL witnesses at both existing Account public ConfigMap writers. Normal Flyway + * guards and owner repositories produce all durable evidence. Only API transport, projected files + * and authenticated readiness-receiver inputs are controlled. A common-cache bridge consumes real + * public service responses; it is not Game Session transport, protected-mount or activation proof. + * Exact pending prepublication is unavailable without a deny latch; exact PREPARED ACTIVE writer + * windows deny without keys until the real owner commit. Genuine tamper remains terminal. + */ +class AccountPublicJwksWriterWindowPostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "jwks_writer_window"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(true); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String CLUSTER_UID = "11111111-1111-4111-8111-111111111111"; + private static final String NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String SECRET_UID = "33333333-3333-4333-8333-333333333333"; + private static final String CONFIG_MAP_UID = "44444444-4444-4444-8444-444444444444"; + private static final String API_DIGEST = "c".repeat(64); + private static final String API_REVISION = "api-r1"; + private final Set schemas = ConcurrentHashMap.newKeySet(); + @TempDir Path temporaryDirectory; + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @AfterEach + void dropRunOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.startsWith(SCHEMA_PREFIX + "_") || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean an unowned PostgreSQL schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + schemas.clear(); + } + + @Test + void initialPrepublicationCutsRemainUnavailableUntilExactFailedReceiptReconciliation() + throws Exception { + Harness harness = harness(); + harness.generate(); + AtomicReference publishedVersion = new AtomicReference<>(); + harness.transport.beforePatch = + () -> { + assertThat(harness.count("account_jwt_jwks_prepublication_intents")).isEqualTo(1); + assertThat(harness.count("account_jwt_jwks_publication_receipts")).isZero(); + assertThat(harness.transport.data.get("jwks.json")).isEqualTo("{\"keys\":[]}"); + harness.assertUnavailableRead(); + }; + harness.transport.afterPatch = + () -> { + publishedVersion.set(harness.transport.version); + harness.assertLiveMatchesCurrentPrepublicationIntent(); + assertThat(harness.count("account_jwt_jwks_publication_receipts")).isZero(); + harness.assertUnavailableRead(); + harness.manager.beforeCommit.set( + () -> + harness.observeBlockedPublicRead( + harness::assertUnavailableRead, + () -> + assertThat(harness.count("account_jwt_jwks_publication_receipts")) + .isZero())); + }; + try { + assertThatThrownBy(harness.prepublication::prepublishCurrentGeneration) + .isInstanceOf(TransactionSystemException.class); + } finally { + harness.awaitBlockedPublicRead(); + } + assertThat(harness.count("account_jwt_jwks_publication_receipts")).isZero(); + assertThat(harness.transport.patches).isEqualTo(1); + harness.assertUnavailableRead(); + harness.transport.clearHooks(); + var receipt = harness.prepublication.prepublishCurrentGeneration(); + assertThat(receipt.observedResourceVersion()).isEqualTo(publishedVersion.get()); + assertThat(harness.transport.patches).isEqualTo(1); + assertThat(harness.prepublication.prepublishCurrentGeneration()).isEqualTo(receipt); + harness.mountAndObserve(); + ReadResult stable = harness.read(); + assertThat(stable.preparedDeny()).isFalse(); + assertThat(stable.committedRecoveryEligible()).isFalse(); + assertThat(stable.jwksBytes()).isEqualTo(harness.publicBytes()); + assertThat(harness.count("account_jwt_jwks_prepublication_intents")).isEqualTo(1); + assertThat(harness.count("account_jwt_jwks_publication_receipts")).isEqualTo(1); + assertThat(harness.count("account_jwt_jwks_mount_observations")).isEqualTo(1); + } + + @Test + void committedSignerRefusesNextPublicationWithoutDurableRotationRequestAndPreservesCache() + throws Exception { + Harness harness = harness(); + harness.commitInitialSigner(); + AccountPublicJwksCache cache = harness.cache(); + String committedKid = harness.result.targetKid(); + var cachedKey = cache.keyFor(committedKid); + var committed = + harness + .tx( + () -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) + .orElseThrow(); + var state = + harness + .tx(() -> harness.desired.readEnrollmentState(harness.binding.accountBinding())) + .orElseThrow(); + assertThat(state.generationOperationId()).isEmpty(); + assertThat(state.preparedOperationId()).isEmpty(); + ConfigMapSnapshot publicResource = harness.configMap.observe(); + Map> durableHistory = harness.ownerHistoryImages(); + String mountedJwks = Files.readString(harness.publicMount.resolve("jwks.json")); + String mountedMarker = Files.readString(harness.publicMount.resolve("jwt-generation.json")); + int patchCount = harness.transport.patches; + + // A subsequent rotation-request entrypoint and its prepublication/pruning lifecycle are not + // implemented or physically qualified. Neither a retained signer nor a test may invent it. + assertThatThrownBy( + () -> + harness.tx( + () -> + harness.desired.ensureCurrentGenerationRequest( + harness.binding.accountBinding(), harness.trust))) + .isExactlyInstanceOf( + AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class) + .hasMessage("Account has no durable rotation request for its committed signer"); + assertThat(harness.ownerHistoryImages()).isEqualTo(durableHistory); + assertThat(harness.transport.patches).isEqualTo(patchCount); + assertThatThrownBy(harness.prepublication::prepublishCurrentGeneration) + .isExactlyInstanceOf( + AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class) + .hasMessage("Account has no owner-selected JWT generation operation"); + + assertThat(harness.ownerHistoryImages()).isEqualTo(durableHistory); + assertThat( + harness + .tx(() -> harness.desired.readEnrollmentState(harness.binding.accountBinding())) + .orElseThrow()) + .isEqualTo(state); + assertThat( + harness + .tx( + () -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), + harness.trust, + API_DIGEST, + API_REVISION)) + .orElseThrow()) + .isEqualTo(committed); + assertThat(harness.transport.patches).isEqualTo(patchCount); + assertThat(harness.configMap.observe()).isEqualTo(publicResource); + assertThat(Files.readString(harness.publicMount.resolve("jwks.json"))).isEqualTo(mountedJwks); + assertThat(Files.readString(harness.publicMount.resolve("jwt-generation.json"))) + .isEqualTo(mountedMarker); + ReadResult stable = harness.read(); + assertThat(stable.preparedDeny()).isFalse(); + assertThat(stable.committedRecoveryEligible()).isTrue(); + assertThat(stable.jwksBytes()).isEqualTo(harness.publicBytes()); + cache.refresh(); + assertThat(cache.keyFor(committedKid)).isEqualTo(cachedKey); + assertThat(harness.count("account_jwt_jwks_prepublication_intents")).isEqualTo(1); + assertThat(harness.count("account_jwt_jwks_publication_receipts")).isEqualTo(1); + assertThat(harness.count("account_jwt_jwks_mount_observations")).isEqualTo(1); + } + + @Test + void activeCasWithoutReceiptDeniesCachedKeysAcrossOutageAndRecoversAfterExactOwnerCommit() + throws Exception { + Harness harness = harness(); + harness.generate(); + harness.prepublication.prepublishCurrentGeneration(); + harness.mountAndObserve(); + AccountPublicJwksCache transitionCache = harness.cache(); + AccountPublicJwksCache preparedCache = harness.cache(); + String kid = harness.result.targetKid(); + assertThat(transitionCache.keyFor(kid)).isNotNull(); + assertThat(preparedCache.keyFor(kid)).isNotNull(); + harness.prepareAndRecordPrivatePromotion(); + harness.assertPreparedDeny(); + assertThatThrownBy(preparedCache::refresh).isInstanceOf(SourcePreparedDenyException.class); + assertThatThrownBy(() -> preparedCache.keyFor(kid)) + .isInstanceOf(SourcePreparedDenyException.class); + harness.transport.beforePatch = harness::assertPreparedDeny; + harness.transport.afterPatch = + () -> { + harness.assertLiveMatchesPreparedActiveIntent(); + harness.assertNoActiveReceipt(); + harness.assertPreparedDeny(); + assertThatThrownBy(transitionCache::refresh) + .isInstanceOf(SourcePreparedDenyException.class); + harness.manager.beforeCommit.set( + () -> + harness.observeBlockedPublicRead( + harness::assertPreparedDeny, + () -> + assertThat( + harness + .dsl + .resultQuery( + "SELECT count(*) FROM account_jwt_signer_promotion_operations " + + "WHERE active_jwks_receipt_digest IS NOT NULL") + .fetchOne(0, Long.class)) + .isZero())); + }; + try { + assertThatThrownBy(harness::reconcilePromotion) + .isInstanceOf(TransactionSystemException.class); + } finally { + harness.awaitBlockedPublicRead(); + } + harness.assertNoActiveReceipt(); + harness.assertLiveMatchesPreparedActiveIntent(); + harness.assertPreparedDeny(); + int writtenPatches = harness.transport.patches; + harness.transport.clearHooks(); + harness.assertChangedPrivateReceiptReplayRefused(); + harness.transport.unavailable = true; + try { + harness.assertUnavailableRead(); + assertThatThrownBy(transitionCache::refresh).isInstanceOf(SourcePreparedDenyException.class); + assertThatThrownBy(() -> transitionCache.keyFor(kid)) + .isInstanceOf(SourcePreparedDenyException.class); + assertThatThrownBy(() -> preparedCache.keyFor(kid)) + .isInstanceOf(SourcePreparedDenyException.class); + } finally { + harness.transport.unavailable = false; + } + harness.assertPreparedDeny(); + AtomicInteger exactReceiptPreparedReads = new AtomicInteger(); + harness.afterInventory = + () -> { + var promotion = + harness + .tx( + () -> + harness.desired.readPreparedGenerationForRecovery( + harness.binding.accountBinding(), harness.trust)) + .promotion(); + if (promotion.activeJwksReceiptDigest().isPresent()) { + exactReceiptPreparedReads.incrementAndGet(); + harness.assertPreparedDeny(); + assertThatThrownBy(preparedCache::refresh) + .isInstanceOf(SourcePreparedDenyException.class); + } + }; + harness.reconcilePromotion(); + harness.afterInventory = () -> {}; + assertThat(exactReceiptPreparedReads.get()).isEqualTo(1); + assertThat(harness.transport.patches).isEqualTo(writtenPatches); + var committed = + harness + .tx( + () -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) + .orElseThrow(); + assertThat(committed.promotion().status()).isEqualTo("COMMITTED"); + assertThat(committed.publicReceipt().observedResourceVersion()) + .isEqualTo(harness.transport.version); + ReadResult stable = harness.read(); + assertThat(stable.preparedDeny()).isFalse(); + assertThat(stable.committedRecoveryEligible()).isTrue(); + assertThat(stable.jwksBytes()).isEqualTo(harness.publicBytes()); + preparedCache.refresh(); + assertThat(preparedCache.keyFor(kid)).isNotNull(); + harness.assertCurrentMountedKeyCorrespondence(); + assertThat(stable.sourceIdentity()).isEqualTo(transitionCache.sourceIdentity()); + transitionCache.refresh(); + assertThat(transitionCache.keyFor(kid)).isNotNull(); + harness.reconcilePromotion(); + assertThat(harness.transport.patches).isEqualTo(writtenPatches); + assertThat( + harness + .tx( + () -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), + harness.trust, + API_DIGEST, + API_REVISION)) + .orElseThrow()) + .isEqualTo(committed); + + // Removing a key at the same UID is not a supported owner transition, even after prior commit. + Map stableData = harness.transport.data; + AccountPublicJwksCache tamperedCache = harness.cache(); + assertThat(tamperedCache.keyFor(kid)).isNotNull(); + Map removed = new LinkedHashMap<>(stableData); + removed.put("jwks.json", "{\"keys\":[]}"); + harness.transport.data = Map.copyOf(removed); + harness.assertInvalidRead(); + assertThatThrownBy(tamperedCache::refresh).isInstanceOf(InvalidJwksException.class); + harness.transport.data = stableData; + ReadResult restored = harness.read(); + assertThat(restored.sourceIdentity()).isEqualTo(stable.sourceIdentity()); + assertThat(restored.jwksBytes()).isEqualTo(stable.jwksBytes()); + assertThat(restored.preparedDeny()).isEqualTo(stable.preparedDeny()); + assertThat(restored.committedRecoveryEligible()).isEqualTo(stable.committedRecoveryEligible()); + assertThatThrownBy(tamperedCache::refresh).isInstanceOf(InvalidJwksException.class); + assertThatThrownBy(() -> tamperedCache.keyFor(kid)).isInstanceOf(InvalidJwksException.class); + } + + @Test + void durableReceiptCommitAcknowledgementLossRetainsBothWriterImagesAcrossExactReplay() + throws Exception { + Harness harness = harness(); + harness.generate(); + harness.transport.afterPatch = () -> harness.manager.loseCommitAcknowledgement.set(true); + assertThatThrownBy(harness.prepublication::prepublishCurrentGeneration) + .isInstanceOf(TransactionSystemException.class) + .hasMessage("Controlled durable receipt acknowledgement loss"); + harness.transport.clearHooks(); + var durablePublication = + harness + .independent( + () -> + harness.tx( + () -> + harness.publication.readCurrentPublication( + harness.binding.accountBinding(), harness.trust))) + .orElseThrow(); + var durableReceipt = durablePublication.receipt().orElseThrow(); + assertThat(durableReceipt.observedResourceVersion()).isEqualTo(harness.transport.version); + assertThat(durablePublication.intent().jwksJson()) + .isEqualTo(harness.transport.data.get("jwks.json")); + assertThat(durablePublication.intent().generationMarkerJson()) + .isEqualTo(harness.transport.data.get("jwt-generation.json")); + assertThat(harness.count("account_jwt_jwks_publication_receipts")).isEqualTo(1); + assertThat(harness.read().jwksBytes()).isEqualTo(harness.publicBytes()); + assertThat(harness.read().committedRecoveryEligible()).isFalse(); + int prepublicationPatches = harness.transport.patches; + assertThat(harness.prepublication.prepublishCurrentGeneration()).isEqualTo(durableReceipt); + assertThat(harness.transport.patches).isEqualTo(prepublicationPatches); + assertThat( + harness + .tx( + () -> + harness.publication.readCurrentPublication( + harness.binding.accountBinding(), harness.trust)) + .orElseThrow()) + .isEqualTo(durablePublication); + harness.mountAndObserve(); + harness.prepareAndRecordPrivatePromotion(); + harness.transport.afterPatch = () -> harness.manager.loseCommitAcknowledgement.set(true); + assertThatThrownBy(harness::reconcilePromotion) + .isInstanceOf(TransactionSystemException.class) + .hasMessage("Controlled durable receipt acknowledgement loss"); + harness.transport.clearHooks(); + var durableActive = + harness + .independent( + () -> + harness.tx( + () -> + harness.desired.readPreparedGenerationForRecovery( + harness.binding.accountBinding(), harness.trust))) + .promotion(); + assertThat(durableActive.status()).isEqualTo("PREPARED"); + assertThat(durableActive.activeJwksReceiptDigest()).isPresent(); + assertThat(durableActive.activeJwksObservedResourceVersion()) + .contains(harness.transport.version); + assertThat(durableActive.activeJwksPublicDataDigest()) + .contains( + AccountJwtJwksPublicationRepository.publicDataDigest( + harness.transport.data.get("jwks.json"), + harness.transport.data.get("jwt-generation.json"))); + assertThat(durableActive.expectedPublicJwksJson()) + .isEqualTo(harness.transport.data.get("jwks.json")); + assertThat(durableActive.expectedActiveMarkerJson()) + .isEqualTo(harness.transport.data.get("jwt-generation.json")); + harness.assertPreparedDeny(); + int activePatches = harness.transport.patches; + harness.reconcilePromotion(); + assertThat(harness.transport.patches).isEqualTo(activePatches); + var committed = + harness + .independent( + () -> + harness.tx( + () -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), + harness.trust, + API_DIGEST, + API_REVISION))) + .orElseThrow(); + assertThat(committed.publicReceipt().receiptDigest()) + .isEqualTo(durableActive.activeJwksReceiptDigest().orElseThrow()); + assertThat(committed.promotion().expectedPublicJwksJson()) + .isEqualTo(durableActive.expectedPublicJwksJson()); + assertThat(committed.promotion().expectedActiveMarkerJson()) + .isEqualTo(durableActive.expectedActiveMarkerJson()); + assertThat(harness.read().committedRecoveryEligible()).isTrue(); + assertThat(harness.read().jwksBytes()).isEqualTo(harness.publicBytes()); + assertThat(harness.count("account_jwt_jwks_publication_receipts")).isEqualTo(1); + } + + @Test + void bothWritersReconcileLostCasRepliesFromExactLiveReadbackWithoutASecondMutation() + throws Exception { + Harness harness = harness(); + harness.generate(); + harness.transport.losePatchReply.set(true); + harness.transport.afterPatch = + () -> { + harness.assertLiveMatchesCurrentPrepublicationIntent(); + assertThat(harness.count("account_jwt_jwks_publication_receipts")).isZero(); + harness.assertUnavailableRead(); + }; + var receipt = harness.prepublication.prepublishCurrentGeneration(); + harness.transport.clearHooks(); + assertThat(harness.transport.lostPatchReplies).isEqualTo(1); + assertThat(harness.transport.patches).isEqualTo(1); + assertThat(receipt.observedResourceVersion()).isEqualTo(harness.transport.version); + assertThat(harness.prepublication.prepublishCurrentGeneration()).isEqualTo(receipt); + assertThat(harness.transport.patches).isEqualTo(1); + harness.mountAndObserve(); + assertThat(harness.read().jwksBytes()).isEqualTo(harness.publicBytes()); + harness.prepareAndRecordPrivatePromotion(); + harness.transport.losePatchReply.set(true); + harness.transport.afterPatch = + () -> { + harness.assertLiveMatchesPreparedActiveIntent(); + harness.assertNoActiveReceipt(); + harness.assertPreparedDeny(); + }; + harness.reconcilePromotion(); + harness.transport.clearHooks(); + assertThat(harness.transport.lostPatchReplies).isEqualTo(2); + assertThat(harness.transport.patches).isEqualTo(2); + var committed = + harness + .tx( + () -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) + .orElseThrow(); + assertThat(committed.publicReceipt().observedResourceVersion()) + .isEqualTo(harness.transport.version); + assertThat(harness.read().committedRecoveryEligible()).isTrue(); + assertThat(harness.read().jwksBytes()).isEqualTo(harness.publicBytes()); + harness.reconcilePromotion(); + assertThat(harness.transport.patches).isEqualTo(2); + assertThat(harness.count("account_jwt_jwks_publication_receipts")).isEqualTo(1); + } + + @Test + void ordinaryPrepublicationOutagePreservesOriginalCacheAgeAndPendingReadinessCanProgress() + throws Exception { + Harness harness = harness(); + harness.generate(); + harness.prepublication.prepublishCurrentGeneration(); + harness.mountAndObserve(); + AdjustableClock clock = new AdjustableClock(Instant.parse("2026-11-10T12:00:00Z")); + AccountPublicJwksCache cache = harness.cache(clock, Duration.ofSeconds(5)); + String kid = harness.result.targetKid(); + assertThat(cache.keyFor(kid)).isNotNull(); + var pin = cache.sourceIdentity(); + assertThat(harness.read().committedRecoveryEligible()).isFalse(); + clock.advance(Duration.ofSeconds(4)); + harness.transport.unavailable = true; + try { + harness.assertUnavailableRead(); + cache.refresh(); + assertThat(cache.keyFor(kid)).isNotNull(); + clock.advance(Duration.ofSeconds(1)); + assertThatThrownBy(() -> cache.keyFor(kid)).isInstanceOf(SourceUnavailableException.class); + clock.advance(Duration.ofSeconds(1)); + assertThatThrownBy(cache::refresh).isInstanceOf(SourceUnavailableException.class); + } finally { + harness.transport.unavailable = false; + } + cache.refresh(); + assertThat(cache.keyFor(kid)).isNotNull(); + assertThat(harness.read().sourceIdentity()).isEqualTo(pin); + assertThat(harness.read().committedRecoveryEligible()).isFalse(); + // Receipt-backed pending keys are usable for real mounted-key readiness before PREPARED. + harness.prepareAndRecordPrivatePromotion(); + harness.assertPreparedDeny(); + assertThatThrownBy(cache::refresh).isInstanceOf(SourcePreparedDenyException.class); + assertThatThrownBy(() -> cache.keyFor(kid)).isInstanceOf(SourcePreparedDenyException.class); + harness.reconcilePromotion(); + harness.assertCurrentMountedKeyCorrespondence(); + assertThat(harness.read().sourceIdentity()).isEqualTo(pin); + assertThat(harness.read().committedRecoveryEligible()).isTrue(); + cache.refresh(); + assertThat(cache.keyFor(kid)).isNotNull(); + } + + private static final class AdjustableClock extends Clock { + private Instant now; + + private AdjustableClock(Instant now) { + this.now = now; + } + + private void advance(Duration duration) { + now = now.plus(duration); + } + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return Clock.fixed(now, zone); + } + + @Override + public Instant instant() { + return now; + } + } + + private Harness harness() throws Exception { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + return new Harness( + POSTGRES.dataSource(schema), + schema, + Files.createDirectory(temporaryDirectory.resolve(schema))); + } + + private static final class ReceiptCommitFailureManager extends DataSourceTransactionManager { + private static final long serialVersionUID = 1L; + private final transient ThreadLocal readerBackend = new ThreadLocal<>(); + private final AtomicReference beforeCommit = new AtomicReference<>(); + private final AtomicBoolean loseCommitAcknowledgement = new AtomicBoolean(); + + private ReceiptCommitFailureManager(DataSource dataSource) { + super(dataSource); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + super.doBegin(transaction, definition); + IntConsumer capture = readerBackend.get(); + if (capture != null) { + var connection = + DataSourceUtils.getConnection(java.util.Objects.requireNonNull(getDataSource())); + try (var statement = connection.createStatement(); + var result = statement.executeQuery("SELECT pg_backend_pid()")) { + if (!result.next()) throw new IllegalStateException("Reader backend PID unavailable"); + capture.accept(result.getInt(1)); + } catch (java.sql.SQLException failure) { + throw new TransactionSystemException("Reader backend PID unavailable", failure); + } finally { + DataSourceUtils.releaseConnection(connection, getDataSource()); + } + } + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + Runnable cut = beforeCommit.getAndSet(null); + if (cut != null) { + try { + cut.run(); + } finally { + super.doRollback(status); + } + throw new TransactionSystemException("Controlled owner receipt commit loss"); + } + super.doCommit(status); + if (loseCommitAcknowledgement.getAndSet(false)) { + throw new TransactionSystemException("Controlled durable receipt acknowledgement loss"); + } + } + } + + private static final class Harness { + private final DSLContext dsl; + private final ReceiptCommitFailureManager manager; + private final TransactionTemplate transaction; + private final AccountJwtSignerMaterializerTrustBinding.Binding binding; + private final TrustFence trust; + private final AccountJwtSignerDesiredStateRepository desired; + private final AccountJwtJwksPublicationRepository publication; + private final AccountJwtReadinessProbeRepository readiness; + private final AccountJwtJwksPrepublicationService prepublication; + private final AccountJwtSignerBootstrapCoordinator coordinator; + private final AccountPublicJwksReadService publicRead; + private final ControlledTransport transport; + private final AccountJwtJwksConfigMapClient configMap; + private final Path privateMount; + private final Path publicMount; + private GenerationRequest request; + private GenerationResult result; + private KeyPair keyPair; + private AccountJwtPreparedPublicationPostgresFixture readinessFixture; + private PrivatePromotionObservation privateObservation; + private PrivatePromotionReceipt privateReceipt; + private Runnable afterInventory = () -> {}; + private final AtomicReference> blockedPublicRead = + new AtomicReference<>(); + + private Harness(DataSource dataSource, String schema, Path directory) throws Exception { + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + manager = new ReceiptCommitFailureManager(dataSource); + transaction = new TransactionTemplate(manager); + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + String peer = "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + List pins = List.of("d".repeat(64)); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "trust-r1", + "prod", + "prod-cluster-1", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + peer, + pins); + binding = + new AccountJwtSignerMaterializerTrustBinding.Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + peer, + pins, + "trust-r1", + digest); + trust = new TrustFence(CLUSTER_UID, NAMESPACE_UID, digest, "trust-r1"); + var materializer = mock(AccountJwtSignerMaterializerTrustBinding.class); + when(materializer.current()).thenReturn(Optional.of(binding)); + ParsedBinding parsed = + new ParsedBinding( + API_REVISION, + "prod", + "prod-cluster-1", + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("unused-ca.pem"), + "b".repeat(64), + Path.of("unused-token"), + "firemud-prod", + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:firemud-prod:account-service", + API_DIGEST); + var api = mock(AccountJwtJwksApiBinding.class); + when(api.current()).thenReturn(parsed); + transport = new ControlledTransport(parsed); + configMap = new AccountJwtJwksConfigMapClient(() -> transport); + desired = new AccountJwtSignerDesiredStateRepository(dsl); + publication = new AccountJwtJwksPublicationRepository(dsl, desired); + readiness = + new AccountJwtReadinessProbeRepository( + dsl, desired, publication, new AccountJwtValidatorInventoryRepository(dsl)); + privateMount = Files.createDirectory(directory.resolve("private")); + publicMount = Files.createDirectory(directory.resolve("public")); + transport.projectPublishedData = + () -> { + try { + Files.writeString(publicMount.resolve("jwks.json"), transport.data.get("jwks.json")); + Files.writeString( + publicMount.resolve("jwt-generation.json"), + transport.data.get("jwt-generation.json")); + } catch (java.io.IOException failure) { + throw new IllegalStateException( + "Controlled public projection could not catch up", failure); + } + }; + prepublication = + new AccountJwtJwksPrepublicationService( + desired, + publication, + materializer, + configMap, + manager, + new AccountJwtJwksPrepublicationService.MountedProjection( + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json"), + Path.of("jwt-generation.json"))); + var inventory = mock(AccountJwtValidatorInventorySource.class); + when(inventory.observe(any(AccountJwtValidatorInventorySource.ObservationContext.class))) + .thenAnswer( + invocation -> { + afterInventory.run(); + return readinessFixture.currentInventory(dsl, invocation.getArgument(0)); + }); + var beans = new DefaultListableBeanFactory(); + beans.registerSingleton("controlledInventory", inventory); + coordinator = + new AccountJwtSignerBootstrapCoordinator( + materializer, + configMap, + desired, + prepublication, + readiness, + beans.getBeanProvider(AccountJwtValidatorInventorySource.class), + transaction); + var source = + new AccountJwtJwksTrustedSource(configMap, materializer, desired, publication, manager); + publicRead = + new AccountPublicJwksReadService( + source, + new AccountPublicJwksReadWorkloadGuard(materializer, api, binding.namespace())); + coordinator.enrollOnce(); + } + + private void generate() throws Exception { + request = tx(() -> desired.ensureCurrentGenerationRequest(binding.accountBinding(), trust)); + String prior = result == null ? "12" : "14"; + String next = result == null ? "13" : "15"; + var observed = + tx( + () -> + desired.recordSecretObservation( + binding.accountBinding(), + trust, + request.operationId(), + request.operationDigest(), + SECRET_UID, + prior)); + keyPair = generateRsa3072(); + PublicJwk jwk = publicJwk(request.targetKid(), (RSAPublicKey) keyPair.getPublic()); + result = + tx( + () -> + desired.recordGenerationResult( + binding.accountBinding(), + trust, + request.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + prior, + next, + jwk.json())); + Files.writeString( + privateMount.resolve("pending.key"), privateBundleJson(request, result, keyPair)); + readinessFixture = + new AccountJwtPreparedPublicationPostgresFixture( + binding.accountBinding(), trust, result, API_DIGEST, API_REVISION); + } + + private void mountAndObserve() throws Exception { + Files.writeString(publicMount.resolve("jwks.json"), transport.data.get("jwks.json")); + Files.writeString( + publicMount.resolve("jwt-generation.json"), transport.data.get("jwt-generation.json")); + prepublication.observeCurrentMountedCorrespondence(); + } + + private void prepareAndRecordPrivatePromotion() throws Exception { + readinessFixture.completeReadiness(readiness, transaction, dsl, privateMount, publicMount); + assertThat(coordinator.prepareCurrentPromotionOnce()).isPresent(); + var prepared = + tx(() -> desired.readAndMarkPreparedPromotionDispatched(binding.accountBinding(), trust)) + .promotion(); + privateObservation = + new PrivatePromotionObservation( + prepared.operationId(), + prepared.requestDigest(), + prepared.generationOperationId(), + prepared.generationOperationDigest(), + result.secretUid(), + prepared.expectedPrivateResourceVersion(), + "14", + new PublicKeyIdentity( + prepared.targetGeneration(), + prepared.targetKid(), + prepared.targetPublicKeyFingerprint()), + Optional.empty(), + List.of("current")); + privateReceipt = + tx( + () -> + desired.recordPrivatePromotionResult( + binding.accountBinding(), trust, privateObservation)); + Files.writeString( + privateMount.resolve("current.key"), privateBundleJson(request, result, keyPair)); + } + + private void commitInitialSigner() throws Exception { + generate(); + prepublication.prepublishCurrentGeneration(); + mountAndObserve(); + prepareAndRecordPrivatePromotion(); + reconcilePromotion(); + assertThat(read().committedRecoveryEligible()).isTrue(); + } + + private void reconcilePromotion() { + coordinator.reconcilePreparedPromotionOnce(privateObservation, privateReceipt); + } + + private ReadResult read() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud-prod/sa/game-session-service") + .orElseThrow(); + try { + return Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .call( + () -> + AccountPublicJwksReadCodec.result( + publicRead.read(AccountPublicJwksReadCodec.request()))); + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } + + private void assertUnavailableRead() { + assertThatThrownBy(this::read).isExactlyInstanceOf(SourceUnavailableException.class); + } + + private void assertInvalidRead() { + assertThatThrownBy(this::read).isExactlyInstanceOf(InvalidJwksException.class); + } + + private void assertPreparedDeny() { + ReadResult deny = read(); + assertThat(deny.preparedDeny()).isTrue(); + assertThat(deny.committedRecoveryEligible()).isFalse(); + assertThat(deny.jwksBytes()).isEmpty(); + } + + private void assertNoActiveReceipt() { + assertThat( + tx(() -> desired.readPreparedGenerationForRecovery(binding.accountBinding(), trust)) + .promotion() + .activeJwksReceiptDigest()) + .isEmpty(); + } + + private void assertLiveMatchesCurrentPrepublicationIntent() { + var evidence = + tx(() -> publication.readCurrentPublication(binding.accountBinding(), trust)) + .orElseThrow(); + var intent = evidence.intent(); + ConfigMapSnapshot live = configMap.observe(); + assertThat(intent.operationId()).isEqualTo(result.operationId()); + assertThat(intent.operationDigest()).isEqualTo(result.operationDigest()); + assertThat(intent.generationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(intent.binding()).isEqualTo(binding.accountBinding()); + assertThat(intent.trustFence()).isEqualTo(trust); + assertThat(intent.apiBindingDigest()).isEqualTo(API_DIGEST); + assertThat(intent.apiConfigRevision()).isEqualTo(API_REVISION); + assertThat(live.uid()).isEqualTo(intent.configMapUid()); + assertThat(live.resourceVersion()).isNotEqualTo(intent.expectedResourceVersion()); + assertThat(live.data().get("jwks.json")).isEqualTo(intent.jwksJson()); + assertThat(live.data().get("jwt-generation.json")).isEqualTo(intent.generationMarkerJson()); + assertThat( + AccountJwtJwksPublicationRepository.publicDataDigest( + live.data().get("jwks.json"), live.data().get("jwt-generation.json"))) + .isEqualTo(intent.publicDataDigest()); + } + + private void assertLiveMatchesPreparedActiveIntent() { + var promotion = + tx(() -> desired.readPreparedGenerationForRecovery(binding.accountBinding(), trust)) + .promotion(); + var prepublished = + tx(() -> publication.readPreparedPublicationForRecovery(binding.accountBinding(), trust)); + ConfigMapSnapshot live = configMap.observe(); + assertThat(promotion.generationOperationId()).isEqualTo(result.operationId()); + assertThat(promotion.generationOperationDigest()).isEqualTo(result.operationDigest()); + assertThat(promotion.generationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(promotion.binding()).isEqualTo(binding.accountBinding()); + assertThat(promotion.trustFence()).isEqualTo(trust); + assertThat(promotion.apiBindingDigest()).isEqualTo(API_DIGEST); + assertThat(promotion.apiConfigRevision()).isEqualTo(API_REVISION); + assertThat(promotion.prepublicationIntentDigest()) + .isEqualTo(prepublished.intent().intentDigest()); + assertThat(promotion.prepublicationReceiptDigest()) + .isEqualTo(prepublished.receipt().receiptDigest()); + assertThat(promotion.mountedObservationDigest()) + .isEqualTo(prepublished.mountedCorrespondence().observationDigest()); + assertThat(promotion.expectedPublicResourceVersion()) + .isEqualTo(prepublished.receipt().observedResourceVersion()); + assertThat(live.uid()).isEqualTo(promotion.publicConfigMapUid()); + assertThat(live.resourceVersion()).isNotEqualTo(promotion.expectedPublicResourceVersion()); + assertThat(live.data().get("jwks.json")).isEqualTo(promotion.expectedPublicJwksJson()); + assertThat(live.data().get("jwt-generation.json")) + .isEqualTo(promotion.expectedActiveMarkerJson()); + assertThat( + AccountJwtJwksPublicationRepository.publicDataDigest( + live.data().get("jwks.json"), live.data().get("jwt-generation.json"))) + .isEqualTo( + AccountJwtJwksPublicationRepository.publicDataDigest( + promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson())); + } + + private void assertChangedPrivateReceiptReplayRefused() { + Map> retained = ownerHistoryImages(); + PrivatePromotionObservation changed = + new PrivatePromotionObservation( + privateObservation.promotionOperationId(), + privateObservation.promotionRequestDigest(), + privateObservation.generationOperationId(), + privateObservation.generationOperationDigest(), + privateObservation.secretUid(), + privateObservation.expectedPriorResourceVersion(), + privateObservation.observedResourceVersion() + "-changed", + privateObservation.current(), + privateObservation.previous(), + privateObservation.resultingSlots()); + assertThatThrownBy( + () -> + tx( + () -> + desired.recordPrivatePromotionResult( + binding.accountBinding(), trust, changed))) + .isExactlyInstanceOf( + AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class) + .hasMessage("Private promotion readback changed for the same Account operation"); + assertThat(ownerHistoryImages()).isEqualTo(retained); + assertThat( + tx( + () -> + desired.recordPrivatePromotionResult( + binding.accountBinding(), trust, privateObservation))) + .isEqualTo(privateReceipt); + assertPreparedDeny(); + } + + private void assertCurrentMountedKeyCorrespondence() { + var identity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + result.operationId().toString(), + result.targetGeneration(), + result.targetKid(), + result.publicKeyFingerprint()); + assertThat( + AccountMountedJwtSignerBundle.observeMounted( + privateMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity) + .expectedIdentity()) + .isEqualTo(identity); + } + + private AccountPublicJwksCache cache() { + return cache(Clock.systemUTC(), Duration.ofMinutes(5)); + } + + private AccountPublicJwksCache cache(Clock clock, Duration maximumAge) { + ReadResult initial = read(); + return new AccountPublicJwksCache( + () -> { + ReadResult current = read(); + if (current.preparedDeny()) throw new SourcePreparedDenyException(); + return new PublicJwksSnapshot( + current.sourceIdentity(), current.jwksBytes(), current.committedRecoveryEligible()); + }, + initial.sourceIdentity(), + clock, + maximumAge); + } + + private byte[] publicBytes() { + return transport.data.get("jwks.json").getBytes(StandardCharsets.UTF_8); + } + + private T tx(Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + /** The same public read waits on real owner locks and is awaited only after rollback. */ + private void observeBlockedPublicRead( + Runnable assertAfterRollback, Runnable assertCommittedReceiptAbsent) { + int writerPid = + java.util.Objects.requireNonNull( + dsl.resultQuery("SELECT pg_backend_pid()").fetchOne(0, Integer.class)); + AtomicInteger readerPid = new AtomicInteger(); + CountDownLatch readerBegan = new CountDownLatch(1); + CompletableFuture reader = + CompletableFuture.runAsync( + () -> { + manager.readerBackend.set( + pid -> { + if (readerPid.compareAndSet(0, pid)) readerBegan.countDown(); + }); + try { + assertAfterRollback.run(); + } finally { + manager.readerBackend.remove(); + } + }); + assertThat(blockedPublicRead.compareAndSet(null, reader)).isTrue(); + try { + assertThat(readerBegan.await(5, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Independent public read did not start", interrupted); + } + Awaitility.await() + .alias("exact public reader waits on actual receipt writer") + .atMost(Duration.ofSeconds(5)) + .until( + () -> + independent( + () -> + Boolean.TRUE.equals( + dsl.resultQuery( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = ? " + + "AND wait_event_type = 'Lock' AND ? = ANY(pg_blocking_pids(pid)))", + readerPid.get(), + writerPid) + .fetchOne(0, Boolean.class)))); + assertThat(reader.isDone()).isFalse(); + independent( + () -> { + assertCommittedReceiptAbsent.run(); + return null; + }); + } + + private void awaitBlockedPublicRead() { + CompletableFuture reader = blockedPublicRead.getAndSet(null); + assertThat(reader).isNotNull(); + try { + reader.get(10, TimeUnit.SECONDS); + } catch (Exception failure) { + throw new IllegalStateException( + "Same public reader did not reach its expected classification after rollback", failure); + } finally { + reader.cancel(true); + } + } + + private T independent(Supplier operation) { + try { + return CompletableFuture.supplyAsync(operation).get(10, TimeUnit.SECONDS); + } catch (Exception failure) { + throw new IllegalStateException("Independent public read failed", failure); + } + } + + /** Full retained owner/receipt row images plus MVCC identity; these are read-only witnesses. */ + private Map> ownerHistoryImages() { + Map> images = new LinkedHashMap<>(); + for (String table : + List.of( + "account_jwt_signer_desired_states", + "account_jwt_signer_generation_operations", + "account_jwt_signer_secret_observations", + "account_jwt_signer_generation_results", + "account_jwt_signer_generation_abort_receipts", + "account_jwt_signer_promotion_operations", + "account_jwt_jwks_prepublication_intents", + "account_jwt_jwks_publication_receipts", + "account_jwt_jwks_mount_observations")) { + images.put( + table, + dsl.resultQuery( + "SELECT history.xmin::text || ':' || row_to_json(history)::text " + + "FROM " + + table + + " history ORDER BY row_to_json(history)::text") + .fetch(0, String.class)); + } + return Map.copyOf(images); + } + + private long count(String table) { + return java.util.Objects.requireNonNull( + dsl.resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class)); + } + } + + private static final class ControlledTransport + implements AccountJwtJwksConfigMapClient.ApiSession { + private final ParsedBinding binding; + private Map data = + Map.of("jwks.json", "{\"keys\":[]}", "unrelated.txt", "preserve"); + private String version = "41"; + private int patches; + private boolean unavailable; + private final AtomicBoolean losePatchReply = new AtomicBoolean(); + private int lostPatchReplies; + private Runnable projectPublishedData = () -> {}; + private Runnable beforePatch = () -> {}; + private Runnable afterPatch = () -> {}; + + private ControlledTransport(ParsedBinding binding) { + this.binding = binding; + } + + @Override + public ParsedBinding binding() { + return binding; + } + + @Override + public ApiResponse send(ApiCall call, byte[] body) { + try { + if (unavailable && call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL) { + return response(503, Map.of()); + } + return switch (call) { + case REVIEW_AUTHENTICATED_PRINCIPAL -> + response( + 201, + Map.of( + "apiVersion", + "authentication.k8s.io/v1", + "kind", + "SelfSubjectReview", + "status", + Map.of("userInfo", Map.of("username", binding.expectedApiUsername())))); + case READ_KUBE_SYSTEM_NAMESPACE, READ_TARGET_NAMESPACE -> + response( + 200, + Map.of( + "apiVersion", + "v1", + "kind", + "Namespace", + "metadata", + Map.of( + "name", + call == ApiCall.READ_KUBE_SYSTEM_NAMESPACE + ? "kube-system" + : binding.namespace(), + "uid", + call == ApiCall.READ_KUBE_SYSTEM_NAMESPACE + ? CLUSTER_UID + : NAMESPACE_UID), + "status", + Map.of("phase", "Active"))); + case READ_JWKS_CONFIG_MAP -> configMapResponse(); + case PATCH_JWKS_CONFIG_MAP -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + beforePatch.run(); + var patch = JSON.readTree(body); + assertThat(patch.path("metadata").path("uid").asText()).isEqualTo(CONFIG_MAP_UID); + assertThat(patch.path("metadata").path("resourceVersion").asText()).isEqualTo(version); + assertThat(patch.path("data").size()).isEqualTo(2); + assertThat(patch.path("data").has("jwks.json")).isTrue(); + assertThat(patch.path("data").has("jwt-generation.json")).isTrue(); + Map changed = new LinkedHashMap<>(data); + for (String key : List.of("jwks.json", "jwt-generation.json")) { + changed.put(key, patch.path("data").path(key).asText()); + } + data = Map.copyOf(changed); + version = Integer.toString(Integer.parseInt(version) + 1); + patches++; + projectPublishedData.run(); + afterPatch.run(); + if (losePatchReply.getAndSet(false)) { + lostPatchReplies++; + throw new AccountJwtJwksApiBinding.ApiTransportException(); + } + yield configMapResponse(); + } + default -> throw new IllegalStateException("Unexpected controlled API endpoint"); + }; + } catch (RuntimeException failure) { + throw failure; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } + + private ApiResponse configMapResponse() throws Exception { + return response( + 200, + Map.of( + "apiVersion", + "v1", + "kind", + "ConfigMap", + "metadata", + Map.of( + "name", + "jwt-jwks", + "namespace", + binding.namespace(), + "uid", + CONFIG_MAP_UID, + "resourceVersion", + version), + "data", + data)); + } + + private static ApiResponse response(int status, Map value) throws Exception { + return new ApiResponse(status, JSON.writeValueAsBytes(value)); + } + + private void clearHooks() { + beforePatch = () -> {}; + afterPatch = () -> {}; + } + + @Override + public void close() {} + } + + private static String privateBundleJson( + GenerationRequest request, GenerationResult result, KeyPair pair) { + Map bundle = new LinkedHashMap<>(); + bundle.put("version", 1); + bundle.put("environmentId", request.binding().environmentId()); + bundle.put("clusterId", request.binding().clusterId()); + bundle.put("namespace", request.binding().namespace()); + bundle.put("operationId", request.operationId().toString()); + bundle.put("generation", result.targetGeneration()); + bundle.put("kid", result.targetKid()); + bundle.put("algorithm", "RS256"); + bundle.put( + "privateKeyPkcs8", + Base64.getUrlEncoder().withoutPadding().encodeToString(pair.getPrivate().getEncoded())); + bundle.put("publicKeyFingerprint", result.publicKeyFingerprint()); + try { + return JSON.writeValueAsString(bundle); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } + + private static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new LinkedHashMap<>(); + jwk.put("alg", "RS256"); + jwk.put("e", exponent); + jwk.put("key_ops", List.of("verify")); + jwk.put("kid", kid); + jwk.put("kty", "RSA"); + jwk.put("n", modulus); + jwk.put("use", "sig"); + String json = canonicalJson(jwk); + Map withoutKeyOps = new LinkedHashMap<>(jwk); + withoutKeyOps.remove("key_ops"); + String jsonWithoutKeyOps = canonicalJson(withoutKeyOps); + String fingerprint = + sha256( + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(Map.of("e", exponent, "kty", "RSA", "n", modulus)))); + return new PublicJwk(json, jsonWithoutKeyOps, fingerprint); + } + + private static String canonicalJson(Map value) throws Exception { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)), + StandardCharsets.UTF_8); + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + private static KeyPair generateRsa3072() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3_072); + return generator.generateKeyPair(); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 is required for the persistence fixture", failure); + } + } + + private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java new file mode 100644 index 0000000000..9468d2277e --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.lettuce.core.RedisURI; +import java.net.URI; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** Controlled configuration proof only; no production credentials or protected mounts are read. */ +class AccountGameplayLoginProtectedSourcesConfigurationTest { + static final String API_PATH = "/etc/firemud/account-jwt-api/binding.json"; + private final AccountGameplayLoginProtectedSourcesConfiguration configuration = + new AccountGameplayLoginProtectedSourcesConfiguration(); + + @Test + void dedicatedUriRetainsExplicitTlsAclDatabaseAndCommandDeadline() { + RedisURI uri = + AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + "rediss://account_coord_app:test-only-password@coordination.example.invalid:6380/0", + 875); + + assertThat(uri.getHost()).isEqualTo("coordination.example.invalid"); + assertThat(uri.getPort()).isEqualTo(6380); + assertThat(uri.getDatabase()).isZero(); + assertThat(uri.isSsl()).isTrue(); + assertThat(uri.isVerifyPeer()).isTrue(); + var credentials = + uri.getCredentialsProvider().resolveCredentials().block(Duration.ofSeconds(1)); + assertThat(credentials).isNotNull(); + assertThat(credentials.getUsername()).isEqualTo("account_coord_app"); + assertThat(credentials.getPassword()).containsExactly("test-only-password".toCharArray()); + assertThat(uri.getTimeout()).isEqualTo(Duration.ofMillis(875)); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + "redis://account_coord_app:secret@coordination.example.invalid:6380/0", + "rediss://default:secret@coordination.example.invalid:6380/0", + "rediss://account_coord_app:@coordination.example.invalid:6380/0", + "rediss://account_coord_app:secret@coordination.example.invalid/0", + "rediss://account_coord_app:secret@coordination.example.invalid:6380", + "rediss://account_coord_app:secret@coordination.example.invalid:6380/1", + "rediss://account_coord_app:secret@coordination.example.invalid:6380/0?verifyPeer=false", + "rediss://account_coord_app:secret@coordination.example.invalid:6380/0#extra", + "rediss://account_coord_app:secret%0a@coordination.example.invalid:6380/0", + "not a URI containing secret" + }) + void refusesMissingAmbiguousOrWeakerUriWithoutRetainingCredentialCauses(String uri) { + assertThatThrownBy( + () -> + AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri(uri, 500)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Protected Account gameplay LOGIN configuration required") + .hasNoCause(); + } + + @ParameterizedTest + @ValueSource(ints = {0, -1, 60_001}) + void commandDeadlineMustBeExplicitAndBounded(int timeout) { + assertThatThrownBy( + () -> + AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + "rediss://account_coord_app:secret@coordination.example.invalid:6380/0", + timeout)) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause(); + } + + @Test + void accountAcknowledgementsCannotUseTheGameSessionSingleNodeException() { + var ack = configuration.accountGameplayLoginAcknowledgements(1, 2, 750); + assertThat(ack.requiredLocalAofCount()).isEqualTo(1); + assertThat(ack.requiredReplicaAofCount()).isEqualTo(2); + assertThat(ack.timeoutMillis()).isEqualTo(750); + assertThatThrownBy(() -> configuration.accountGameplayLoginAcknowledgements(1, 0, 750)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> configuration.accountGameplayLoginAcknowledgements(0, 1, 750)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> configuration.accountGameplayLoginAcknowledgements(1, 1, 0)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void protectedApiAndMaterializerMustMatchTheConfiguredNamespaceAndIncarnations() { + var trust = mock(AccountJwtSignerMaterializerTrustBinding.class); + when(trust.current()).thenReturn(Optional.of(materializerBinding())); + try (var construction = + mockConstruction( + AccountJwtJwksApiBinding.class, + (api, context) -> when(api.current()).thenReturn(apiBinding("test", "cluster-a")))) { + assertThat( + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "test")) + .isSameAs(construction.constructed().getFirst()); + assertThatThrownBy( + () -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "other")) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause(); + } + try (var construction = + mockConstruction( + AccountJwtJwksApiBinding.class, + (api, context) -> + when(api.current()).thenReturn(apiBinding("test", "other-cluster")))) { + assertThatThrownBy( + () -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause(); + assertThat(construction.constructed()).hasSize(1); + } + } + + @Test + void missingWithdrawnOrAlternateProtectedSourcesNeverProduceAnApiBinding() { + var trust = mock(AccountJwtSignerMaterializerTrustBinding.class); + when(trust.current()).thenReturn(Optional.empty()); + try (var construction = mockConstruction(AccountJwtJwksApiBinding.class)) { + assertThatThrownBy( + () -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause(); + assertThat(construction.constructed()).hasSize(1); + } + when(trust.current()).thenReturn(Optional.of(materializerBinding())); + try (var construction = + mockConstruction( + AccountJwtJwksApiBinding.class, + (api, context) -> + when(api.current()) + .thenThrow(new AccountJwtJwksApiBinding.BindingRejectedException()))) { + assertThatThrownBy( + () -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause(); + assertThat(construction.constructed()).hasSize(1); + } + assertThatThrownBy( + () -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, "/alternate/binding", "test")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "")) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"", "relative/keyring", "/run/../other/keyring"}) + void missingRelativeOrUnnormalizedMountSelectorsFail(String path) { + assertThatThrownBy(() -> AccountGameplayLoginProtectedSourcesConfiguration.requiredMount(path)) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause(); + } + + static AccountJwtSignerMaterializerTrustBinding.Binding materializerBinding() { + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + String peer = "spiffe://firemud/ns/test/sa/account-jwt-signer-materializer"; + List pins = List.of("a".repeat(64)); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "test-revision", "test", "cluster-a", "test", clusterUid, namespaceUid, peer, pins); + return new AccountJwtSignerMaterializerTrustBinding.Binding( + "test", "cluster-a", "test", clusterUid, namespaceUid, peer, pins, "test-revision", digest); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "Fixed nonexistent paths identify controlled API metadata in this wiring-only test; no protected mount, token or certificate is read.") + static AccountJwtJwksApiBinding.ParsedBinding apiBinding(String namespace, String cluster) { + var trust = materializerBinding(); + return new AccountJwtJwksApiBinding.ParsedBinding( + "test-api-revision", + trust.environmentId(), + cluster, + URI.create("https://api.example.invalid:6443/"), + "api.example.invalid", + Path.of("/not-read-by-configuration-test/serving-ca.pem"), + "b".repeat(64), + Path.of("/not-read-by-configuration-test/token"), + namespace, + trust.expectedClusterIncarnationUid(), + trust.expectedNamespaceUid(), + "system:serviceaccount:" + namespace + ":account-service", + "c".repeat(64)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java new file mode 100644 index 0000000000..29b075bd0c --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java @@ -0,0 +1,323 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.codec.ByteArrayCodec; +import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisContract; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAuthenticateReceiver; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Real intermediate-owner wiring with controlled SQL, primary credentials, API trust and Redis + * transport edges. This does not prove protected key custody, enrolled signer state or LOGIN. + */ +class AccountGameplayLoginSourceConfigurationTest { + private static final Class[] CONFIGURATIONS = { + CanonicalGameplayRuntimeConfiguration.class, + AccountGameplayLoginSourceConfiguration.class, + AccountGameplayLoginProtectedSourcesConfiguration.class + }; + + @Test + void entireGraphIsAbsentByDefaultEvenWithoutOwnerInfrastructure() { + new ApplicationContextRunner() + .withUserConfiguration(CONFIGURATIONS) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(AccountGameplayAuthenticateReceiver.class); + assertThat(context).doesNotHaveBean(AccountGameplayDelegationSigner.class); + assertThat(context).doesNotHaveBean(AccountJwtJwksApiBinding.class); + assertThat(context).doesNotHaveBean(AccountGameplayDelegationRedisClient.class); + }); + new ApplicationContextRunner() + .withUserConfiguration(CONFIGURATIONS) + .withPropertyValues("firemud.account.gameplay-login.enabled=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(AccountGameplayAuthenticateReceiver.class); + }); + } + + @Test + void explicitEnableCannotSilentlyLeaveTheReceiverUncomposed() { + new ApplicationContextRunner() + .withUserConfiguration(CONFIGURATIONS) + .withPropertyValues("firemud.account.gameplay-login.enabled=true") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void fullCompositionUsesGenuineIntermediateOwnersAndClosesItsDedicatedClient() { + RedisClient client = mock(RedisClient.class); + try (var redisFactory = mockStatic(RedisClient.class); + var apiConstruction = + mockConstruction( + AccountJwtJwksApiBinding.class, + (api, construction) -> + when(api.current()) + .thenReturn( + AccountGameplayLoginProtectedSourcesConfigurationTest.apiBinding( + "test", "cluster-a")))) { + redisFactory.when(() -> RedisClient.create(any(RedisURI.class))).thenReturn(client); + enabledContext() + .withPropertyValues("firemud.account.public-jwks-read.enabled=true") + .run( + context -> { + assertThat(context).hasNotFailed(); + for (Class owner : + List.of( + AccountAuthEvidenceBundleRepository.class, + AccountGameplayDelegationIssuanceRepository.class, + AccountGameplayDelegationResponseEnvelopeRepository.class, + AccountGameplayDelegationResponseEnvelopeService.class, + AccountJwtJwksConfigMapClient.class, + AccountJwtJwksTrustedSource.class, + AccountGameplayDelegationSigner.class, + AccountGameplayDelegationRedisClient.class, + AccountGameplayDelegationAuthorityProjection.class, + AccountGameplayDelegationTokenRegistry.class, + AccountGameplayDelegationIssuanceCommitService.class, + AccountGameplayDelegationCommittedIssuanceOwner.class, + AccountGameplayDelegationResponseRecoveryOwner.class, + AccountGameplayAuthenticateReceiver.class)) { + assertThat(context).hasSingleBean(owner); + } + + var issuance = context.getBean(AccountGameplayDelegationIssuanceRepository.class); + var signer = context.getBean(AccountGameplayDelegationSigner.class); + var commits = context.getBean(AccountGameplayDelegationIssuanceCommitService.class); + var recovery = + context.getBean(AccountGameplayDelegationResponseRecoveryOwner.class); + var registry = context.getBean(AccountGameplayDelegationTokenRegistry.class); + var envelopes = + context.getBean(AccountGameplayDelegationResponseEnvelopeRepository.class); + assertThat(ReflectionTestUtils.getField(signer, "issuanceRepository")) + .isSameAs(issuance); + assertThat(ReflectionTestUtils.getField(commits, "signer")).isSameAs(signer); + assertThat(ReflectionTestUtils.getField(commits, "tokenRegistry")) + .isSameAs(registry); + assertThat(ReflectionTestUtils.getField(recovery, "responseEnvelopes")) + .isSameAs(envelopes); + assertThat(ReflectionTestUtils.getField(envelopes, "responseCryptography")) + .isSameAs(context.getBean("accountResponseEnvelopeCryptography")); + var receiver = context.getBean(AccountGameplayAuthenticateReceiver.class); + var login = ReflectionTestUtils.getField(receiver, "owner"); + assertThat(ReflectionTestUtils.getField(login, "commitOwner")).isSameAs(commits); + assertThat(ReflectionTestUtils.getField(login, "responseOwner")).isSameAs(recovery); + assertThat(ReflectionTestUtils.getField(receiver, "expectedWorkload")) + .isEqualTo("spiffe://firemud/ns/test/sa/game-session-service"); + assertThat(context.getBean(AcknowledgementRequirements.class)) + .isEqualTo(new AcknowledgementRequirements(1, 2, 900)); + var catalog = + (RedisScriptCatalog) + ReflectionTestUtils.getField( + context.getBean(AccountGameplayDelegationRedisClient.class), + "scriptCatalog"); + assertThat(catalog).isNotNull(); + assertThat(catalog.require(AccountGenerationProjectionRedisContract.SCRIPT_ID)) + .isEqualTo(AccountGenerationProjectionRedisContract.descriptor()); + assertThat( + catalog.require(AccountGameplayDelegationRedisClient.SCRIPT_ID).principal()) + .isEqualTo("account_coord_app"); + assertThat( + catalog + .require( + AccountGameplayDelegationRedisClient + .INITIAL_LOGIN_DISPOSAL_SCRIPT_ID) + .principal()) + .isEqualTo("account_coord_app"); + assertThat(apiConstruction.constructed()).hasSize(1); + verifyNoInteractions(context.getBean(DSLContext.class)); + verifyNoInteractions(context.getBean(AccountServiceImpl.class)); + verify(client, never()).connect(ByteArrayCodec.INSTANCE); + }); + var options = ArgumentCaptor.forClass(ClientOptions.class); + verify(client).setOptions(options.capture()); + assertThat(options.getValue().isAutoReconnect()).isFalse(); + verify(client).shutdown(); + } + } + + @Test + void absentMountSelectorsAndUnboundedRetentionFailWithoutOpeningConnections() { + RedisClient client = mock(RedisClient.class); + try (var redisFactory = mockStatic(RedisClient.class); + var apiConstruction = + mockConstruction( + AccountJwtJwksApiBinding.class, + (api, construction) -> + when(api.current()) + .thenReturn( + AccountGameplayLoginProtectedSourcesConfigurationTest.apiBinding( + "test", "cluster-a")))) { + redisFactory.when(() -> RedisClient.create(any(RedisURI.class))).thenReturn(client); + enabledContext() + .withPropertyValues("firemud.account.gameplay-login.request-digest-keyring-path=") + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Protected Account gameplay LOGIN configuration required"); + verify(client, never()).connect(ByteArrayCodec.INSTANCE); + }); + enabledContext() + .withPropertyValues("firemud.account.response-envelope.keyring-path=") + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Protected Account gameplay LOGIN configuration required"); + verify(client, never()).connect(ByteArrayCodec.INSTANCE); + }); + enabledContext() + .withPropertyValues( + "firemud.account.gameplay-login.registry-cleanup-margin-millis=300001") + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Registry cleanup margin is outside its finite bound"); + verify(client, never()).connect(ByteArrayCodec.INSTANCE); + }); + assertThat(apiConstruction.constructed()).isNotEmpty(); + verify(client, never()).connect(ByteArrayCodec.INSTANCE); + } + } + + private static ApplicationContextRunner enabledContext() { + return new ApplicationContextRunner() + .withUserConfiguration(CONFIGURATIONS) + .withUserConfiguration(ExistingOwnerInfrastructure.class) + .withPropertyValues( + "firemud.account.gameplay-login.enabled=true", + "firemud.grpc.workload-namespace=test", + "firemud.account.public-jwks.api-binding-path=" + + AccountGameplayLoginProtectedSourcesConfigurationTest.API_PATH, + "firemud.account.gameplay-login.coordination.uri=" + + "rediss://account_coord_app:test-only-password@coordination.example.invalid:6380/0", + "firemud.account.gameplay-login.coordination.command-timeout-millis=800", + "firemud.account.gameplay-login.coordination.required-local-aof-count=1", + "firemud.account.gameplay-login.coordination.required-replica-aof-count=2", + "firemud.account.gameplay-login.coordination.acknowledgement-timeout-millis=900", + "firemud.account.gameplay-login.registry-cleanup-margin-millis=5000", + "firemud.account.gameplay-login.request-digest-keyring-path=/not-read-by-configuration-test/digest", + "firemud.account.response-envelope.keyring-path=/not-read-by-configuration-test/response"); + } + + @TestConfiguration(proxyBeanMethods = false) + static class ExistingOwnerInfrastructure { + @Bean + DSLContext dsl() { + return mock(DSLContext.class); + } + + @Bean + AccountAuthorityGenerationRepository generations(DSLContext dsl) { + return new AccountAuthorityGenerationRepository(dsl); + } + + @Bean + AccountAuthorityOutboxRepository outbox(DSLContext dsl) { + return new AccountAuthorityOutboxRepository(dsl); + } + + @Bean + AccountAuthoritySourceEvidenceRepository sources( + DSLContext dsl, + AccountAuthorityGenerationRepository generations, + AccountAuthorityOutboxRepository outbox) { + return new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + } + + @Bean + AccountRepository accounts(DSLContext dsl, AccountAuthoritySourceEvidenceRepository sources) { + return new AccountRepository(dsl, sources); + } + + @Bean + AccountJwtSignerDesiredStateRepository signers(DSLContext dsl) { + return new AccountJwtSignerDesiredStateRepository(dsl); + } + + @Bean + AccountJwtJwksPublicationRepository publications( + DSLContext dsl, AccountJwtSignerDesiredStateRepository signers) { + return new AccountJwtJwksPublicationRepository(dsl, signers); + } + + @Bean + AccountServiceImpl primaryCredentials() { + return mock(AccountServiceImpl.class); + } + + @Bean(name = "transactionManager") + PlatformTransactionManager transactions() { + return mock(PlatformTransactionManager.class); + } + + @Bean + AccountJwtSignerMaterializerTrustBinding materializerTrust() { + var trust = mock(AccountJwtSignerMaterializerTrustBinding.class); + when(trust.current()) + .thenReturn( + Optional.of( + AccountGameplayLoginProtectedSourcesConfigurationTest.materializerBinding())); + return trust; + } + + @Bean + AccountResponseEnvelopeCryptography accountResponseEnvelopeCryptography() { + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring("/not-read-by-configuration-test/response")); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPublicJwksReadWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPublicJwksReadWorkloadGuardTest.java new file mode 100644 index 0000000000..1a3279918a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPublicJwksReadWorkloadGuardTest.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Context; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class AccountPublicJwksReadWorkloadGuardTest { + @AfterEach + void clear() { + SessionContext.clear(); + } + + @Test + void exactPeerRequiresBothCurrentProtectedBindingsAndNoApplicationAuthority() { + var guard = guard("test", "cluster-a"); + assertThatThrownBy(guard::requireCaller) + .isInstanceOf(AccountPublicJwksReadWorkloadGuard.ReadDeniedException.class); + for (String peer : + List.of( + "spiffe://firemud/ns/other/sa/game-session-service", + "spiffe://firemud/ns/test/sa/game-design-service")) { + withPeer( + peer, + () -> + assertThatThrownBy(guard::requireCaller) + .isInstanceOf(AccountPublicJwksReadWorkloadGuard.ReadDeniedException.class)); + } + withPeer( + "spiffe://firemud/ns/test/sa/game-session-service", + () -> { + assertThat(guard.requireCaller().materializer()) + .isEqualTo( + AccountGameplayLoginProtectedSourcesConfigurationTest.materializerBinding()); + assertThatThrownBy(guard("test", "wrong-cluster")::requireCaller) + .isInstanceOf(AccountPublicJwksReadWorkloadGuard.ReadDeniedException.class); + assertThatThrownBy(guard("other", "cluster-a")::requireCaller) + .isInstanceOf(AccountPublicJwksReadWorkloadGuard.ReadDeniedException.class); + var withdrawn = + new AccountPublicJwksReadWorkloadGuard( + Optional::empty, + () -> + AccountGameplayLoginProtectedSourcesConfigurationTest.apiBinding( + "test", "cluster-a"), + "test"); + assertThatThrownBy(withdrawn::requireCaller) + .isInstanceOf(AccountPublicJwksReadWorkloadGuard.ReadDeniedException.class); + SessionContext.setContext("account", List.of(), Map.of()); + assertThatThrownBy(guard::requireCaller) + .isInstanceOf(AccountPublicJwksReadWorkloadGuard.ReadDeniedException.class); + }); + } + + @Test + void sourceMustCorrespondToActualApiAndMaterializerIdentity() { + withPeer( + "spiffe://firemud/ns/test/sa/game-session-service", + () -> { + var caller = guard("test", "cluster-a").requireCaller(); + var api = caller.api(); + var binding = caller.materializer(); + var pin = + new SourceIdentity( + binding.environmentId(), + binding.clusterId(), + binding.expectedClusterIncarnationUid(), + binding.namespace(), + binding.expectedNamespaceUid(), + "33333333-3333-4333-8333-333333333333", + api.configRevision(), + api.apiServer().toString(), + api.servingCaSha256()); + caller.requireSource(pin); + assertThatThrownBy(() -> caller.requireSource(null)) + .isExactlyInstanceOf(InvalidJwksException.class); + for (SourceIdentity changed : + List.of( + new SourceIdentity( + pin.environmentId(), + pin.clusterId(), + pin.clusterIncarnationUid(), + pin.namespace(), + pin.namespaceUid(), + pin.configMapUid(), + "different-api-revision", + pin.apiServerOrigin(), + pin.servingCaSha256()), + new SourceIdentity( + pin.environmentId(), + pin.clusterId(), + pin.clusterIncarnationUid(), + pin.namespace(), + pin.namespaceUid(), + pin.configMapUid(), + pin.bindingRevision(), + "https://different-api.test:6443", + pin.servingCaSha256()))) { + assertThatThrownBy(() -> caller.requireSource(changed)) + .isExactlyInstanceOf(InvalidJwksException.class); + } + }); + } + + private static AccountPublicJwksReadWorkloadGuard guard(String namespace, String cluster) { + return new AccountPublicJwksReadWorkloadGuard( + () -> + Optional.of( + AccountGameplayLoginProtectedSourcesConfigurationTest.materializerBinding()), + () -> AccountGameplayLoginProtectedSourcesConfigurationTest.apiBinding(namespace, cluster), + "test"); + } + + private static void withPeer(String uri, Runnable action) { + Context context = + Context.ROOT.withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + Context previous = context.attach(); + try { + action.run(); + } finally { + context.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPublicJwksSourceConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPublicJwksSourceConfigurationTest.java new file mode 100644 index 0000000000..0dc0547011 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPublicJwksSourceConfigurationTest.java @@ -0,0 +1,125 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.Optional; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountPublicJwksReadGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountPublicJwksReadService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.stereotype.Component; +import org.springframework.transaction.PlatformTransactionManager; + +class AccountPublicJwksSourceConfigurationTest { + private final ApplicationContextRunner context = + new ApplicationContextRunner() + .withUserConfiguration( + AccountPublicJwksSourceConfiguration.class, + AccountPublicJwksReadGrpcService.class, + AdditionalSelectedConsumer.class); + + @Test + void noSourceOrReceiverIsRegisteredByDefault() { + context.run( + ctx -> { + assertThat(ctx).hasNotFailed(); + assertThat(ctx).doesNotHaveBean(AccountProtectedJwksSourceConfiguration.class); + assertThat(ctx).doesNotHaveBean(AccountJwtJwksApiBinding.class); + assertThat(ctx).doesNotHaveBean(AccountJwtJwksConfigMapClient.class); + assertThat(ctx).doesNotHaveBean(AccountJwtJwksTrustedSource.class); + assertThat( + AnnotationUtils.findAnnotation( + AccountProtectedJwksSourceConfiguration.class, Component.class)) + .isNull(); + assertThat(ctx).doesNotHaveBean(AccountPublicJwksReadGrpcService.class); + }); + } + + @Test + void explicitReadRequiresRealProtectedSources() { + context + .withPropertyValues("firemud.account.public-jwks-read.enabled=true") + .run(ctx -> assertThat(ctx).hasFailed()); + } + + @ParameterizedTest + @ValueSource(strings = {"login", "read", "additional", "all"}) + void selectedConsumersImportExactlyOneProtectedGraphWithoutSelectingEachOther(String selection) { + var trust = mock(AccountJwtSignerMaterializerTrustBinding.class); + var signers = mock(AccountJwtSignerDesiredStateRepository.class); + var publications = mock(AccountJwtJwksPublicationRepository.class); + when(trust.current()) + .thenReturn( + Optional.of( + AccountGameplayLoginProtectedSourcesConfigurationTest.materializerBinding())); + try (var construction = + mockConstruction( + AccountJwtJwksApiBinding.class, + (api, ignored) -> + when(api.current()) + .thenReturn( + AccountGameplayLoginProtectedSourcesConfigurationTest.apiBinding( + "test", "cluster-a")))) { + context + .withPropertyValues( + "firemud.account.gameplay-login.enabled=" + + (selection.equals("login") || selection.equals("all")), + "firemud.account.public-jwks-read.enabled=" + + (selection.equals("read") || selection.equals("all")), + "test.additional-protected-jwks-consumer.enabled=" + + (selection.equals("additional") || selection.equals("all")), + "firemud.grpc.workload-namespace=test", + "firemud.account.public-jwks.api-binding-path=" + + AccountGameplayLoginProtectedSourcesConfigurationTest.API_PATH) + .withBean(AccountJwtSignerMaterializerTrustBinding.class, () -> trust) + .withBean(AccountJwtSignerDesiredStateRepository.class, () -> signers) + .withBean(AccountJwtJwksPublicationRepository.class, () -> publications) + .withBean( + "transactionManager", + PlatformTransactionManager.class, + () -> mock(PlatformTransactionManager.class)) + .run( + ctx -> { + assertThat(ctx).hasNotFailed(); + assertThat(ctx).hasSingleBean(AccountProtectedJwksSourceConfiguration.class); + assertThat(ctx).hasSingleBean(AccountJwtJwksApiBinding.class); + assertThat(ctx).hasSingleBean(AccountJwtJwksConfigMapClient.class); + assertThat(ctx).hasSingleBean(AccountJwtJwksTrustedSource.class); + if (selection.equals("read") || selection.equals("all")) { + assertThat(ctx).hasSingleBean(AccountPublicJwksReadService.class); + assertThat(ctx).hasSingleBean(AccountPublicJwksReadGrpcService.class); + } else { + assertThat(ctx).doesNotHaveBean(AccountPublicJwksReadService.class); + assertThat(ctx).doesNotHaveBean(AccountPublicJwksReadGrpcService.class); + } + assertThat(ctx).doesNotHaveBean(AccountGameplayDelegationRedisClient.class); + assertThat(construction.constructed()).hasSize(1); + verifyNoInteractions(signers, publications); + }); + } + } + + /** Models another independently selected owner, without importing its business graph. */ + @Configuration(proxyBeanMethods = false) + @ConditionalOnProperty( + prefix = "test.additional-protected-jwks-consumer", + name = "enabled", + havingValue = "true") + @Import(AccountProtectedJwksSourceConfiguration.class) + static class AdditionalSelectedConsumer {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java index 6561bbb11d..f6e26dcfbe 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java @@ -74,10 +74,51 @@ void clearTransactionState() { TransactionSynchronizationManager.clear(); } + @Test + void activeReceiptDigestRetainsFrozenGrammarAndWriterSuppliedObservation() { + var promotion = mock(AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence.class); + when(promotion.operationId()) + .thenReturn(UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + when(promotion.requestDigest()).thenReturn("1".repeat(64)); + when(promotion.generationOperationId()) + .thenReturn(UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); + when(promotion.generationOperationDigest()).thenReturn("2".repeat(64)); + when(promotion.generationReceiptDigest()).thenReturn("3".repeat(64)); + // Different owner fields must not replace the writer's explicitly supplied observation. + when(promotion.publicConfigMapUid()).thenReturn("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + when(promotion.expectedPublicResourceVersion()).thenReturn("owner-prior"); + when(promotion.activeJwksObservedResourceVersion()) + .thenReturn(java.util.Optional.of("owner-observed")); + String uid = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; + String original = + AccountJwtSignerDesiredStateRepository.activeJwksPromotionReceiptDigest( + promotion, uid, "opaque-prior", "opaque-observed", "4".repeat(64)); + // Frozen pre-extraction RFC 8785 preimage hash, independent of the production helper. + assertThat(original) + .isEqualTo("c7b924b789f0c7f140b12074c02862ec3056969b64b242174ac039bb27437251"); + assertThat( + AccountJwtSignerDesiredStateRepository.activeJwksPromotionReceiptDigest( + promotion, + "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", + "opaque-prior", + "opaque-observed", + "4".repeat(64))) + .isNotEqualTo(original); + assertThat( + AccountJwtSignerDesiredStateRepository.activeJwksPromotionReceiptDigest( + promotion, uid, "different-prior", "opaque-observed", "4".repeat(64))) + .isNotEqualTo(original); + assertThat( + AccountJwtSignerDesiredStateRepository.activeJwksPromotionReceiptDigest( + promotion, uid, "opaque-prior", "different-observed", "4".repeat(64))) + .isNotEqualTo(original); + } + @Test void durableGenerationEntryPointsRequireAnAccountTransaction() throws Exception { assertMandatory("initialize", Binding.class, EnrollmentIdentity.class); assertMandatory("read", Binding.class); + assertMandatoryWritable("readLockedEnrollmentState", Binding.class); assertMandatory("ensureCurrentGenerationRequest", Binding.class, TrustFence.class); assertMandatoryWritable( "abortUnpreparedGeneration", Binding.class, TrustFence.class, GenerationResult.class); @@ -101,6 +142,8 @@ void durableGenerationEntryPointsRequireAnAccountTransaction() throws Exception String.class, String.class); assertMandatoryWritable("readPreparedGenerationForRecovery", Binding.class, TrustFence.class); + assertMandatoryWritable( + "readPreparedPrivatePromotionReceiptForRecovery", Binding.class, TrustFence.class); assertMandatoryWritable( "readAndMarkPreparedPromotionDispatched", Binding.class, TrustFence.class); assertMandatoryWritable( @@ -147,9 +190,16 @@ void lockedPromotionReadsRejectReadOnlyTransactionsBeforeSql() { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); try { + assertThatThrownBy(() -> repository.readLockedEnrollmentState(BINDING)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); assertThatThrownBy(() -> repository.readPreparedGenerationForRecovery(BINDING, TRUST)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Writable Account transaction"); + assertThatThrownBy( + () -> repository.readPreparedPrivatePromotionReceiptForRecovery(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); assertThatThrownBy(() -> repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Writable Account transaction"); @@ -432,7 +482,29 @@ void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() th String exactPrivateReceiptDigest = (String) conversation.preparedPromotionValues.get("private_promotion_receipt_digest"); + var exactPrivateRecovery = + inWritableTransaction( + () -> + conversation.repository.readPreparedPrivatePromotionReceiptForRecovery( + BINDING, TRUST)); + assertThat(exactPrivateRecovery.promotionOperationId()) + .isEqualTo(conversation.preparedPromotionId); + assertThat(exactPrivateRecovery.generationOperationId()).isEqualTo(result.operationId()); + assertThat(exactPrivateRecovery.receiptDigest()).isEqualTo(exactPrivateReceiptDigest); + int statementsBeforeRecovery = conversation.executedStatements.size(); conversation.preparedPromotionValues.put("private_promotion_receipt_digest", "0".repeat(64)); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.readPreparedPrivatePromotionReceiptForRecovery( + BINDING, TRUST))) + .isExactlyInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) + .hasMessageContaining("private promotion receipt digest is invalid"); + assertThat( + conversation.executedStatements.subList( + statementsBeforeRecovery, conversation.executedStatements.size())) + .noneMatch(sql -> sql.contains("UPDATE ") || sql.contains("INSERT ")); assertThatThrownBy( () -> inWritableTransaction( @@ -463,6 +535,30 @@ void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() th .doesNotContain("plan.expires_at_epoch_seconds", "CURRENT_TIMESTAMP", "clock_timestamp"); } + @Test + void lockedEnrollmentRecoveryReadPinsOwnerRowWithoutChangingAnyEvidence() { + DSLContext dsl = mock(DSLContext.class); + var repository = new AccountJwtSignerDesiredStateRepository(dsl); + Record enrolledRow = stateRow(BINDING, 1, null, null, null, null, null); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(enrolledRow, null); + var enrolled = + inWritableTransaction(() -> repository.readLockedEnrollmentState(BINDING)).orElseThrow(); + assertThat(enrolled.enrollmentIdentity()).contains(ENROLLMENT); + assertThat(enrolled.recordVersion()).isEqualTo(1); + assertThat(inWritableTransaction(() -> repository.readLockedEnrollmentState(BINDING))) + .isEmpty(); + ArgumentCaptor queries = ArgumentCaptor.forClass(String.class); + verify(dsl, times(2)).fetchOne(queries.capture(), any(Object[].class)); + assertThat(queries.getAllValues()) + .allSatisfy( + sql -> { + assertThat(sql) + .contains("FROM account_jwt_signer_desired_states") + .endsWith(" FOR UPDATE"); + }); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + @Test void accountCreatesAndReplaysOnlyItsOwnBoundGenerationRequest() { Conversation conversation = new Conversation(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java index 7069c36ceb..95bfbca50d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java @@ -96,6 +96,38 @@ void oversizedConfigMapResponseIsRejectedAtTheBound() { assertThat(api.patchCount).isZero(); } + @org.junit.jupiter.api.Test + void temporaryPrincipalReviewResponsesDenyTheReadWithoutRejectingCustody() { + for (int status : List.of(408, 429, 500, 502, 503, 504)) { + FakeKubernetesApi api = new FakeKubernetesApi(); + api.principalReviewStatus = status; + AccountJwtJwksConfigMapClient client = client(api); + + assertThatThrownBy(client::observe) + .isInstanceOfSatisfying( + AccountJwtJwksConfigMapClient.ApiFailureException.class, + failure -> assertThat(failure.statusCode()).isEqualTo(status)); + assertThat(api.calls).containsExactly(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL); + assertThat(api.patchCount).isZero(); + + api.principalReviewStatus = 201; + assertThat(client.observe().uid()).isEqualTo(CONFIG_MAP_UID); + } + } + + @org.junit.jupiter.api.Test + void otherUnsuccessfulPrincipalReviewsRemainCustodyRejections() { + for (int status : List.of(204, 302, 400, 401, 403, 404, 409, 600)) { + FakeKubernetesApi api = new FakeKubernetesApi(); + api.principalReviewStatus = status; + + assertThatThrownBy(() -> client(api).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).containsExactly(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL); + assertThat(api.patchCount).isZero(); + } + } + @org.junit.jupiter.api.Test void rejectsWrongAccountPrincipalAndEitherNamespaceIncarnationBeforeConfigMapRead() { FakeKubernetesApi wrongPrincipal = new FakeKubernetesApi(); @@ -437,6 +469,7 @@ private static final class FakeKubernetesApi { "unrelated.txt", "retain")); private String authenticatedUsername = API_USERNAME; + private int principalReviewStatus = 201; private String kubeSystemUid = KUBE_SYSTEM_UID; private String targetNamespaceUid = TARGET_NAMESPACE_UID; private String configMapUid = CONFIG_MAP_UID; @@ -478,7 +511,7 @@ private ApiResponse send(ApiCall call, byte[] body) { switch (call) { case REVIEW_AUTHENTICATED_PRINCIPAL -> response( - 201, + principalReviewStatus, "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\"," + "\"status\":{\"userInfo\":{\"username\":\"" + authenticatedUsername diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java index 3e84bf697e..b1e7cb41eb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java @@ -5,21 +5,42 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.net.URI; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.security.MessageDigest; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.config.AccountPublicJwksReadWorkloadGuard; import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.MountObservation; import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PromotionPublicationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; @@ -30,21 +51,28 @@ import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.impl.AccountPublicJwksReadGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountPublicJwksReadService; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec; import org.junit.jupiter.api.Test; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ObjectNode; class AccountJwtJwksTrustedSourceTest { private static final String ENVIRONMENT = "test"; @@ -62,13 +90,86 @@ class AccountJwtJwksTrustedSourceTest { private static final String GENERATION_OPERATION_DIGEST = "1".repeat(64); private static final String GENERATION_REQUEST_DIGEST = "2".repeat(64); private static final String GENERATION_RECEIPT_DIGEST = "3".repeat(64); - private static final String JWK_1 = - "{\"alg\":\"RS256\",\"e\":\"AQAB\",\"key_ops\":[\"verify\"],\"kid\":\"key_1\",\"kty\":\"RSA\",\"n\":\"AQID\",\"use\":\"sig\"}"; - private static final String JWK_2 = - "{\"alg\":\"RS256\",\"e\":\"AQAB\",\"key_ops\":[\"verify\"],\"kid\":\"key_2\",\"kty\":\"RSA\",\"n\":\"BAUG\",\"use\":\"sig\"}"; + private static final String JWK_1 = publicTestJwk("key_1"); + private static final String JWK_2 = publicTestJwk("key_2"); + private static final Map INITIAL_PRIOR_DATA = + Map.of("jwks.json", "{\"keys\":[]}", "operator.note", "retained"); private static final String JWKS_1 = "{\"keys\":[" + JWK_1 + "]}"; private static final String JWKS_1_AND_2 = "{\"keys\":[" + JWK_1 + "," + JWK_2 + "]}"; + @Test + void sameUidUnownedPublicKeyRemovalIsTerminalAndCannotRepopulateWarmCache() { + Fixture fixture = new Fixture(); + fixture.useCommittedState(); + var pin = fixture.source.sourceIdentity(); + var cache = + new net.firedevops.firemud.common.security.AccountPublicJwksCache( + fixture.source, + pin, + java.time.Clock.fixed( + java.time.Instant.parse("2026-11-10T00:00:00Z"), java.time.ZoneOffset.UTC), + java.time.Duration.ofSeconds(10)); + cache.refresh(); + assertThat(cache.keyFor("key_1")).isNotNull(); + assertThat(cache.keyFor("key_2")).isNotNull(); + var original = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1_AND_2, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + fixture.nextPublication.intent().generationMarkerJson())); + var pruned = new java.util.LinkedHashMap<>(original.data()); + pruned.put(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, "{\"keys\":[" + JWK_2 + "]}"); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "44", pruned)); + // Same UID and a valid retained key profile cannot replace exact Account owner evidence. + assertRejectedPublicRead(fixture); + assertThatThrownBy(cache::refresh) + .isInstanceOf( + net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException + .class); + for (String kid : List.of("key_1", "key_2")) { + assertThatThrownBy(() -> cache.keyFor(kid)) + .isInstanceOf( + net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException + .class); + } + when(fixture.configMapClient.observe()).thenReturn(original); + assertThat(fixture.source.currentPublicRead().jwksBytes()) + .containsExactly(JWKS_1_AND_2.getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(cache::refresh) + .isInstanceOf( + net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException + .class); + assertThatThrownBy(() -> cache.keyFor("key_1")) + .isInstanceOf( + net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException + .class); + } + + private static String publicTestJwk(String kid) { + try { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + var key = (java.security.interfaces.RSAPublicKey) generator.generateKeyPair().getPublic(); + byte[] modulus = key.getModulus().toByteArray(); + if (modulus[0] == 0) modulus = java.util.Arrays.copyOfRange(modulus, 1, modulus.length); + var encoder = java.util.Base64.getUrlEncoder().withoutPadding(); + return "{\"alg\":\"RS256\",\"e\":\"" + + encoder.encodeToString(key.getPublicExponent().toByteArray()) + + "\",\"key_ops\":[\"verify\"],\"kid\":\"" + + kid + + "\",\"kty\":\"RSA\",\"n\":\"" + + encoder.encodeToString(modulus) + + "\",\"use\":\"sig\"}"; + } catch (java.security.GeneralSecurityException failure) { + throw new ExceptionInInitializerError(failure); + } + } + @Test void derivesPinAndReturnsOnlyExactReceiptBackedPublicBytes() { Fixture fixture = new Fixture(); @@ -93,7 +194,8 @@ void derivesPinAndReturnsOnlyExactReceiptBackedPublicBytes() { } @Test - void allowsAbsentKeyOperationsOnlyForTrustedPublishedKeysAndRejectsOtherShapes() { + void allowsAbsentKeyOperationsOnlyForTrustedPublishedKeysAndRejectsOtherShapes() + throws Exception { String jwkWithoutKeyOps = JWK_1.replace("\"key_ops\":[\"verify\"],", ""); Fixture absentKeyOps = new Fixture("{\"keys\":[" + jwkWithoutKeyOps + "]}"); @@ -107,11 +209,14 @@ void allowsAbsentKeyOperationsOnlyForTrustedPublishedKeysAndRejectsOtherShapes() .getBytes(StandardCharsets.UTF_8)); assertThat(identity.configMapUid()).isEqualTo(CONFIG_MAP_UID); + var mapper = JsonMapper.builder().build(); + var missingModulus = (tools.jackson.databind.node.ObjectNode) mapper.readTree(JWK_1); + missingModulus.remove("n"); for (String malformedJwk : List.of( JWK_1.replace("\"use\":\"sig\"", "\"use\":\"sig\",\"unexpected\":true"), JWK_1.replace("\"use\":\"sig\"", "\"use\":\"sig\",\"d\":\"AQID\""), - JWK_1.replace("\"n\":\"AQID\",", ""), + mapper.writeValueAsString(missingModulus), JWK_1.replace("[\"verify\"]", "[\"verify\",\"sign\"]"))) { Fixture malformed = new Fixture("{\"keys\":[" + malformedJwk + "]}"); assertThatThrownBy(malformed.source::sourceIdentity) @@ -178,16 +283,32 @@ void requiresReceiptWhenCurrentPublicationExistsAlongsideCommittedSigner() { @Test void historicalKeyFingerprintRequiresTheCurrentOwnerProvedSetToRetainItsExactIdentity() { Fixture missingKey = new Fixture(); + SourceIdentity missingPin = missingKey.source.sourceIdentity(); missingKey.useCommittedState(); + assertThat(missingKey.source.load().sourceIdentity()).isEqualTo(missingPin); + assertThat(missingKey.source.load().jwksBytes()) + .containsExactly(JWKS_1_AND_2.getBytes(StandardCharsets.UTF_8)); missingKey.replaceNextJwks("{\"keys\":[" + JWK_2 + "]}"); assertThatThrownBy(missingKey.source::load) .isInstanceOf(IllegalStateException.class) .hasMessage("Account trusted public JWKS source was rejected"); Fixture substitutedKey = new Fixture(); + SourceIdentity substitutedPin = substitutedKey.source.sourceIdentity(); substitutedKey.useCommittedState(); - String substitutedJwk = JWK_1.replace("\"n\":\"AQID\"", "\"n\":\"BAUG\""); - substitutedKey.replaceNextJwks("{\"keys\":[" + substitutedJwk + "," + JWK_2 + "]}"); + assertThat(substitutedKey.source.load().sourceIdentity()).isEqualTo(substitutedPin); + assertThat(substitutedKey.source.load().jwksBytes()) + .containsExactly(JWKS_1_AND_2.getBytes(StandardCharsets.UTF_8)); + String substitutedJwk = publicTestJwk("key_1"); + assertThat(substitutedJwk).isNotEqualTo(JWK_1); + assertThat(fingerprint(substitutedJwk)).isNotEqualTo(fingerprint(JWK_1)); + var json = JsonMapper.builder().build(); + assertThat(json.readTree(substitutedJwk).path("kid").asText()).isEqualTo("key_1"); + assertThat(json.readTree(substitutedJwk).path("n").asText()) + .isNotEqualTo(json.readTree(JWK_1).path("n").asText()); + String substitutedSet = "{\"keys\":[" + substitutedJwk + "," + JWK_2 + "]}"; + assertThat(substitutedSet).isNotEqualTo(JWKS_1_AND_2); + substitutedKey.replaceNextJwks(substitutedSet); assertThatThrownBy(substitutedKey.source::load) .isInstanceOf(IllegalStateException.class) .hasMessage("Account trusted public JWKS source was rejected"); @@ -258,6 +379,145 @@ void treatsUnreceiptedOrAmbiguousOwnerPublicationAsUnavailableNotAsAKeySet() { verify(fixture.configMapClient, never()).observe(); } + @Test + void realPrincipalReviewOutageRemainsRetryableThroughCurrentReadGrpc() throws Exception { + Fixture fixture = new Fixture(); + var parsed = + new ParsedBinding( + "api-r1", + ENVIRONMENT, + CLUSTER, + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("unused-ca.pem"), + API_CA_DIGEST, + Path.of("unused-token"), + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + fixture.apiIdentity.expectedApiUsername(), + API_BINDING_DIGEST); + var api = mock(AccountJwtJwksApiBinding.class); + var operation = mock(AccountJwtJwksApiBinding.ApiOperation.class); + when(api.beginOperation()).thenReturn(operation); + when(operation.binding()).thenReturn(parsed); + var reviewStatus = new AtomicInteger(503); + var json = JsonMapper.builder().build(); + when(operation.send(any(), any())) + .thenAnswer( + invocation -> { + ApiCall call = invocation.getArgument(0); + int status = + call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL ? reviewStatus.get() : 200; + Map body = + switch (call) { + case REVIEW_AUTHENTICATED_PRINCIPAL -> + status == 201 + ? Map.of( + "apiVersion", "authentication.k8s.io/v1", + "kind", "SelfSubjectReview", + "status", + Map.of( + "userInfo", + Map.of("username", parsed.expectedApiUsername()))) + : Map.of(); + case READ_KUBE_SYSTEM_NAMESPACE, READ_TARGET_NAMESPACE -> + Map.of( + "apiVersion", + "v1", + "kind", + "Namespace", + "metadata", + Map.of( + "name", + call == ApiCall.READ_KUBE_SYSTEM_NAMESPACE + ? "kube-system" + : NAMESPACE, + "uid", + call == ApiCall.READ_KUBE_SYSTEM_NAMESPACE + ? CLUSTER_UID + : NAMESPACE_UID), + "status", + Map.of("phase", "Active")); + case READ_JWKS_CONFIG_MAP -> + Map.of( + "apiVersion", + "v1", + "kind", + "ConfigMap", + "metadata", + Map.of( + "name", + AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME, + "namespace", + NAMESPACE, + "uid", + CONFIG_MAP_UID, + "resourceVersion", + fixture.snapshot.resourceVersion()), + "data", + fixture.snapshot.data()); + default -> throw new AssertionError("Unexpected public-read API call"); + }; + return new ApiResponse(status, json.writeValueAsBytes(body)); + }); + var source = + new AccountJwtJwksTrustedSource( + new AccountJwtJwksConfigMapClient(api), + fixture.materializerTrust, + fixture.desiredStateRepository, + fixture.publicationRepository, + fixture.transactionManager); + var guard = mock(AccountPublicJwksReadWorkloadGuard.class); + when(guard.requireCaller()) + .thenReturn( + new AccountPublicJwksReadWorkloadGuard.ProtectedCaller(fixture.binding, parsed)); + var receiver = + new AccountPublicJwksReadGrpcService(new AccountPublicJwksReadService(source, guard)); + + // First-pin and later load outages both recover only after another complete protected read. + for (int status : List.of(408, 201, 429, 201, 503, 201, 401, 200)) { + reviewStatus.set(status); + var response = new AtomicReference(); + var failure = new AtomicReference(); + var completed = new AtomicInteger(); + receiver.getCurrentPublicJwks( + AccountPublicJwksReadCodec.request(), + new StreamObserver<>() { + @Override + public void onNext(GetCurrentAccountPublicJwksResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() { + completed.incrementAndGet(); + } + }); + if (status == 201) { + assertThat(failure.get()).isNull(); + assertThat(completed.get()).isEqualTo(1); + PublicJwksSnapshot snapshot = AccountPublicJwksReadCodec.snapshot(response.get()); + assertThat(snapshot.sourceIdentity()).isEqualTo(source.sourceIdentity()); + assertThat(snapshot.jwksBytes()).containsExactly(JWKS_1.getBytes(StandardCharsets.UTF_8)); + } else { + assertThat(response.get()).isNull(); + assertThat(completed.get()).isZero(); + assertThat(failure.get()).isNotNull(); + assertThat(Status.fromThrowable(failure.get()).getCode()) + .isEqualTo( + status == 401 || status == 200 + ? Status.Code.FAILED_PRECONDITION + : Status.Code.UNAVAILABLE); + } + } + } + @Test void treatsDatabaseAndTransactionFailuresAsRetryableSourceUnavailability() { List failures = @@ -322,6 +582,589 @@ void rejectsReadbackThatDoesNotMatchReceiptResourceVersionOrMarker() { .hasMessage("Account trusted public JWKS source was rejected"); } + @Test + void publicMovingOwnerBracketRequalifiesWhileOrdinaryReadRemainsTemporary() { + for (boolean publicRead : new boolean[] {false, true}) { + Fixture fixture = new Fixture(); + var intent = fixture.publication.intent(); + // Two individually valid owner projections differ around the intervening live read. + var after = + new PublicationEvidence( + intent, Optional.of(PublicationReceipt.create(intent, "43")), Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(fixture.publication), Optional.of(after)); + when(fixture.configMapClient.observe()) + .thenReturn( + fixture.snapshot, + new ConfigMapSnapshot(CONFIG_MAP_UID, "43", fixture.snapshot.data())); + if (publicRead) { + assertThat(fixture.source.currentPublicRead().jwksBytes()) + .isEqualTo(JWKS_1.getBytes(StandardCharsets.UTF_8)); + } else { + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + } + verify(fixture.configMapClient, times(publicRead ? 2 : 1)).observe(); + } + } + + @Test + void publicReadRequalifiesPreparedCommitAndBothMissingReceiptCompletions() { + for (String movement : List.of("commit", "publication-receipt", "active-receipt")) { + Fixture fixture = new Fixture(); + if (movement.equals("publication-receipt")) { + var pending = + new PublicationEvidence( + fixture.publication.intent(), Optional.empty(), Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + fixture.accountBinding, fixture.trustFence)) + .thenReturn(Optional.of(pending), Optional.of(fixture.publication)); + } else { + fixture.usePreparedState(true, false); + var beforeState = + fixture.desiredStateRepository.readEnrollmentState(fixture.accountBinding); + var before = + fixture.desiredStateRepository.readPreparedGenerationForRecovery( + fixture.accountBinding, fixture.trustFence); + if (movement.equals("commit")) { + fixture.useStableCommittedState(); + var afterState = + fixture.desiredStateRepository.readEnrollmentState(fixture.accountBinding); + when(fixture.desiredStateRepository.readLockedEnrollmentState(fixture.accountBinding)) + .thenReturn(beforeState, afterState); + } else { + fixture.usePreparedState(true, true); + var after = + fixture.desiredStateRepository.readPreparedGenerationForRecovery( + fixture.accountBinding, fixture.trustFence); + when(fixture.desiredStateRepository.readPreparedGenerationForRecovery( + fixture.accountBinding, fixture.trustFence)) + .thenReturn(before, after); + } + } + var result = fixture.source.currentPublicRead(); + assertThat(result.sourceIdentity().configMapUid()).isEqualTo(CONFIG_MAP_UID); + assertThat(result.preparedDeny()).isEqualTo(movement.equals("active-receipt")); + assertThat(result.committedRecoveryEligible()).isEqualTo(movement.equals("commit")); + assertThat(result.jwksBytes()) + .isEqualTo( + movement.equals("active-receipt") + ? new byte[0] + : JWKS_1.getBytes(StandardCharsets.UTF_8)); + verify(fixture.configMapClient, times(2)).observe(); + } + } + + @Test + void repeatedOwnerMovementIsTerminalAfterExactlyThreeCompleteTrials() { + Fixture fixture = new Fixture(); + var intent = fixture.publication.intent(); + var e42 = fixture.publication; + var e43 = + new PublicationEvidence( + intent, Optional.of(PublicationReceipt.create(intent, "43")), Optional.empty()); + var e44 = + new PublicationEvidence( + intent, Optional.of(PublicationReceipt.create(intent, "44")), Optional.empty()); + var e45 = + new PublicationEvidence( + intent, Optional.of(PublicationReceipt.create(intent, "45")), Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + fixture.accountBinding, fixture.trustFence)) + .thenReturn( + Optional.of(e42), + Optional.of(e43), + Optional.of(e43), + Optional.of(e44), + Optional.of(e44), + Optional.of(e45)); + when(fixture.configMapClient.observe()) + .thenReturn( + fixture.snapshot, + new ConfigMapSnapshot(CONFIG_MAP_UID, "43", fixture.snapshot.data()), + new ConfigMapSnapshot(CONFIG_MAP_UID, "44", fixture.snapshot.data())); + assertRejectedPublicRead(fixture); + verify(fixture.configMapClient, times(3)).observe(); + verify(fixture.desiredStateRepository, times(6)) + .readLockedEnrollmentState(fixture.accountBinding); + } + + @Test + void movingOwnerNeverLaundersUidTrustMarkerOrOwnedByteTamper() { + for (String tamper : List.of("uid", "trust", "marker", "jwks")) { + Fixture fixture = new Fixture(); + var after = + new PublicationEvidence( + fixture.publication.intent(), + Optional.of(PublicationReceipt.create(fixture.publication.intent(), "43")), + Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + fixture.accountBinding, fixture.trustFence)) + .thenReturn(Optional.of(fixture.publication), Optional.of(after)); + when(fixture.configMapClient.observe()) + .thenAnswer( + invocation -> { + if (tamper.equals("trust")) + when(fixture.materializerTrust.current()) + .thenReturn(Optional.of(binding(CLUSTER_UID, NAMESPACE_UID, "other-trust"))); + Map data = new LinkedHashMap<>(fixture.snapshot.data()); + if (tamper.equals("marker")) + data.put("jwt-generation.json", fixture.initialMarker + " "); + if (tamper.equals("jwks")) data.put("jwks.json", "{\"keys\":[]}"); + return new ConfigMapSnapshot( + tamper.equals("uid") ? "44444444-4444-4444-8444-444444444444" : CONFIG_MAP_UID, + "42", + data); + }); + assertRejectedPublicRead(fixture); + verify(fixture.configMapClient).observe(); + } + } + + @Test + void movedOwnerCannotChangeTheAnchoredUidEvenWhenPriorLiveBytesStillQualify() { + Fixture fixture = new Fixture(); + AtomicInteger reads = new AtomicInteger(); + when(fixture.desiredStateRepository.readLockedEnrollmentState(fixture.accountBinding)) + .thenAnswer( + invocation -> { + if (reads.incrementAndGet() == 2) { + fixture.useStableCommittedState(); + var committed = + fixture + .desiredStateRepository + .readCurrentCommittedSigner( + fixture.accountBinding, + fixture.trustFence, + API_BINDING_DIGEST, + "api-r1") + .orElseThrow(); + when(committed.promotion().publicConfigMapUid()) + .thenReturn("44444444-4444-4444-8444-444444444444"); + when(committed.publicReceipt().configMapUid()) + .thenReturn("44444444-4444-4444-8444-444444444444"); + } + return fixture.desiredStateRepository.readEnrollmentState(fixture.accountBinding); + }); + assertRejectedPublicRead(fixture); + verify(fixture.configMapClient).observe(); + assertThat(reads.get()).isEqualTo(2); + } + + @Test + void movementRequalificationKeepsInitialPinAndCapturedCancellation() throws Exception { + Fixture fixture = new Fixture(); + var after = + new PublicationEvidence( + fixture.publication.intent(), + Optional.of(PublicationReceipt.create(fixture.publication.intent(), "43")), + Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + fixture.accountBinding, fixture.trustFence)) + .thenReturn(Optional.of(fixture.publication), Optional.of(after)); + when(fixture.configMapClient.observe()) + .thenReturn( + fixture.snapshot, + new ConfigMapSnapshot( + "44444444-4444-4444-8444-444444444444", "43", fixture.snapshot.data())); + assertRejectedPublicRead(fixture); + verify(fixture.configMapClient, times(2)).observe(); + + Fixture cancelled = new Fixture(); + try (var context = Context.current().withCancellation()) { + when(cancelled.configMapClient.observe()) + .thenAnswer( + invocation -> { + context.cancel(null); + return cancelled.snapshot; + }); + assertThatThrownBy(() -> context.call(cancelled.source::currentPublicRead)) + .isInstanceOf(SourceUnavailableException.class); + verify(cancelled.configMapClient).observe(); + } + } + + @Test + void movementThenCoherentPendingPrepublicationRemainsUnavailableWithoutInstallingAPin() { + for (boolean additive : List.of(false, true)) { + Fixture fixture = new Fixture(); + if (additive) fixture.useCommittedState(); + PublicationEvidence complete = additive ? fixture.nextPublication : fixture.publication; + var pending = new PublicationEvidence(complete.intent(), Optional.empty(), Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + fixture.accountBinding, fixture.trustFence)) + .thenReturn( + Optional.of(complete), + Optional.of(pending), + Optional.of(pending), + Optional.of(pending)); + + assertThatThrownBy(fixture.source::currentPublicRead) + .isExactlyInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + assertThatThrownBy(fixture.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, times(2)).observe(); + verify(fixture.publicationRepository, times(4)) + .readCurrentPublication(fixture.accountBinding, fixture.trustFence); + } + } + + @Test + void movementThenCoherentVersionOnlyDriftRemainsUnavailableWithoutInstallingAPin() { + Fixture fixture = new Fixture(); + var pending = + new PublicationEvidence(fixture.publication.intent(), Optional.empty(), Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + fixture.accountBinding, fixture.trustFence)) + .thenReturn(Optional.of(pending), Optional.of(fixture.publication)); + when(fixture.configMapClient.observe()) + .thenReturn( + fixture.snapshot, new ConfigMapSnapshot(CONFIG_MAP_UID, "43", fixture.snapshot.data())); + + assertThatThrownBy(fixture.source::currentPublicRead) + .isExactlyInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + assertThatThrownBy(fixture.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, times(2)).observe(); + verify(fixture.publicationRepository, times(4)) + .readCurrentPublication(fixture.accountBinding, fixture.trustFence); + } + + @Test + void movementWithVersionOnlyReadbackRequiresAFreshCoherentTrial() { + Fixture fixture = new Fixture(); + var later = + new PublicationEvidence( + fixture.publication.intent(), + Optional.of(PublicationReceipt.create(fixture.publication.intent(), "44")), + Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + fixture.accountBinding, fixture.trustFence)) + .thenReturn(Optional.of(fixture.publication), Optional.of(later)); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", fixture.snapshot.data())) + .thenAnswer( + invocation -> { + assertThatThrownBy(fixture.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + return new ConfigMapSnapshot(CONFIG_MAP_UID, "44", fixture.snapshot.data()); + }); + + var result = fixture.source.currentPublicRead(); + assertThat(result.sourceIdentity().configMapUid()).isEqualTo(CONFIG_MAP_UID); + assertThat(result.preparedDeny()).isFalse(); + assertThat(result.committedRecoveryEligible()).isFalse(); + assertThat(result.jwksBytes()).containsExactly(JWKS_1.getBytes(StandardCharsets.UTF_8)); + verify(fixture.configMapClient, times(2)).observe(); + verify(fixture.publicationRepository, times(4)) + .readCurrentPublication(fixture.accountBinding, fixture.trustFence); + } + + @Test + void movementThenApiMissingResourceOrSqlOutageIsTerminalWithoutInstallingAPin() { + for (boolean afterMovement : List.of(false, true)) { + for (String failure : List.of("api503", "missing-resource", "sql")) { + Fixture fixture = new Fixture(); + var pending = + new PublicationEvidence( + fixture.publication.intent(), Optional.empty(), Optional.empty()); + if (afterMovement) { + var publication = + when(fixture.publicationRepository.readCurrentPublication( + fixture.accountBinding, fixture.trustFence)) + .thenReturn(Optional.of(pending), Optional.of(fixture.publication)); + if (failure.equals("sql")) + publication.thenThrow( + new DataAccessResourceFailureException("controlled retry SQL outage")); + } else if (failure.equals("sql")) { + when(fixture.publicationRepository.readCurrentPublication( + fixture.accountBinding, fixture.trustFence)) + .thenThrow(new DataAccessResourceFailureException("controlled initial SQL outage")); + } + if (!failure.equals("sql")) { + RuntimeException outage = + failure.equals("api503") + ? new AccountJwtJwksConfigMapClient.ApiFailureException(503) + : new AccountJwtJwksConfigMapClient.ResourceMissingException(); + if (afterMovement) { + when(fixture.configMapClient.observe()).thenReturn(fixture.snapshot).thenThrow(outage); + } else { + when(fixture.configMapClient.observe()).thenThrow(outage); + } + } + if (afterMovement) { + assertRejectedPublicRead(fixture); + } else { + assertThatThrownBy(fixture.source::currentPublicRead) + .isExactlyInstanceOf(SourceUnavailableException.class); + } + assertThatThrownBy(fixture.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + int observations = + failure.equals("sql") ? (afterMovement ? 1 : 0) : (afterMovement ? 2 : 1); + verify(fixture.configMapClient, times(observations)).observe(); + } + } + } + + @Test + void movementThenIncomingCancellationOrDeadlineIsTerminalUnderTheOriginalContext() { + for (boolean afterMovement : List.of(false, true)) { + for (String failure : List.of("cancel", "deadline")) { + Fixture fixture = new Fixture(); + var pending = + new PublicationEvidence( + fixture.publication.intent(), Optional.empty(), Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + fixture.accountBinding, fixture.trustFence)) + .thenReturn(Optional.of(pending), Optional.of(fixture.publication)); + var ticks = new java.util.concurrent.atomic.AtomicLong(); + var ticker = + new io.grpc.Deadline.Ticker() { + @Override + public long nanoTime() { + return ticks.get(); + } + }; + var scheduler = mock(java.util.concurrent.ScheduledExecutorService.class); + var expiration = mock(java.util.concurrent.ScheduledFuture.class); + doReturn(expiration) + .when(scheduler) + .schedule( + any(Runnable.class), org.mockito.ArgumentMatchers.anyLong(), any(TimeUnit.class)); + var deadline = io.grpc.Deadline.after(1, TimeUnit.SECONDS, ticker); + try (var incoming = Context.current().withDeadline(deadline, scheduler)) { + AtomicInteger trustReads = new AtomicInteger(); + when(fixture.materializerTrust.current()) + .thenAnswer( + invocation -> { + assertThat(Context.current().getDeadline()).isSameAs(deadline); + if (trustReads.incrementAndGet() == (afterMovement ? 3 : 1)) { + if (failure.equals("cancel")) incoming.cancel(null); + else ticks.set(TimeUnit.SECONDS.toNanos(2)); + } + return Optional.of(fixture.binding); + }); + incoming.run( + () -> { + if (afterMovement) assertRejectedPublicRead(fixture); + else + assertThatThrownBy(fixture.source::currentPublicRead) + .isExactlyInstanceOf(SourceUnavailableException.class); + assertThatThrownBy(fixture.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + }); + assertThat(trustReads.get()).isEqualTo(afterMovement ? 3 : 1); + verify(fixture.configMapClient, times(afterMovement ? 1 : 0)).observe(); + } + } + } + } + + @Test + void lockedEnrollmentPreventsStalePreparedBranchDuringCurrentCommittedRead() { + Fixture fixture = new Fixture(); + fixture.usePreparedState(true, true); + var stale = fixture.desiredStateRepository.readEnrollmentState(fixture.accountBinding); + fixture.useStableCommittedState(); + var current = fixture.desiredStateRepository.readEnrollmentState(fixture.accountBinding); + when(fixture.desiredStateRepository.readEnrollmentState(fixture.accountBinding)) + .thenReturn(stale); + doReturn(current) + .when(fixture.desiredStateRepository) + .readLockedEnrollmentState(fixture.accountBinding); + when(fixture.desiredStateRepository.readPreparedGenerationForRecovery( + fixture.accountBinding, fixture.trustFence)) + .thenThrow(new AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException()); + assertThat(fixture.source.currentPublicRead().committedRecoveryEligible()).isTrue(); + verify(fixture.desiredStateRepository, times(2)) + .readLockedEnrollmentState(fixture.accountBinding); + verify(fixture.desiredStateRepository, never()) + .readPreparedGenerationForRecovery(fixture.accountBinding, fixture.trustFence); + } + + @Test + void establishedPinReadProgressesWhileAnotherRemoteObservationIsBlocked() throws Exception { + Fixture fixture = new Fixture(); + fixture.source.currentPublicRead(); + CountDownLatch blocked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + AtomicInteger observations = new AtomicInteger(); + when(fixture.configMapClient.observe()) + .thenAnswer( + invocation -> { + if (observations.incrementAndGet() == 1) { + blocked.countDown(); + assertThat(release.await(5, TimeUnit.SECONDS)).isTrue(); + } + return fixture.snapshot; + }); + var pool = Executors.newFixedThreadPool(2); + try { + var first = pool.submit(fixture.source::currentPublicRead); + assertThat(blocked.await(5, TimeUnit.SECONDS)).isTrue(); + var second = pool.submit(fixture.source::currentPublicRead); + assertThat(second.get(2, TimeUnit.SECONDS).jwksBytes()) + .isEqualTo(JWKS_1.getBytes(StandardCharsets.UTF_8)); + assertThat(first.isDone()).isFalse(); + release.countDown(); + assertThat(first.get(5, TimeUnit.SECONDS).sourceIdentity()) + .isEqualTo(fixture.source.sourceIdentity()); + } finally { + release.countDown(); + pool.shutdownNow(); + assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void initiallyQueuedReadersReleaseInitializationMonitorOnceThePinIsInstalled() throws Exception { + Fixture fixture = new Fixture(); + CountDownLatch firstRemote = new CountDownLatch(1); + CountDownLatch releaseFirst = new CountDownLatch(1); + CountDownLatch secondRemote = new CountDownLatch(1); + CountDownLatch releaseSecond = new CountDownLatch(1); + CountDownLatch queued = new CountDownLatch(2); + AtomicReference firstWorker = new AtomicReference<>(); + java.util.concurrent.ConcurrentLinkedQueue queuedWorkers = + new java.util.concurrent.ConcurrentLinkedQueue<>(); + AtomicInteger observations = new AtomicInteger(); + when(fixture.configMapClient.observe()) + .thenAnswer( + invocation -> { + int current = observations.incrementAndGet(); + if (current == 1) { + firstWorker.set(Thread.currentThread()); + firstRemote.countDown(); + assertThat(releaseFirst.await(5, TimeUnit.SECONDS)).isTrue(); + } else if (current == 2) { + secondRemote.countDown(); + assertThat(releaseSecond.await(5, TimeUnit.SECONDS)).isTrue(); + } + return fixture.snapshot; + }); + var pool = Executors.newFixedThreadPool(3); + var completed = + new java.util.concurrent.ExecutorCompletionService< + net.firedevops.firemud.common.security.AccountPublicJwksReadCodec.ReadResult>(pool); + try { + var first = completed.submit(fixture.source::currentPublicRead); + assertThat(firstRemote.await(5, TimeUnit.SECONDS)).isTrue(); + for (int i = 0; i < 2; i++) { + completed.submit( + () -> { + queuedWorkers.add(Thread.currentThread()); + queued.countDown(); + return fixture.source.currentPublicRead(); + }); + } + assertThat(queued.await(5, TimeUnit.SECONDS)).isTrue(); + org.awaitility.Awaitility.await() + .atMost(2, TimeUnit.SECONDS) + .untilAsserted( + () -> { + assertThat(queuedWorkers).hasSize(2); + for (Thread worker : queuedWorkers) { + var info = + java.lang.management.ManagementFactory.getThreadMXBean() + .getThreadInfo(worker.threadId()); + assertThat(info).isNotNull(); + assertThat(info.getThreadState()).isEqualTo(Thread.State.BLOCKED); + assertThat(info.getLockOwnerId()).isEqualTo(firstWorker.get().threadId()); + } + }); + releaseFirst.countDown(); + assertThat(first.get(5, TimeUnit.SECONDS).jwksBytes()) + .containsExactly(JWKS_1.getBytes(StandardCharsets.UTF_8)); + assertThat(secondRemote.await(5, TimeUnit.SECONDS)).isTrue(); + var firstCompleted = completed.poll(5, TimeUnit.SECONDS); + assertThat(firstCompleted).isNotNull(); + assertThat(firstCompleted.get(5, TimeUnit.SECONDS).jwksBytes()) + .containsExactly(JWKS_1.getBytes(StandardCharsets.UTF_8)); + var independentlyCompleted = completed.poll(2, TimeUnit.SECONDS); + assertThat(independentlyCompleted).isNotNull(); + assertThat(independentlyCompleted.get(5, TimeUnit.SECONDS).sourceIdentity()) + .isEqualTo(fixture.source.sourceIdentity()); + assertThat(releaseSecond.getCount()).isEqualTo(1); + releaseSecond.countDown(); + var lastCompleted = completed.poll(5, TimeUnit.SECONDS); + assertThat(lastCompleted).isNotNull(); + assertThat(lastCompleted.get(5, TimeUnit.SECONDS).sourceIdentity()) + .isEqualTo(fixture.source.sourceIdentity()); + } finally { + releaseFirst.countDown(); + releaseSecond.countDown(); + pool.shutdownNow(); + assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void competingFirstReadersCannotInstallConflictingSourcePins() throws Exception { + Fixture fixture = new Fixture(); + CountDownLatch blocked = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + CountDownLatch secondStarted = new CountDownLatch(1); + AtomicInteger observations = new AtomicInteger(); + AtomicReference firstWorker = new AtomicReference<>(); + AtomicReference secondWorker = new AtomicReference<>(); + when(fixture.configMapClient.observe()) + .thenAnswer( + invocation -> { + if (observations.incrementAndGet() == 1) { + firstWorker.set(Thread.currentThread()); + blocked.countDown(); + assertThat(release.await(5, TimeUnit.SECONDS)).isTrue(); + return fixture.snapshot; + } + return new ConfigMapSnapshot( + "44444444-4444-4444-8444-444444444444", "42", fixture.snapshot.data()); + }); + var pool = Executors.newFixedThreadPool(2); + try { + var first = pool.submit(fixture.source::currentPublicRead); + assertThat(blocked.await(5, TimeUnit.SECONDS)).isTrue(); + var second = + pool.submit( + () -> { + secondWorker.set(Thread.currentThread()); + secondStarted.countDown(); + return fixture.source.currentPublicRead(); + }); + assertThat(secondStarted.await(5, TimeUnit.SECONDS)).isTrue(); + org.awaitility.Awaitility.await() + .atMost(2, TimeUnit.SECONDS) + .untilAsserted( + () -> { + var info = + java.lang.management.ManagementFactory.getThreadMXBean() + .getThreadInfo(secondWorker.get().threadId()); + assertThat(info).isNotNull(); + assertThat(info.getThreadState()).isEqualTo(Thread.State.BLOCKED); + assertThat(info.getLockOwnerId()).isEqualTo(firstWorker.get().threadId()); + }); + release.countDown(); + assertThat(first.get(5, TimeUnit.SECONDS).sourceIdentity().configMapUid()) + .isEqualTo(CONFIG_MAP_UID); + assertThatThrownBy(() -> second.get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(IllegalStateException.class); + assertThat(fixture.source.sourceIdentity().configMapUid()).isEqualTo(CONFIG_MAP_UID); + } finally { + release.countDown(); + pool.shutdownNow(); + assertThat(pool.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + @Test void ownerPublicationChangingDuringReadProducesNoSnapshot() { Fixture fixture = new Fixture(); @@ -357,14 +1200,650 @@ void deniesInitialPrepublicationWhenPublicMarkerClaimsAnActiveFence() { } @Test - void deniesInitialPrepublicationWhenConfigMapResourceVersionIsStale() { + void versionOnlyInitialReadbackRemainsUnavailableWithoutInstallingASourcePin() { Fixture fixture = new Fixture(); when(fixture.configMapClient.observe()) .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", fixture.snapshot.data())); assertThatThrownBy(fixture.source::sourceIdentity) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Account trusted public JWKS source was rejected"); + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + } + + @Test + void versionOnlyDriftReturnsNoBytesUntilALaterExactOwnerOperation() { + Fixture fixture = new Fixture(); + SourceIdentity originalPin = fixture.source.sourceIdentity(); + Map metadataOnlyData = new LinkedHashMap<>(fixture.snapshot.data()); + metadataOnlyData.put("operator.note", "changed without changing Account-owned bytes"); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", metadataOnlyData)); + var guard = mock(AccountPublicJwksReadWorkloadGuard.class); + when(guard.requireCaller()) + .thenReturn(mock(AccountPublicJwksReadWorkloadGuard.ProtectedCaller.class)); + var owner = new AccountPublicJwksReadService(fixture.source, guard); + for (int attempt = 0; attempt < 3; attempt++) { + assertThatThrownBy(() -> owner.read(AccountPublicJwksReadCodec.request())) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + assertThat(fixture.source.sourceIdentity()).isEqualTo(originalPin); + } + assertThat(fixture.publication.receipt().orElseThrow().observedResourceVersion()) + .isEqualTo("42"); + // Recovery advances through a different authorized operation and receipt. It neither rolls + // Kubernetes RV backward nor replaces the original operation's immutable receipt. + fixture.useCommittedState("44", "45"); + var recovered = + AccountPublicJwksReadCodec.snapshot(owner.read(AccountPublicJwksReadCodec.request())); + assertThat(recovered.sourceIdentity()).isEqualTo(originalPin); + assertThat(recovered.jwksBytes()) + .containsExactly(JWKS_1_AND_2.getBytes(StandardCharsets.UTF_8)); + assertThat(fixture.nextPublication.receipt().orElseThrow().observedResourceVersion()) + .isEqualTo("45"); + assertThat(fixture.publication.receipt().orElseThrow().observedResourceVersion()) + .isEqualTo("42"); + verify(fixture.configMapClient, never()).publish(any(), anyMap()); + } + + @Test + void versionOnlyOutageClassificationNeverHidesUidOrOwnedByteTamper() { + Fixture original = new Fixture(); + Map changedJwks = new LinkedHashMap<>(original.snapshot.data()); + changedJwks.put(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, JWKS_1_AND_2); + Map changedMarker = new LinkedHashMap<>(original.snapshot.data()); + changedMarker.put( + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + original.initialMarker + " "); + for (ConfigMapSnapshot tamper : + List.of( + new ConfigMapSnapshot( + "44444444-4444-4444-8444-444444444444", "43", original.snapshot.data()), + new ConfigMapSnapshot(CONFIG_MAP_UID, "43", changedJwks), + new ConfigMapSnapshot(CONFIG_MAP_UID, "43", changedMarker))) { + Fixture fixture = new Fixture(); + fixture.source.sourceIdentity(); + when(fixture.configMapClient.observe()).thenReturn(tamper); + var guard = mock(AccountPublicJwksReadWorkloadGuard.class); + when(guard.requireCaller()) + .thenReturn(mock(AccountPublicJwksReadWorkloadGuard.ProtectedCaller.class)); + var owner = new AccountPublicJwksReadService(fixture.source, guard); + assertThatThrownBy(() -> owner.read(AccountPublicJwksReadCodec.request())) + .isExactlyInstanceOf( + net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException + .class) + .hasNoCause(); + } + } + + @Test + void preparedPrepublicationDeniesWithoutKeysRegardlessOfActiveReceiptAndNeverEnablesIssuance() { + for (boolean hasActiveReceipt : List.of(false, true)) { + Fixture fixture = new Fixture(); + fixture.usePreparedState(false, hasActiveReceipt); + var result = fixture.source.currentPublicRead(); + assertThat(result.preparedDeny()).isTrue(); + assertThat(result.committedRecoveryEligible()).isFalse(); + assertThat(result.jwksBytes()).isEmpty(); + assertThat(result.sourceIdentity()).isEqualTo(fixture.source.sourceIdentity()); + assertThatThrownBy(fixture.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, never()).publish(any(), anyMap()); + } + } + + @Test + void preparedActiveDeniesWithExactActiveReceiptOrFullyVerifiedPrivatePromotionProof() { + for (boolean hasActiveReceipt : List.of(false, true)) { + Fixture fixture = new Fixture(); + fixture.usePreparedState(true, hasActiveReceipt); + var result = fixture.source.currentPublicRead(); + assertThat(result.preparedDeny()).isTrue(); + assertThat(result.committedRecoveryEligible()).isFalse(); + assertThat(result.jwksBytes()).isEmpty(); + assertThat(result.sourceIdentity().configMapUid()).isEqualTo(CONFIG_MAP_UID); + verify(fixture.desiredStateRepository, times(2)) + .readPreparedPrivatePromotionReceiptForRecovery( + fixture.accountBinding, fixture.trustFence); + assertThatThrownBy(fixture.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + } + + @Test + void unreceiptedPreparedActiveRejectsMissingMismatchedOrUnverifiedPrivateReceipt() { + for (String tamper : + List.of( + "missing", + "helper-rejected", + "digest", + "operation", + "generation", + "private-rv", + "stored-digest", + "stored-rv", + "not-dispatched")) { + Fixture fixture = new Fixture(); + PromotionOperationEvidence promotion = fixture.usePreparedState(true, false); + UUID promotionId = promotion.operationId(); + String receiptDigest = promotion.privatePromotionReceiptDigest().orElseThrow(); + switch (tamper) { + case "missing" -> { + when(promotion.privatePromotionObservedResourceVersion()).thenReturn(Optional.empty()); + when(promotion.privatePromotionReceiptDigest()).thenReturn(Optional.empty()); + } + case "helper-rejected" -> + when(fixture.desiredStateRepository.readPreparedPrivatePromotionReceiptForRecovery( + eq(fixture.accountBinding), eq(fixture.trustFence))) + .thenThrow( + new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Full canonical private promotion receipt verification failed")); + case "digest", "operation", "generation", "private-rv" -> { + PrivatePromotionReceipt mismatched = + new PrivatePromotionReceipt( + tamper.equals("operation") ? NEXT_OPERATION_ID : promotionId, + tamper.equals("generation") ? NEXT_OPERATION_ID : INITIAL_OPERATION_ID, + tamper.equals("private-rv") ? "private-other" : "private-result", + tamper.equals("digest") ? "0".repeat(64) : receiptDigest); + when(fixture.desiredStateRepository.readPreparedPrivatePromotionReceiptForRecovery( + eq(fixture.accountBinding), eq(fixture.trustFence))) + .thenReturn(mismatched); + } + case "stored-digest" -> + when(promotion.privatePromotionReceiptDigest()).thenReturn(Optional.of("0".repeat(64))); + case "stored-rv" -> + when(promotion.privatePromotionObservedResourceVersion()) + .thenReturn(Optional.of("private-other")); + case "not-dispatched" -> when(promotion.privatePromotionDispatched()).thenReturn(false); + default -> throw new AssertionError(tamper); + } + assertRejectedPublicRead(fixture); + } + } + + @Test + void unreceiptedPreparedActiveAcceptsOpaqueChangedRvAndRejectsPriorRv() { + Fixture opaque = new Fixture(); + PromotionOperationEvidence promotion = opaque.usePreparedState(true, false); + String marker = promotion.expectedActiveMarkerJson(); + Map data = + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, JWKS_1, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, marker); + when(opaque.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "etcd:opaque_v-7", data)); + var result = opaque.source.currentPublicRead(); + assertThat(result.preparedDeny()).isTrue(); + assertThat(result.jwksBytes()).isEmpty(); + assertThat(result.committedRecoveryEligible()).isFalse(); + + Fixture priorRv = new Fixture(); + priorRv.usePreparedState(true, false); + when(priorRv.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "42", data)); + assertRejectedPublicRead(priorRv); + } + + @Test + void unreceiptedPreparedActiveRejectsChangedUidCompletePayloadAndMarker() { + for (String tamper : List.of("uid", "missing-key", "substituted-key", "marker")) { + Fixture fixture = new Fixture(); + PromotionOperationEvidence promotion = fixture.usePreparedState(true, false); + String marker = promotion.expectedActiveMarkerJson(); + String jwks = + switch (tamper) { + case "missing-key" -> "{\"keys\":[]}"; + case "substituted-key" -> "{\"keys\":[" + JWK_2 + "]}"; + default -> JWKS_1; + }; + if (tamper.equals("missing-key") || tamper.equals("substituted-key")) { + assertThat(jwks).isNotEqualTo(JWKS_1); + } + var snapshot = + new ConfigMapSnapshot( + tamper.equals("uid") ? "44444444-4444-4444-8444-444444444444" : CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + jwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + tamper.equals("marker") ? marker + " " : marker)); + when(fixture.configMapClient.observe()).thenReturn(snapshot); + assertRejectedPublicRead(fixture); + } + } + + @Test + void preparedDenialRejectsChangedOperationMountTrustUidMarkerOrActiveReceipt() { + for (String tamper : + List.of( + "operation", + "mount", + "trust", + "uid", + "marker", + "receipt", + "receipt-data", + "receipt-rv", + "unreceipted-active")) { + Fixture fixture = new Fixture(); + PromotionOperationEvidence promotion = fixture.usePreparedState(true, true); + String expectedActiveMarker = promotion.expectedActiveMarkerJson(); + switch (tamper) { + case "operation" -> when(promotion.operationId()).thenReturn(NEXT_OPERATION_ID); + case "mount" -> when(promotion.mountedObservationDigest()).thenReturn("0".repeat(64)); + case "trust" -> when(promotion.apiConfigRevision()).thenReturn("obsolete"); + case "receipt" -> + when(promotion.activeJwksReceiptDigest()).thenReturn(Optional.of("0".repeat(64))); + case "receipt-data" -> + when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.of("0".repeat(64))); + case "receipt-rv" -> + when(promotion.activeJwksObservedResourceVersion()).thenReturn(Optional.of("99")); + case "unreceipted-active" -> + when(promotion.activeJwksReceiptDigest()).thenReturn(Optional.empty()); + case "uid" -> + when(fixture.configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + "44444444-4444-4444-8444-444444444444", + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + expectedActiveMarker))); + case "marker" -> + when(fixture.configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + expectedActiveMarker + " "))); + default -> throw new AssertionError(tamper); + } + assertRejectedPublicRead(fixture); + } + } + + @Test + void publicReadRejectsMissingOwnerEvidenceWhileOrdinarySourceKeepsOutageSemantics() { + for (String missing : List.of("enrollment", "committed-signer", "initial-publication")) { + Fixture fixture = new Fixture(); + switch (missing) { + case "enrollment" -> + when(fixture.desiredStateRepository.readEnrollmentState(eq(fixture.accountBinding))) + .thenReturn(Optional.empty()); + case "committed-signer" -> { + fixture.useCommittedState(); + when(fixture.desiredStateRepository.readCurrentCommittedSigner( + eq(fixture.accountBinding), + eq(fixture.trustFence), + eq(API_BINDING_DIGEST), + eq("api-r1"))) + .thenReturn(Optional.empty()); + } + case "initial-publication" -> + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.accountBinding), eq(fixture.trustFence))) + .thenReturn(Optional.empty()); + default -> throw new AssertionError(missing); + } + + assertRejectedPublicRead(fixture); + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + verify(fixture.configMapClient, never()).observe(); + } + } + + @Test + void unreceiptedInitialPrepublicationIsTemporaryForExactIntendedOrEnrolledPriorProjection() { + for (boolean intendedPublished : List.of(false, true)) { + Fixture fixture = new Fixture(); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.accountBinding), eq(fixture.trustFence))) + .thenReturn( + Optional.of( + new PublicationEvidence( + fixture.publication.intent(), Optional.empty(), Optional.empty()))); + if (!intendedPublished) { + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "41", INITIAL_PRIOR_DATA)); + } + assertThatThrownBy(fixture.source::currentPublicRead) + .isExactlyInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class); + MountObservation mount = + MountObservation.create( + fixture.publication.intent(), fixture.publication.receipt().orElseThrow()); + var recovered = + new PublicationEvidence( + fixture.publication.intent(), fixture.publication.receipt(), Optional.of(mount)); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.accountBinding), eq(fixture.trustFence))) + .thenReturn(Optional.of(recovered)); + when(fixture.configMapClient.observe()).thenReturn(fixture.snapshot); + var result = fixture.source.currentPublicRead(); + assertThat(result.preparedDeny()).isFalse(); + assertThat(result.committedRecoveryEligible()).isFalse(); + assertThat(result.jwksBytes()).isEqualTo(JWKS_1.getBytes(StandardCharsets.UTF_8)); + assertThat(result.sourceIdentity()).isEqualTo(fixture.source.sourceIdentity()); + } + } + + @Test + void unreceiptedAdditivePrepublicationReturnsNoNewKeysAndRecoversWithoutRepinning() { + for (boolean intendedPublished : List.of(false, true)) { + Fixture fixture = new Fixture(); + SourceIdentity pin = fixture.source.sourceIdentity(); + fixture.useCommittedState(); + fixture.removeCurrentPublicationReceipt(); + if (!intendedPublished) { + var prior = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "42", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + activeMarker(new ActiveSigner("1", "key_1")), + "operator.note", + "preserved")); + when(fixture.configMapClient.observe()).thenReturn(prior); + } + for (int attempt = 0; attempt < 2; attempt++) { + assertThatThrownBy(fixture.source::currentPublicRead) + .isExactlyInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + assertThat(fixture.source.sourceIdentity()).isEqualTo(pin); + } + // Exact receipt/mount recording completes the same intended additive publication. + fixture.useCommittedState(); + var receipt = fixture.nextPublication.receipt().orElseThrow(); + var mount = MountObservation.create(fixture.nextPublication.intent(), receipt); + var recovered = + new PublicationEvidence( + fixture.nextPublication.intent(), Optional.of(receipt), Optional.of(mount)); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.accountBinding), eq(fixture.trustFence))) + .thenReturn(Optional.of(recovered)); + var result = fixture.source.currentPublicRead(); + assertThat(result.sourceIdentity()).isEqualTo(pin); + assertThat(result.preparedDeny()).isFalse(); + assertThat(result.committedRecoveryEligible()).isFalse(); + assertThat(result.jwksBytes()).isEqualTo(JWKS_1_AND_2.getBytes(StandardCharsets.UTF_8)); + } + } + + @Test + void unreceiptedAdditivePublicationPreservesOnlyOriginalFreshCachedKeys() { + Fixture fixture = new Fixture(); + var pin = fixture.source.sourceIdentity(); + java.time.Clock clock = mock(java.time.Clock.class); + var start = java.time.Instant.parse("2026-11-10T00:00:00Z"); + when(clock.instant()).thenReturn(start); + var cache = + new net.firedevops.firemud.common.security.AccountPublicJwksCache( + () -> { + var read = fixture.source.currentPublicRead(); + if (read.preparedDeny()) { + throw new net.firedevops.firemud.common.security.AccountPublicJwksCache + .SourcePreparedDenyException(); + } + return new PublicJwksSnapshot( + read.sourceIdentity(), read.jwksBytes(), read.committedRecoveryEligible()); + }, + pin, + clock, + java.time.Duration.ofSeconds(5)); + cache.refresh(); + assertThat(cache.keyFor("key_1")).isNotNull(); + fixture.useCommittedState(); + fixture.removeCurrentPublicationReceipt(); + when(clock.instant()).thenReturn(start.plusSeconds(4)); + cache.refresh(); + assertThat(cache.sourceIdentity()).isEqualTo(pin); + assertThat(cache.keyFor("key_1")).isNotNull(); + assertThatThrownBy(() -> cache.keyFor("key_2")) + .isInstanceOf( + net.firedevops.firemud.common.security.AccountPublicJwksCache.UnknownKeyException + .class); + when(clock.instant()).thenReturn(start.plusSeconds(5)); + assertThatThrownBy(() -> cache.keyFor("key_1")).isInstanceOf(SourceUnavailableException.class); + fixture.useCommittedState(); + cache.refresh(); + assertThat(cache.sourceIdentity()).isEqualTo(pin); + assertThat(cache.keyFor("key_2")).isNotNull(); + } + + @Test + void unreceiptedPublicationRejectsUnprovenPredecessorAndExtraAdditions() { + Fixture initial = new Fixture(); + when(initial.publicationRepository.readCurrentPublication( + eq(initial.accountBinding), eq(initial.trustFence))) + .thenReturn( + Optional.of( + new PublicationEvidence( + initial.publication.intent(), Optional.empty(), Optional.empty()))); + var changed = new LinkedHashMap<>(initial.snapshot.data()); + changed.put("operator.note", "changed"); + when(initial.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "42", changed)); + assertRejectedPublicRead(initial); + + Fixture extra = new Fixture(); + extra.useCommittedState(); + String unauthorized = + "{\"keys\":[" + JWK_1 + "," + JWK_2 + "," + JWK_1.replace("\"key_1\"", "\"key_3\"") + "]}"; + assertThat(unauthorized).isNotEqualTo(JWKS_1_AND_2); + extra.replaceNextJwks(unauthorized); + extra.removeCurrentPublicationReceipt(); + assertRejectedPublicRead(extra); + } + + @Test + void unreceiptedPrepublicationRejectsUidMarkerPayloadAndGenerationMismatch() { + for (boolean initial : List.of(false, true)) { + for (String tamper : List.of("uid", "marker", "payload", "generation")) { + Fixture fixture = new Fixture(); + if (!initial) fixture.useCommittedState(); + PublicationEvidence publication = initial ? fixture.publication : fixture.nextPublication; + String marker = publication.intent().generationMarkerJson(); + String jwks = publication.intent().jwksJson(); + String liveJwks = tamper.equals("payload") ? jwks + " " : jwks; + if (tamper.equals("payload")) { + assertThat(liveJwks).isNotEqualTo(jwks); + } + var live = + new ConfigMapSnapshot( + tamper.equals("uid") ? "44444444-4444-4444-8444-444444444444" : CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + liveJwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + tamper.equals("marker") ? marker + " " : marker)); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.accountBinding), eq(fixture.trustFence))) + .thenReturn( + Optional.of( + new PublicationEvidence( + publication.intent(), Optional.empty(), Optional.empty()))); + when(fixture.configMapClient.observe()).thenReturn(live); + if (tamper.equals("generation")) { + GenerationRequest request = + fixture.desiredStateRepository.readCurrentGenerationRequest( + fixture.accountBinding, fixture.trustFence); + when(request.operationDigest()).thenReturn("0".repeat(64)); + } + assertRejectedPublicRead(fixture); + } + } + } + + @Test + void unreceiptedAdditivePublicationRejectsSelfConsistentButUnqualifiedMarker() throws Exception { + var json = JsonMapper.builder().build(); + ActiveSigner active = new ActiveSigner("1", "key_1"); + for (String tamper : + List.of( + "malformed", + "unknown-phase", + "active-phase", + "unknown-field", + "missing-field", + "schema", + "operation-id", + "operation-digest", + "request-digest", + "receipt-digest", + "trust-digest", + "trust-revision", + "api-digest", + "api-revision", + "namespace", + "pending-generation", + "pending-kid", + "pending-fingerprint", + "durable-absent", + "durable-generation", + "durable-kid", + "published-absent", + "published-generation", + "published-kid")) { + Fixture fixture = new Fixture(); + fixture.useCommittedState(); + String originalMarker = fixture.nextPublication.intent().generationMarkerJson(); + ObjectNode marker = (ObjectNode) json.readTree(originalMarker); + ObjectNode binding = (ObjectNode) marker.get("binding"); + ObjectNode pending = (ObjectNode) marker.get("pending"); + ObjectNode durable = (ObjectNode) marker.get("expectedDurableActive"); + ObjectNode published = (ObjectNode) marker.get("expectedPublishedActive"); + switch (tamper) { + case "malformed" -> { + /* The serialized projection is replaced below. */ + } + case "unknown-phase" -> marker.put("phase", "UNKNOWN"); + case "active-phase" -> marker.put("phase", "ACTIVE"); + case "unknown-field" -> marker.put("unexpected", true); + case "missing-field" -> marker.remove("generationRequestDigest"); + case "schema" -> marker.put("schemaVersion", 2); + case "operation-id" -> marker.put("operationId", INITIAL_OPERATION_ID.toString()); + case "operation-digest" -> marker.put("operationDigest", "0".repeat(64)); + case "request-digest" -> marker.put("generationRequestDigest", "0".repeat(64)); + case "receipt-digest" -> marker.put("generationReceiptDigest", "0".repeat(64)); + case "trust-digest" -> binding.put("trustBindingDigest", "0".repeat(64)); + case "trust-revision" -> binding.put("trustConfigRevision", "obsolete"); + case "api-digest" -> binding.put("apiBindingDigest", "0".repeat(64)); + case "api-revision" -> binding.put("apiConfigRevision", "obsolete"); + case "namespace" -> binding.put("namespace", "other-namespace"); + case "pending-generation" -> pending.put("generation", "3"); + case "pending-kid" -> pending.put("kid", "key_other"); + case "pending-fingerprint" -> pending.put("publicKeyFingerprint", "0".repeat(64)); + case "durable-absent" -> { + durable.removeAll(); + durable.put("present", false); + } + case "durable-generation" -> durable.put("generation", "3"); + case "durable-kid" -> durable.put("kid", "key_other"); + case "published-absent" -> { + published.removeAll(); + published.put("present", false); + } + case "published-generation" -> published.put("generation", "3"); + case "published-kid" -> published.put("kid", "key_other"); + default -> throw new AssertionError(tamper); + } + String alteredMarker = tamper.equals("malformed") ? "{" : json.writeValueAsString(marker); + assertThat(alteredMarker).as(tamper).isNotEqualTo(originalMarker); + PublicationEvidence altered = + fixture.publication( + JWKS_1_AND_2, alteredMarker, "42", "43", "2", "key_2", Optional.of(active)); + // Recompute all immutable intent hashes; rejection must come from marker semantics. + assertThat(altered.intent().generationMarkerDigest()).isEqualTo(sha256(alteredMarker)); + assertThat(altered.intent().publicDataDigest()) + .isEqualTo( + AccountJwtJwksPublicationRepository.publicDataDigest(JWKS_1_AND_2, alteredMarker)); + var unreceipted = + new PublicationEvidence(altered.intent(), Optional.empty(), Optional.empty()); + var live = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1_AND_2, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + alteredMarker, + "operator.note", + "preserved")); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.accountBinding), eq(fixture.trustFence))) + .thenReturn(Optional.of(unreceipted)); + when(fixture.configMapClient.observe()).thenReturn(live); + assertRejectedPublicRead(fixture); + } + } + + @Test + void preparedDenyPinsCurrentResourceAndRejectsSubsequentProtectedTrustChange() { + Fixture fixture = new Fixture(); + fixture.usePreparedState(false, false); + fixture.source.currentPublicRead(); + when(fixture.materializerTrust.current()) + .thenReturn(Optional.of(binding(CLUSTER_UID, NAMESPACE_UID, "materializer-r2"))); + assertRejectedPublicRead(fixture); + } + + @Test + void onlyExactCommittedActiveProjectionIsRecoveryEligible() { + Fixture initial = new Fixture(); + assertThat(initial.source.currentPublicRead().committedRecoveryEligible()).isFalse(); + Fixture nextPrepublication = new Fixture(); + nextPrepublication.useCommittedState(); + assertThat(nextPrepublication.source.currentPublicRead().committedRecoveryEligible()).isFalse(); + + Fixture committed = new Fixture(); + committed.useCommittedState(); + when(committed.desiredStateRepository.readCurrentGenerationRequest( + eq(committed.accountBinding), eq(committed.trustFence))) + .thenReturn(mock(GenerationRequest.class)); + when(committed.configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "42", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + activeMarker(new ActiveSigner("1", "key_1"))))); + var result = committed.source.currentPublicRead(); + assertThat(result.preparedDeny()).isFalse(); + assertThat(result.committedRecoveryEligible()).isTrue(); + assertThat(result.jwksBytes()).isEqualTo(JWKS_1.getBytes(StandardCharsets.UTF_8)); + } + + private static void assertRejectedPublicRead(Fixture fixture) { + var guard = mock(AccountPublicJwksReadWorkloadGuard.class); + when(guard.requireCaller()) + .thenReturn(mock(AccountPublicJwksReadWorkloadGuard.ProtectedCaller.class)); + assertThatThrownBy( + () -> + new AccountPublicJwksReadService(fixture.source, guard) + .read(AccountPublicJwksReadCodec.request())) + .isExactlyInstanceOf( + net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException + .class); } private static Binding binding(String clusterUid, String namespaceUid) { @@ -461,8 +1940,8 @@ private Fixture(String jwks) { API_BINDING_DIGEST, "api-r1", CONFIG_MAP_UID, - "40", - "6".repeat(64)); + "41", + AccountJwtJwksPublicationRepository.snapshotDigest(INITIAL_PRIOR_DATA)); initialMarker = marker(INITIAL_OPERATION_ID, "1", "key_1", publicFingerprint, Optional.empty()); initialRequest = mock(GenerationRequest.class); @@ -523,6 +2002,8 @@ private Fixture(String jwks) { when(configMapClient.observe()).thenReturn(snapshot); when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) .thenReturn(Optional.of(initialDesiredState)); + when(desiredStateRepository.readLockedEnrollmentState(eq(accountBinding))) + .thenAnswer(invocation -> desiredStateRepository.readEnrollmentState(accountBinding)); when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) .thenReturn(initialRequest); when(desiredStateRepository.readCurrentGenerationResult(eq(accountBinding), eq(trustFence))) @@ -538,7 +2019,184 @@ private Fixture(String jwks) { transactionManager); } + private PromotionOperationEvidence usePreparedState( + boolean liveActive, boolean hasActiveReceipt) { + UUID promotionId = UUID.fromString("66666666-6666-4666-8666-000000000001"); + DesiredState preparedState = + new DesiredState( + accountBinding, + 3, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.of(promotionId), + Optional.of(enrollmentIdentity)); + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + PublicationReceipt receipt = publication.receipt().orElseThrow(); + MountObservation mount = MountObservation.create(publication.intent(), receipt); + String activeMarker = initialMarker.replace("PREPUBLISHED", "ACTIVE"); + when(promotion.operationId()).thenReturn(promotionId); + when(promotion.requestDigest()).thenReturn("7".repeat(64)); + when(promotion.status()).thenReturn("PREPARED"); + when(promotion.expectedRecordVersion()).thenReturn(2L); + when(promotion.binding()).thenReturn(accountBinding); + when(promotion.expectedPreviousActive()).thenReturn(Optional.empty()); + when(promotion.expectedPublishedActive()).thenReturn(Optional.empty()); + when(promotion.trustFence()).thenReturn(trustFence); + when(promotion.apiBindingDigest()).thenReturn(API_BINDING_DIGEST); + when(promotion.apiConfigRevision()).thenReturn("api-r1"); + when(promotion.generationOperationId()).thenReturn(INITIAL_OPERATION_ID); + when(promotion.generationOperationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(promotion.generationReceiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + when(promotion.targetGeneration()).thenReturn("1"); + when(promotion.targetKid()).thenReturn("key_1"); + when(promotion.targetAlgorithm()).thenReturn("RS256"); + when(promotion.targetPublicKeyFingerprint()).thenReturn(publicFingerprint); + when(promotion.publicConfigMapUid()).thenReturn(CONFIG_MAP_UID); + when(promotion.expectedPublicResourceVersion()).thenReturn("42"); + when(promotion.expectedPublicJwksJson()).thenReturn(JWKS_1); + when(promotion.expectedActiveMarkerJson()).thenReturn(activeMarker); + when(promotion.prepublicationIntentDigest()).thenReturn(publication.intent().intentDigest()); + when(promotion.prepublicationReceiptDigest()).thenReturn(receipt.receiptDigest()); + when(promotion.mountedObservationDigest()).thenReturn(mount.observationDigest()); + String secretUid = "77777777-7777-4777-8777-777777777777"; + when(promotion.secretUid()).thenReturn(secretUid); + when(promotion.expectedPrivateResourceVersion()).thenReturn("private-prior"); + when(promotion.privatePromotionDispatched()).thenReturn(true); + Map privatePreimage = new LinkedHashMap<>(); + privatePreimage.put("receiptVersion", 1); + privatePreimage.put("promotionOperationId", promotionId.toString()); + privatePreimage.put("promotionRequestDigest", promotion.requestDigest()); + privatePreimage.put("generationOperationId", INITIAL_OPERATION_ID.toString()); + privatePreimage.put("generationOperationDigest", GENERATION_OPERATION_DIGEST); + privatePreimage.put("generationReceiptDigest", GENERATION_RECEIPT_DIGEST); + privatePreimage.put( + "secretResource", + Map.of( + "kind", + "Secret", + "name", + AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME)); + privatePreimage.put("secretUid", secretUid); + privatePreimage.put("expectedPriorResourceVersion", "private-prior"); + privatePreimage.put("observedResourceVersion", "private-result"); + privatePreimage.put("action", "PROMOTE_PENDING"); + privatePreimage.put("resultingSlots", List.of("current")); + privatePreimage.put( + "current", + Map.of("generation", "1", "kid", "key_1", "publicKeyFingerprint", publicFingerprint)); + privatePreimage.put("previous", Map.of("present", false)); + try { + String privateDigest = + sha256( + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(privatePreimage)), + StandardCharsets.UTF_8)); + when(promotion.privatePromotionObservedResourceVersion()) + .thenReturn(Optional.of("private-result")); + when(promotion.privatePromotionReceiptDigest()).thenReturn(Optional.of(privateDigest)); + var privateReceipt = + new PrivatePromotionReceipt( + promotionId, INITIAL_OPERATION_ID, "private-result", privateDigest); + when(desiredStateRepository.readPreparedPrivatePromotionReceiptForRecovery( + eq(accountBinding), eq(trustFence))) + .thenReturn(privateReceipt); + } catch (Exception invalidFixture) { + throw new AssertionError(invalidFixture); + } + when(promotion.activeJwksObservedResourceVersion()).thenReturn(Optional.empty()); + when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.empty()); + when(promotion.activeJwksReceiptDigest()).thenReturn(Optional.empty()); + if (hasActiveReceipt) { + String dataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest(JWKS_1, activeMarker); + Map preimage = new LinkedHashMap<>(); + preimage.put("receiptVersion", "account-jwt-active-jwks-promotion-receipt/v1"); + preimage.put("promotionOperationId", promotionId.toString()); + preimage.put("promotionRequestDigest", promotion.requestDigest()); + preimage.put("generationOperationId", INITIAL_OPERATION_ID.toString()); + preimage.put("generationOperationDigest", GENERATION_OPERATION_DIGEST); + preimage.put("generationReceiptDigest", GENERATION_RECEIPT_DIGEST); + preimage.put("configMapName", AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME); + preimage.put("configMapUid", CONFIG_MAP_UID); + preimage.put("priorResourceVersion", "42"); + preimage.put("observedResourceVersion", "43"); + preimage.put("action", "MARK_ACTIVE"); + preimage.put("publicDataDigest", dataDigest); + try { + String digest = + sha256( + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(preimage)), + StandardCharsets.UTF_8)); + when(promotion.activeJwksObservedResourceVersion()).thenReturn(Optional.of("43")); + when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.of(dataDigest)); + when(promotion.activeJwksReceiptDigest()).thenReturn(Optional.of(digest)); + } catch (Exception invalidFixture) { + throw new AssertionError(invalidFixture); + } + } + var prepared = new PreparedGenerationEvidence(preparedState, promotion, initialResult); + when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) + .thenReturn(Optional.of(preparedState)); + when(desiredStateRepository.readPreparedGenerationForRecovery( + eq(accountBinding), eq(trustFence))) + .thenReturn(prepared); + when(publicationRepository.readPreparedPublicationForRecovery( + eq(accountBinding), eq(trustFence))) + .thenReturn(new PromotionPublicationEvidence(publication.intent(), receipt, mount)); + when(configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + liveActive ? "43" : "42", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + liveActive ? activeMarker : initialMarker))); + return promotion; + } + + private void useStableCommittedState() { + useCommittedState("43", "44"); + var committed = + desiredStateRepository + .readCurrentCommittedSigner(accountBinding, trustFence, API_BINDING_DIGEST, "api-r1") + .orElseThrow(); + ActiveSigner active = new ActiveSigner("1", "key_1"); + DesiredState stable = + new DesiredState( + accountBinding, + 4, + Optional.of(active), + Optional.of(active), + Optional.empty(), + Optional.empty(), + Optional.of(enrollmentIdentity)); + when(committed.desiredState()).thenReturn(stable); + when(desiredStateRepository.readEnrollmentState(accountBinding)) + .thenReturn(Optional.of(stable)); + String marker = initialMarker.replace("PREPUBLISHED", "ACTIVE"); + String digest = AccountJwtJwksPublicationRepository.publicDataDigest(JWKS_1, marker); + when(committed.promotion().expectedActiveMarkerJson()).thenReturn(marker); + when(committed.promotion().activeJwksPublicDataDigest()).thenReturn(Optional.of(digest)); + when(committed.publicReceipt().publicDataDigest()).thenReturn(digest); + when(configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of("jwks.json", JWKS_1, "jwt-generation.json", marker))); + } + private void useCommittedState() { + useCommittedState("42", "43"); + } + + private void useCommittedState(String activeResourceVersion, String nextResourceVersion) { ActiveSigner active = new ActiveSigner("1", "key_1"); DesiredState committedState = new DesiredState( @@ -565,10 +2223,11 @@ private void useCommittedState() { when(promotion.publicConfigMapUid()).thenReturn(CONFIG_MAP_UID); when(promotion.expectedPublicJwksJson()).thenReturn(JWKS_1); when(promotion.expectedActiveMarkerJson()).thenReturn(activeMarker); - when(promotion.activeJwksObservedResourceVersion()).thenReturn(Optional.of("42")); + when(promotion.activeJwksObservedResourceVersion()) + .thenReturn(Optional.of(activeResourceVersion)); when(promotion.activeJwksPublicDataDigest()).thenReturn(Optional.of(activeDigest)); when(receipt.configMapUid()).thenReturn(CONFIG_MAP_UID); - when(receipt.observedResourceVersion()).thenReturn("42"); + when(receipt.observedResourceVersion()).thenReturn(activeResourceVersion); when(receipt.publicDataDigest()).thenReturn(activeDigest); when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) .thenReturn(Optional.of(committedState)); @@ -583,6 +2242,10 @@ private void useCommittedState() { when(nextRequest.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); when(nextRequest.generationReceiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); when(nextRequest.desiredStateVersion()).thenReturn(2L); + when(nextRequest.binding()).thenReturn(accountBinding); + when(nextRequest.trustFence()).thenReturn(trustFence); + when(nextRequest.targetAlgorithm()).thenReturn("RS256"); + when(nextRequest.publicJwkJson()).thenReturn(JWK_2); when(nextRequest.targetGeneration()).thenReturn("2"); when(nextRequest.targetKid()).thenReturn("key_2"); when(nextRequest.publicKeyFingerprint()).thenReturn(fingerprint(JWK_2)); @@ -591,17 +2254,40 @@ private void useCommittedState() { when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) .thenReturn(nextRequest); + GenerationResult nextResult = mock(GenerationResult.class); + when(nextResult.operationId()).thenReturn(NEXT_OPERATION_ID); + when(nextResult.binding()).thenReturn(accountBinding); + when(nextResult.trustFence()).thenReturn(trustFence); + when(nextResult.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(nextResult.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(nextResult.receiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + when(nextResult.desiredStateVersion()).thenReturn(2L); + when(nextResult.targetGeneration()).thenReturn("2"); + when(nextResult.targetKid()).thenReturn("key_2"); + when(nextResult.targetAlgorithm()).thenReturn("RS256"); + when(nextResult.publicKeyFingerprint()).thenReturn(fingerprint(JWK_2)); + when(nextResult.publicJwkJson()).thenReturn(JWK_2); + when(desiredStateRepository.readCurrentGenerationResult(eq(accountBinding), eq(trustFence))) + .thenReturn(nextResult); + String nextMarker = marker(NEXT_OPERATION_ID, "2", "key_2", fingerprint(JWK_2), Optional.of(active)); nextPublication = - publication(JWKS_1_AND_2, nextMarker, "42", "43", "2", "key_2", Optional.of(active)); + publication( + JWKS_1_AND_2, + nextMarker, + activeResourceVersion, + nextResourceVersion, + "2", + "key_2", + Optional.of(active)); when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) .thenReturn(Optional.of(nextPublication)); when(configMapClient.observe()) .thenReturn( new ConfigMapSnapshot( CONFIG_MAP_UID, - "43", + nextResourceVersion, Map.of( AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, JWKS_1_AND_2, @@ -676,7 +2362,16 @@ private PublicationEvidence publication( AccountJwtJwksPublicationRepository.PUBLIC_JWKS_NAME, CONFIG_MAP_UID, expectedResourceVersion, - "4".repeat(64), + AccountJwtJwksPublicationRepository.snapshotDigest( + expectedActive.isEmpty() + ? INITIAL_PRIOR_DATA + : Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + activeMarker(expectedActive.orElseThrow()), + "operator.note", + "preserved")), generation, kid, keyFingerprint, @@ -748,9 +2443,15 @@ private static String activeMarker(Optional active) { } private static String fingerprint(String jwk) { - String modulus = jwk.contains("key_1") ? "AQID" : "BAUG"; - String preimage = "{\"e\":\"AQAB\",\"kty\":\"RSA\",\"n\":\"" + modulus + "\"}"; try { + var mapper = JsonMapper.builder().build(); + var key = mapper.readTree(jwk); + String preimage = + mapper.writeValueAsString( + Map.of( + "e", key.path("e").asText(), + "kty", key.path("kty").asText(), + "n", key.path("n").asText())); return java.util.HexFormat.of() .formatHex( MessageDigest.getInstance("SHA-256") diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadServiceTest.java new file mode 100644 index 0000000000..2030dc17c7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadServiceTest.java @@ -0,0 +1,161 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksRequest; +import net.firedevops.firemud.accountservice.config.AccountPublicJwksReadWorkloadGuard; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec.ReadResult; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Owner orchestration proof; the source edge has its own receipt/ConfigMap custody tests. */ +class AccountPublicJwksReadServiceTest { + private static final AccountPublicJwksCache.SourceIdentity PIN = + new AccountPublicJwksCache.SourceIdentity( + "prod", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "api-7", + "https://kubernetes.example:6443", + "a".repeat(64)); + private final AccountJwtJwksTrustedSource source = mock(AccountJwtJwksTrustedSource.class); + private final AccountPublicJwksReadWorkloadGuard guard = + mock(AccountPublicJwksReadWorkloadGuard.class); + private final AccountPublicJwksReadWorkloadGuard.ProtectedCaller caller = + mock(AccountPublicJwksReadWorkloadGuard.ProtectedCaller.class); + private final AccountPublicJwksReadService owner = + new AccountPublicJwksReadService(source, guard); + + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void returnsExactCurrentSnapshotBetweenProtectedGuardReadsWithNoReadinessPlan() { + when(guard.requireCaller()).thenReturn(caller); + when(source.sourceIdentity()).thenReturn(PIN); + when(source.currentPublicRead()) + .thenReturn(new ReadResult(PIN, new byte[] {1, 2, 3}, false, false)); + var response = owner.read(AccountPublicJwksReadCodec.request()); + assertThat(AccountPublicJwksReadCodec.snapshot(response).sourceIdentity()).isEqualTo(PIN); + assertThat(response.getPublicJwks().toByteArray()) + .containsExactly((byte) 1, (byte) 2, (byte) 3); + var order = inOrder(guard, source, caller); + order.verify(guard).requireCaller(); + order.verify(source).currentPublicRead(); + order.verify(caller).requireSource(PIN); + order.verify(source).sourceIdentity(); + order.verify(guard).requireCaller(); + } + + @Test + void authenticatesPreparedDenyAndReturnsNoKeysOrRecoveryAuthority() { + when(guard.requireCaller()).thenReturn(caller); + when(source.sourceIdentity()).thenReturn(PIN); + var deny = new ReadResult(PIN, new byte[0], true, false); + when(source.currentPublicRead()).thenReturn(deny); + var result = + AccountPublicJwksReadCodec.result(owner.read(AccountPublicJwksReadCodec.request())); + assertThat(result.sourceIdentity()).isEqualTo(PIN); + assertThat(result.preparedDeny()).isTrue(); + assertThat(result.jwksBytes()).isEmpty(); + assertThat(result.committedRecoveryEligible()).isFalse(); + var order = inOrder(guard, source, caller); + order.verify(guard).requireCaller(); + order.verify(source).currentPublicRead(); + order.verify(caller).requireSource(PIN); + order.verify(source).sourceIdentity(); + order.verify(guard).requireCaller(); + } + + @Test + void peerDenialPrecedesParsingAndOwnerReads() { + when(guard.requireCaller()) + .thenThrow(new AccountPublicJwksReadWorkloadGuard.ReadDeniedException()); + assertThatThrownBy(() -> owner.read(GetCurrentAccountPublicJwksRequest.getDefaultInstance())) + .isInstanceOf(AccountPublicJwksReadWorkloadGuard.ReadDeniedException.class); + verifyNoInteractions(source); + } + + @Test + void malformedRequestAndAmbientTransactionNeverReadOwnerSource() { + when(guard.requireCaller()).thenReturn(caller); + assertThatThrownBy(() -> owner.read(GetCurrentAccountPublicJwksRequest.getDefaultInstance())) + .isInstanceOf(AccountPublicJwksReadCodec.InvalidFrameException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> owner.read(AccountPublicJwksReadCodec.request())) + .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class); + verifyNoInteractions(source); + } + + @Test + void rejectsProducerBytesAsPublicationFailureAfterAcceptingRequest() { + when(guard.requireCaller()).thenReturn(caller); + when(source.sourceIdentity()).thenReturn(PIN); + for (byte[] bytes : + new byte[][] {new byte[0], new byte[AccountPublicJwksCache.MAX_JWKS_BYTES + 1]}) { + var invalid = mock(ReadResult.class); + when(invalid.sourceIdentity()).thenReturn(PIN); + when(invalid.jwksBytes()).thenReturn(bytes); + when(source.currentPublicRead()).thenReturn(invalid); + assertThatThrownBy(() -> owner.read(AccountPublicJwksReadCodec.request())) + .isExactlyInstanceOf(AccountPublicJwksCache.InvalidJwksException.class) + .hasNoCause(); + } + when(source.currentPublicRead()).thenReturn(null); + assertThatThrownBy(() -> owner.read(AccountPublicJwksReadCodec.request())) + .isExactlyInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + } + + @Test + void preservesUnclassifiedHandlerFaultForReceiverAvailabilityMapping() { + when(guard.requireCaller()).thenReturn(caller); + var fault = new IllegalStateException("unclassified internal fault"); + when(source.currentPublicRead()).thenThrow(fault); + assertThatThrownBy(() -> owner.read(AccountPublicJwksReadCodec.request())).isSameAs(fault); + } + + @Test + void refusesChangedSourceOrProtectedGuardAndPreservesTemporaryOutageType() { + when(guard.requireCaller()).thenReturn(caller); + when(source.sourceIdentity()).thenReturn(PIN); + when(source.currentPublicRead()) + .thenThrow(new AccountPublicJwksCache.SourceUnavailableException()); + assertThatThrownBy(() -> owner.read(AccountPublicJwksReadCodec.request())) + .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class); + var changed = + new AccountPublicJwksCache.SourceIdentity( + PIN.environmentId(), + PIN.clusterId(), + PIN.clusterIncarnationUid(), + PIN.namespace(), + PIN.namespaceUid(), + "44444444-4444-4444-8444-444444444444", + PIN.bindingRevision(), + PIN.apiServerOrigin(), + PIN.servingCaSha256()); + doReturn(new ReadResult(changed, new byte[] {1}, false, false)) + .when(source) + .currentPublicRead(); + assertThatThrownBy(() -> owner.read(AccountPublicJwksReadCodec.request())) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + when(source.currentPublicRead()).thenReturn(new ReadResult(PIN, new byte[] {1}, false, false)); + when(guard.requireCaller()) + .thenReturn(caller, mock(AccountPublicJwksReadWorkloadGuard.ProtectedCaller.class)); + assertThatThrownBy(() -> owner.read(AccountPublicJwksReadCodec.request())) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountJwtPreparedPublicationPostgresFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountJwtPreparedPublicationPostgresFixture.java new file mode 100644 index 0000000000..b6d333caa3 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountJwtPreparedPublicationPostgresFixture.java @@ -0,0 +1,463 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ExpectedPod; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Bounded real-PostgreSQL readiness setup for public-publication writer tests. Inventory and + * authenticated receiver inputs are controlled transport observations; all durable plans, real + * mounted-key signing attempts, per-pod receipts and promotion proofs use the normal owners. No SQL + * writes, synthetic owner receipts, live Kubernetes IO or runtime activation are provided. Mutable + * owner/database collaborators are supplied per operation and are not retained by this fixture. + */ +public final class AccountJwtPreparedPublicationPostgresFixture { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final Binding binding; + private final TrustFence trust; + private final GenerationResult result; + private final String apiDigest; + private final String apiRevision; + + public AccountJwtPreparedPublicationPostgresFixture( + Binding binding, + TrustFence trust, + GenerationResult result, + String apiDigest, + String apiRevision) { + this.binding = binding; + this.trust = trust; + this.result = result; + this.apiDigest = apiDigest; + this.apiRevision = apiRevision; + } + + /** Completes the existing readiness prerequisites; the caller invokes its real PREPARED owner. */ + public void completeReadiness( + AccountJwtReadinessProbeRepository readiness, + TransactionTemplate transaction, + DSLContext dsl, + Path privateMount, + Path publicMount) + throws Exception { + ObservationContext context = + inTransaction( + transaction, () -> readiness.readCurrentInventoryObservationContext(binding, trust)); + long plannedAt = + databaseNow(dsl) + - AccountJwtReadinessProbeRepository.MAX_VALIDATOR_CACHE_AGE_SECONDS + - AccountJwtReadinessProbeRepository.PROBE_LIFETIME_SECONDS + + 300; + Instant planningTime = Instant.ofEpochSecond(plannedAt); + ReadinessProbePlan plan = + inTransaction( + transaction, + () -> + readiness.planCurrent( + binding, + trust, + planningTime, + completeInventorySnapshot(planningTime, context))); + var identity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + result.operationId().toString(), + result.targetGeneration(), + result.targetKid(), + result.publicKeyFingerprint()); + assertThat( + completeRemainingProbes( + readiness, + transaction, + dsl, + plan, + currentInventory(dsl, context), + privateMount, + publicMount, + identity)) + .isEqualTo(12L); + assertThat( + inTransaction( + transaction, + () -> + readiness.readCurrentPromotionPrerequisites( + binding, trust, result.operationId(), currentInventory(dsl, context)))) + .isPresent(); + } + + public InventorySnapshot currentInventory(DSLContext dsl, ObservationContext context) { + return completeInventorySnapshot(Instant.ofEpochSecond(databaseNow(dsl)), context); + } + + private static T inTransaction(TransactionTemplate transaction, Supplier operation) { + return transaction.execute(status -> operation.get()); + } + + private static long databaseNow(DSLContext dsl) { + return java.util.Objects.requireNonNull( + dsl.resultQuery("SELECT floor(extract(epoch FROM clock_timestamp()))::bigint") + .fetchOne(0, Long.class)); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 is required for readiness proof", failure); + } + } + + private long completeRemainingProbes( + AccountJwtReadinessProbeRepository readiness, + TransactionTemplate transaction, + DSLContext dsl, + ReadinessProbePlan plan, + InventorySnapshot inventory, + Path privateMount, + Path publicMount, + AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity) + throws Exception { + long expectedPodReceiptCount = 0; + for (ProbeEntry planned : plan.entries()) { + ProbeEntry current = + inTransaction( + transaction, + () -> readiness.readCurrentPlan(binding, trust, result.operationId())) + .entries() + .stream() + .filter(entry -> entry.jti().equals(planned.jti())) + .findFirst() + .orElseThrow(); + if (current.state() == ProbeState.VERIFIED) { + continue; + } + var signingSpec = + new AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec( + current.validatorId(), + current.probeKind(), + current.tokenProfile(), + current.audience(), + current.jti(), + current.targetGeneration(), + current.targetKid(), + current.plannedIssuedAtEpochSecond(), + current.expiresAtEpochSecond()); + Instant plannedAt = Instant.ofEpochSecond(current.plannedIssuedAtEpochSecond()); + AccountMountedJwtSignerBundle.signReadinessProbeDigest( + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json"), + expectedIdentity, + signingSpec, + (digest, compactJwt) -> { + inTransaction( + transaction, + () -> readiness.recordSigningAttempt(binding, trust, digest, plannedAt)); + inTransaction( + transaction, () -> readiness.recordIssued(binding, trust, digest, plannedAt)); + }); + ProbeEntry issued = + inTransaction( + transaction, + () -> readiness.readCurrentPlan(binding, trust, result.operationId())) + .entries() + .stream() + .filter(entry -> entry.jti().equals(planned.jti())) + .findFirst() + .orElseThrow(); + ProbeEntry issuedForInventory = issued; + List pods = + inTransaction( + transaction, + () -> + readiness.readCurrentExpectedPods(binding, trust, issuedForInventory, inventory)); + expectedPodReceiptCount += pods.size(); + for (ExpectedPod pod : pods) { + ProbeEntry currentEvidence = issued; + var acceptance = testAcceptance(currentEvidence, pod, databaseNow(dsl)); + issued = + inTransaction( + transaction, + () -> + readiness.recordPodAcceptance( + binding, trust, currentEvidence, pod, acceptance, inventory)); + } + assertThat(issued.state()).isEqualTo(ProbeState.VERIFIED); + } + return expectedPodReceiptCount; + } + + private static AuthenticatedAcceptance testAcceptance( + ProbeEntry entry, ExpectedPod expectedPod, long observedAtEpochSecond) { + return testAcceptance(entry, expectedPod, observedAtEpochSecond, entry.targetKid()); + } + + private static AuthenticatedAcceptance testAcceptance( + ProbeEntry entry, ExpectedPod expectedPod, long observedAtEpochSecond, String verifiedKid) { + return testAcceptance( + entry, + expectedPod, + observedAtEpochSecond, + verifiedKid, + expectedPod.target().exactPodEndpoint().orElseThrow().toString()); + } + + private static AuthenticatedAcceptance testAcceptance( + ProbeEntry entry, + ExpectedPod expectedPod, + long observedAtEpochSecond, + String verifiedKid, + String actualPodEndpoint) { + var target = expectedPod.target(); + return AccountJwtReadinessReceiverInvocationPort.authenticatedAcceptance( + target.podUid(), + actualPodEndpoint, + target.image(), + target.verifierConfigSha256(), + target.canonicalServiceUri().orElseThrow(), + target.podLeafSpkiSha256().orElseThrow(), + entry.jti(), + entry.compactTokenSha256().orElseThrow(), + verifiedKid, + target.expectation(), + observedAtEpochSecond); + } + + public InventorySnapshot completeInventorySnapshot( + Instant observedAt, ObservationContext observationContext) { + return completeInventorySnapshot(observedAt, "10.11.0.11", observationContext); + } + + public InventorySnapshot completeInventorySnapshot( + Instant observedAt, String firstAccountPodIp, ObservationContext observationContext) { + String accountImage = "registry.example/account-validator@sha256:" + "1".repeat(64); + String gameSessionImage = "registry.example/game-session-validator@sha256:" + "3".repeat(64); + String accountConfigDigest = "2".repeat(64); + String gameSessionConfigDigest = "4".repeat(64); + String accountServiceUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator"; + String gameSessionServiceUri = "spiffe://firemud/ns/firemud-prod/sa/game-session-jwt-validator"; + List accountProfiles = + List.of( + new ProfileExpectation("control-ui", "control-ui"), + new ProfileExpectation("game-session-account-delegation", "account-service"), + new ProfileExpectation("player-bootstrap", "player-bootstrap")); + List gameSessionProfiles = + List.of(new ProfileExpectation("game-session-account-delegation", "account-service")); + List accountPods = + List.of( + inventoryPod( + "account-a", + "77777777-7777-4777-8777-777777777777", + "account-rs", + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "acct1", + firstAccountPodIp, + 9443, + accountImage, + accountConfigDigest, + accountServiceUri, + "5".repeat(64)), + inventoryPod( + "account-b", + "88888888-8888-4888-8888-888888888888", + "account-rs", + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "acct1", + "10.11.0.12", + 9443, + accountImage, + accountConfigDigest, + accountServiceUri, + "6".repeat(64))); + List gameSessionPods = + List.of( + inventoryPod( + "game-session-a", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "game-session-rs", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "games", + "10.12.0.11", + 9444, + gameSessionImage, + gameSessionConfigDigest, + gameSessionServiceUri, + "7".repeat(64))); + List validators = + List.of( + new ValidatorObservation( + "account-service", + "account-service", + "66666666-6666-4666-8666-666666666666", + 1L, + "51", + 2, + accountImage, + accountConfigDigest, + 300, + accountProfiles, + accountPods, + List.of()), + new ValidatorObservation( + "game-session-service", + "game-session-service", + "99999999-9999-4999-8999-999999999999", + 1L, + "52", + 1, + gameSessionImage, + gameSessionConfigDigest, + 300, + gameSessionProfiles, + gameSessionPods, + List.of())); + List> validatorMaps = + List.of( + inventoryValidatorMap(validators.get(0), accountServiceUri, 9443), + inventoryValidatorMap(validators.get(1), gameSessionServiceUri, 9444)); + Map preimage = new LinkedHashMap<>(); + preimage.put("domain", "firemud-account-validator-inventory/v2"); + preimage.put("environmentId", binding.environmentId()); + preimage.put("clusterId", binding.clusterId()); + preimage.put("clusterIncarnationUid", trust.expectedClusterIncarnationUid()); + preimage.put("namespace", binding.namespace()); + preimage.put("namespaceUid", trust.expectedNamespaceUid()); + preimage.put("apiBindingRevision", apiRevision); + preimage.put("apiBindingDigest", apiDigest); + preimage.put("inventoryBindingRevision", "inventory-r1"); + preimage.put("inventoryBindingDigest", "d".repeat(64)); + preimage.put( + "observationContext", + Map.of( + "purpose", observationContext.purpose().name(), + "operationId", observationContext.operationId().toString(), + "operationDigest", observationContext.operationDigest())); + preimage.put("validators", validatorMaps); + byte[] bytes; + try { + bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + } catch (Exception failure) { + throw new AssertionError(failure); + } + InventorySnapshot snapshot = mock(InventorySnapshot.class); + when(snapshot.observedAt()).thenReturn(observedAt); + when(snapshot.environmentId()).thenReturn(binding.environmentId()); + when(snapshot.clusterId()).thenReturn(binding.clusterId()); + when(snapshot.clusterIncarnationUid()).thenReturn(trust.expectedClusterIncarnationUid()); + when(snapshot.namespace()).thenReturn(binding.namespace()); + when(snapshot.namespaceUid()).thenReturn(trust.expectedNamespaceUid()); + when(snapshot.apiBindingRevision()).thenReturn(apiRevision); + when(snapshot.apiBindingDigest()).thenReturn(apiDigest); + when(snapshot.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(snapshot.inventoryBindingDigest()).thenReturn("d".repeat(64)); + when(snapshot.observationContext()).thenReturn(Optional.of(observationContext)); + when(snapshot.validators()).thenReturn(validators); + when(snapshot.canonicalBytes()).thenReturn(bytes.clone()); + when(snapshot.digest()).thenReturn(sha256(bytes)); + return snapshot; + } + + private PodObservation inventoryPod( + String name, + String uid, + String ownerName, + String ownerUid, + String podTemplateHash, + String podIp, + int receiverPort, + String image, + String configDigest, + String serviceUri, + String spkiDigest) { + String host = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + return new PodObservation( + name, + uid, + "11", + ownerName, + ownerUid, + podTemplateHash, + image, + configDigest, + podIp, + URI.create("grpcs://" + host + ":" + receiverPort), + serviceUri, + spkiDigest); + } + + private Map inventoryValidatorMap( + ValidatorObservation validator, String serviceUri, int receiverPort) { + Map result = new LinkedHashMap<>(); + result.put("validatorId", validator.validatorId()); + result.put("deploymentName", validator.deploymentName()); + result.put("deploymentUid", validator.deploymentUid()); + result.put("deploymentGeneration", Long.toString(validator.deploymentGeneration())); + result.put("deploymentResourceVersion", validator.deploymentResourceVersion()); + result.put("replicas", Integer.toString(validator.replicas())); + result.put("image", validator.image()); + result.put("verifierConfigSha256", validator.verifierConfigSha256()); + result.put("maxCacheAgeSeconds", Integer.toString(validator.maxCacheAgeSeconds())); + result.put( + "profiles", + validator.profiles().stream() + .map( + profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList()); + result.put( + "pods", + validator.pods().stream() + .map( + pod -> + Map.ofEntries( + Map.entry("name", pod.name()), + Map.entry("uid", pod.uid()), + Map.entry("resourceVersion", pod.resourceVersion()), + Map.entry("ownerReplicaSetName", pod.ownerName()), + Map.entry("ownerReplicaSetUid", pod.ownerUid()), + Map.entry("podTemplateHash", pod.podTemplateHash()), + Map.entry("image", pod.image()), + Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), + Map.entry("podIp", pod.podIp()), + Map.entry("exactPodEndpoint", pod.endpoint().toString()), + Map.entry("canonicalServiceUri", pod.receiverServiceUri()), + Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) + .toList()); + result.put("receiverServiceUri", serviceUri); + result.put("receiverPort", receiverPort); + result.put("replicaSets", List.of()); + return result; + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java index ee80fbbff7..0564d01eab 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksCache.java @@ -22,6 +22,8 @@ import java.util.Map; import java.util.Objects; import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.regex.Pattern; import tools.jackson.core.StreamReadFeature; import tools.jackson.core.type.TypeReference; @@ -64,8 +66,12 @@ public final class AccountPublicJwksCache { private final Map rememberedFingerprints = new LinkedHashMap<>(); private final Set hardDeniedKids = new LinkedHashSet<>(); + private RefreshFlight inFlight; private Map keys = Map.of(); private boolean hardCutoverQuarantined; + private boolean sourceRejected; + private boolean preparedDenied; + private long observedPreparedDenyEpoch; private Instant loadedAt; private String loadedJwksFingerprint; private Instant lastUnknownKidRefreshAt; @@ -93,11 +99,31 @@ public AccountPublicJwksCache( * Returns a currently usable key; unknown-kid lookups can trigger at most one refresh per second. */ public RSAPublicKey keyFor(String kid) { + return lookupKey(kid, null, null); + } + + /** + * Returns a key only from the exact protected source and JWKS bytes observed by the caller. + * Ordinary cache refresh and denial rules still apply; a binding mismatch does not force a load. + */ + public RSAPublicKey keyFor(String kid, SourceIdentity requiredSource, String requiredJwksSha256) { + if (requiredSource == null + || requiredJwksSha256 == null + || !SHA256.matcher(requiredJwksSha256).matches()) { + throw new InvalidJwksException(); + } + return lookupKey(kid, requiredSource, requiredJwksSha256); + } + + private RSAPublicKey lookupKey( + String kid, SourceIdentity requiredSource, String requiredJwksSha256) { if (kid == null || !KID.matcher(kid).matches()) { throw new UnknownKeyException(); } + final RefreshRequest refresh; synchronized (monitor) { rejectHardDenied(kid); + rejectSource(); Instant now = clock.instant(); boolean cachedKidKnown = keys.containsKey(kid); if (!cachedKidKnown && loadedAt != null) { @@ -105,7 +131,8 @@ public RSAPublicKey keyFor(String kid) { throw new UnknownKeyException(); } } - if (!isFresh(now) + boolean fresh = isFresh(now); + if (!fresh && lastStaleRefreshFailureAt != null && !now.isBefore(lastStaleRefreshFailureAt) && Duration.between(lastStaleRefreshFailureAt, now).compareTo(STALE_SOURCE_RETRY_BACKOFF) @@ -115,76 +142,47 @@ public RSAPublicKey keyFor(String kid) { } throw staleRefreshFailureException(); } - if (isFresh(now)) { - RSAPublicKey existing = keys.get(kid); - if (existing != null) { - return existing; + if (fresh) { + if (cachedKidKnown) { + return boundKey(kid, requiredSource, requiredJwksSha256); } - if (!unknownKidsRefreshedForSnapshot.contains(kid) - && unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) { - recordUnknownKidRefresh(kid, now); - refreshFromSource(); - rejectHardDenied(kid); - RSAPublicKey refreshed = keys.get(kid); - if (refreshed != null) { - return refreshed; - } - if (unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) { - unknownKidsRefreshedForSnapshot.add(kid); - } + if (unknownKidsRefreshedForSnapshot.contains(kid) + || unknownKidsRefreshedForSnapshot.size() >= MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) { + throw new UnknownKeyException(); } - throw new UnknownKeyException(); } - - try { - if (!cachedKidKnown && loadedAt != null) { - recordUnknownKidRefresh(kid, now); - } - refreshFromSource(); - } catch (SourceUnavailableException unavailable) { - recordStaleRefreshFailure(StaleRefreshFailure.SOURCE_UNAVAILABLE); - if (loadedAt != null - && !cachedKidKnown - && unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) { - unknownKidsRefreshedForSnapshot.add(kid); - } - throw unavailable; - } catch (InvalidJwksException invalid) { - recordStaleRefreshFailure(StaleRefreshFailure.INVALID_JWKS); - throw invalid; + if (!cachedKidKnown && loadedAt != null) { + recordUnknownKidRefresh(kid, now); } + refresh = beginRefresh(false, !fresh); + } + refreshFromSource(refresh); + synchronized (monitor) { rejectHardDenied(kid); - RSAPublicKey refreshed = keys.get(kid); - if (refreshed == null) { - if (unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) { - unknownKidsRefreshedForSnapshot.add(kid); - } - throw new UnknownKeyException(); + rejectSource(); + if (!isFresh(clock.instant())) { + throw new SourceUnavailableException(); } - return refreshed; + return boundKey(kid, requiredSource, requiredJwksSha256); } } - /** - * Returns a key only from the exact protected source and JWKS bytes observed by the caller. - * Ordinary cache refresh and denial rules still apply; a binding mismatch does not force a load. - */ - public RSAPublicKey keyFor(String kid, SourceIdentity requiredSource, String requiredJwksSha256) { - if (requiredSource == null - || requiredJwksSha256 == null - || !SHA256.matcher(requiredJwksSha256).matches()) { - throw new InvalidJwksException(); - } - synchronized (monitor) { - RSAPublicKey key = keyFor(kid); - // Every installed snapshot has already matched expectedSource. Keep the lookup and - // comparison under the same monitor so a concurrent refresh cannot relabel this key. - if (!expectedSource.equals(requiredSource) - || !requiredJwksSha256.equals(loadedJwksFingerprint)) { - throw new InvalidJwksException(); + // Call only under monitor, so neither the key nor its binding can change during this comparison. + private RSAPublicKey boundKey( + String kid, SourceIdentity requiredSource, String requiredJwksSha256) { + RSAPublicKey key = keys.get(kid); + if (key == null) { + if (unknownKidsRefreshedForSnapshot.size() < MAX_UNKNOWN_KID_REFRESHES_PER_SNAPSHOT) { + unknownKidsRefreshedForSnapshot.add(kid); } - return key; + throw new UnknownKeyException(); } + if (requiredSource != null + && (!expectedSource.equals(requiredSource) + || !requiredJwksSha256.equals(loadedJwksFingerprint))) { + throw new InvalidJwksException(); + } + return key; } /** @@ -208,6 +206,67 @@ public void invalidateKid(String kid) { } } + /** + * Explicit proactive refresh for an owning service's bounded lifecycle task. A temporary outage + * preserves the original age and finite fresh-key exception. Invalid authenticated source or key + * evidence permanently refuses this cache instance, including previously known keys; only an + * explicitly requalified replacement instance may resume. Deny history remains independent. + */ + public void refresh() { + final RefreshRequest refresh; + synchronized (monitor) { + rejectTerminalSource(); + refresh = beginRefresh(true, false); + } + refreshFromSource(refresh); + } + + private void rejectTerminalSource() { + sourceRejected |= source.isCustodyRejected(); + if (sourceRejected) throw new InvalidJwksException(); + } + + private void observePreparedDenial() { + // A separate source observation can deny while our older refresh is in flight. + // This is a local nonblocking state query, never source I/O. + long epoch = source.preparedDenyEpoch(); + if (epoch < observedPreparedDenyEpoch || epoch < 0) { + sourceRejected = true; + throw new InvalidJwksException(); + } + if (epoch != observedPreparedDenyEpoch) { + observedPreparedDenyEpoch = epoch; + preparedDenied = true; + } + if (source.isPreparedDenied()) preparedDenied = true; + } + + private void rejectSource() { + rejectTerminalSource(); + observePreparedDenial(); + if (preparedDenied) throw new SourcePreparedDenyException(); + } + + // All refresh triggers share one flight. No older load can install after a newer load, and + // joining a proactive refresh retains its stricter terminal-rejection behavior. + private RefreshRequest beginRefresh(boolean proactive, boolean stale) { + boolean owner = inFlight == null; + if (owner) { + inFlight = new RefreshFlight(); + } + inFlight.proactive |= proactive; + inFlight.stale |= stale; + return new RefreshRequest(inFlight, owner); + } + + private static final class RefreshFlight { + private final CompletableFuture completion = new CompletableFuture<>(); + private boolean proactive; + private boolean stale; + } + + private record RefreshRequest(RefreshFlight flight, boolean owner) {} + /** Exposes only the non-secret source pin for integration correspondence checks. */ public SourceIdentity sourceIdentity() { return expectedSource; @@ -235,19 +294,89 @@ private void recordUnknownKidRefresh(String kid, Instant now) { } } - private void refreshFromSource() { - final PublicJwksSnapshot snapshot; + private void refreshFromSource(RefreshRequest request) { + RefreshFlight flight = request.flight(); + if (request.owner()) { + PublicJwksSnapshot snapshot = null; + RuntimeException sourceFailure = null; + try { + // Never hold monitor over remote I/O, including demand-triggered source reads. + snapshot = source.load(); + } catch (RuntimeException failure) { + sourceFailure = failure; + } catch (Error failure) { + synchronized (monitor) { + inFlight = null; + flight.completion.completeExceptionally(failure); + } + throw failure; + } + synchronized (monitor) { + try { + installSnapshot(snapshot, sourceFailure); + flight.completion.complete(null); + } catch (RuntimeException failure) { + RuntimeException reported = failure; + if (!(failure instanceof SourceUnavailableException) + && !(failure instanceof SourcePreparedDenyException)) { + sourceRejected |= flight.proactive; + reported = new InvalidJwksException(); + } + if (flight.stale && !(reported instanceof SourcePreparedDenyException)) { + recordStaleRefreshFailure( + reported instanceof SourceUnavailableException + ? StaleRefreshFailure.SOURCE_UNAVAILABLE + : StaleRefreshFailure.INVALID_JWKS); + } + flight.completion.completeExceptionally(reported); + } catch (Error failure) { + flight.completion.completeExceptionally(failure); + throw failure; + } finally { + inFlight = null; + } + } + } try { - snapshot = source.load(); - } catch (SourceUnavailableException unavailable) { - if (loadedAt == null || !isFresh(clock.instant())) { + flight.completion.join(); + } catch (CompletionException failure) { + if (failure.getCause() instanceof RuntimeException cause) { + throw cause; + } + if (failure.getCause() instanceof Error cause) { + throw cause; + } + throw new InvalidJwksException(); + } + } + + // Source identity, freshness, remembered fingerprints, and invalidation history are checked + // atomically against the current state, including invalidations made while the load was blocked. + private void installSnapshot(PublicJwksSnapshot snapshot, RuntimeException sourceFailure) { + rejectTerminalSource(); + observePreparedDenial(); + if (sourceFailure instanceof SourcePreparedDenyException) { + preparedDenied = true; + throw new SourcePreparedDenyException(); + } + if (sourceFailure instanceof SourceUnavailableException) { + if (preparedDenied) throw new SourcePreparedDenyException(); + if (!isFresh(clock.instant())) { throw new SourceUnavailableException(); } return; - } catch (RuntimeException invalidSource) { + } + if (sourceFailure instanceof SourceCustodyRejectedException) { + sourceRejected = true; + } + if (sourceFailure != null) { + throw new InvalidJwksException(); + } + if (snapshot == null) { throw new InvalidJwksException(); } - if (snapshot == null || !expectedSource.equals(snapshot.sourceIdentity())) { + if (!expectedSource.equals(snapshot.sourceIdentity())) { + sourceRejected = true; throw new InvalidJwksException(); } @@ -264,8 +393,18 @@ private void refreshFromSource() { throw new InvalidJwksException(); } } + rejectTerminalSource(); + observePreparedDenial(); + if (preparedDenied + && (!snapshot.committedRecoveryEligible() + || snapshot.preparedDenyEpoch() != observedPreparedDenyEpoch + || source.isPreparedDenied())) { + throw new SourcePreparedDenyException(); + } + preparedDenied = false; rememberedFingerprints.clear(); rememberedFingerprints.putAll(nextFingerprints); + parsed.keySet().removeAll(hardDeniedKids); keys = Collections.unmodifiableMap(parsed); String nextJwksFingerprint = fingerprintBytes(snapshotBytes); if (!Objects.equals(loadedJwksFingerprint, nextJwksFingerprint)) { @@ -295,6 +434,11 @@ private void rejectHardDenied(String kid) { } } + /** Validates the public-key profile without installing trust or changing any cache state. */ + public static void validatePublicJwks(byte[] bytes) { + parseJwks(bytes); + } + private static Map parseJwks(byte[] bytes) { if (bytes == null || bytes.length == 0 || bytes.length > MAX_JWKS_BYTES) { throw new InvalidJwksException(); @@ -482,12 +626,41 @@ private static boolean validApiOrigin(String value) { @FunctionalInterface public interface TrustedPublicJwksSource { PublicJwksSnapshot load() throws SourceUnavailableException; + + /** Nonblocking local latch observation; implementations must not perform I/O here. */ + default boolean isPreparedDenied() { + return false; + } + + /** Nonblocking terminal custody observation; once observed a cache can never recover. */ + default boolean isCustodyRejected() { + return false; + } + + /** Monotonic local epoch retains a deny event even after a later source recovery. */ + default long preparedDenyEpoch() { + return 0; + } } /** A single exact public ConfigMap data value plus its independently established source pin. */ - public record PublicJwksSnapshot(SourceIdentity sourceIdentity, byte[] jwksBytes) { + public record PublicJwksSnapshot( + SourceIdentity sourceIdentity, + byte[] jwksBytes, + boolean committedRecoveryEligible, + long preparedDenyEpoch) { + public PublicJwksSnapshot(SourceIdentity sourceIdentity, byte[] jwksBytes) { + this(sourceIdentity, jwksBytes, false, 0); + } + + public PublicJwksSnapshot( + SourceIdentity sourceIdentity, byte[] jwksBytes, boolean committedRecoveryEligible) { + this(sourceIdentity, jwksBytes, committedRecoveryEligible, 0); + } + public PublicJwksSnapshot { Objects.requireNonNull(sourceIdentity, "source identity is required"); + if (preparedDenyEpoch < 0) throw new IllegalArgumentException("Invalid source deny epoch"); jwksBytes = jwksBytes == null ? null : jwksBytes.clone(); } @@ -503,6 +676,20 @@ public SourceUnavailableException() { } } + /** Verified PREPARED quarantine; only exact committed owner and mount proof may recover it. */ + public static final class SourcePreparedDenyException extends RuntimeException { + public SourcePreparedDenyException() { + super("Account public JWKS source is prepared and denied"); + } + } + + /** Terminal custody refusal from a trusted source; never the finite-outage exception. */ + public static final class SourceCustodyRejectedException extends RuntimeException { + public SourceCustodyRejectedException() { + super("Account public JWKS source custody is rejected"); + } + } + public static final class InvalidJwksException extends RuntimeException { public InvalidJwksException() { super("Account public JWKS source data is invalid"); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksReadCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksReadCodec.java new file mode 100644 index 0000000000..f546bbc253 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountPublicJwksReadCodec.java @@ -0,0 +1,148 @@ +package net.firedevops.firemud.common.security; + +import com.google.protobuf.ByteString; +import net.firedevops.firemud.account.v1.AccountPublicJwksSourceIdentity; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksRequest; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksResponse; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksResponse.Disposition; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; + +/** Closed bounded wire frame for the private current Account public-JWKS read. */ +public final class AccountPublicJwksReadCodec { + public static final int MAX_REQUEST_BYTES = 32; + public static final int MAX_RESPONSE_BYTES = AccountPublicJwksCache.MAX_JWKS_BYTES + 2048; + private static final int SCHEMA_VERSION = 2; + + private AccountPublicJwksReadCodec() {} + + public static GetCurrentAccountPublicJwksRequest request() { + return GetCurrentAccountPublicJwksRequest.newBuilder().setSchemaVersion(SCHEMA_VERSION).build(); + } + + public static void requireRequest(GetCurrentAccountPublicJwksRequest request) { + if (request == null + || request.getSchemaVersion() != SCHEMA_VERSION + || !request.getUnknownFields().asMap().isEmpty() + || request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new InvalidFrameException(); + } + } + + /** Ordinary snapshots do not assert current committed promotion evidence. */ + public static GetCurrentAccountPublicJwksResponse response(PublicJwksSnapshot snapshot) { + if (snapshot == null) throw new InvalidFrameException(); + return response(new ReadResult(snapshot.sourceIdentity(), snapshot.jwksBytes(), false, false)); + } + + /** Producer classification comes only from Account's verified current owner evidence. */ + public static GetCurrentAccountPublicJwksResponse response(ReadResult result) { + if (result == null) throw new InvalidFrameException(); + SourceIdentity source = result.sourceIdentity(); + var identity = + AccountPublicJwksSourceIdentity.newBuilder() + .setEnvironmentId(source.environmentId()) + .setClusterId(source.clusterId()) + .setClusterIncarnationUid(source.clusterIncarnationUid()) + .setNamespace(source.namespace()) + .setNamespaceUid(source.namespaceUid()) + .setConfigMapUid(source.configMapUid()) + .setBindingRevision(source.bindingRevision()) + .setApiServerOrigin(source.apiServerOrigin()) + .setServingCaSha256(source.servingCaSha256()) + .build(); + var response = + GetCurrentAccountPublicJwksResponse.newBuilder() + .setSchemaVersion(SCHEMA_VERSION) + .setSourceIdentity(identity) + .setDisposition( + result.preparedDeny() ? Disposition.PREPARED_DENY : Disposition.SNAPSHOT); + if (!result.preparedDeny()) { + response.setPublicJwks(ByteString.copyFrom(result.jwksBytes())); + response.setCommittedRecoveryEligible(result.committedRecoveryEligible()); + } + var built = response.build(); + result(built); + return built; + } + + /** A deny is never a snapshot and cannot be mistaken for ordinary source unavailability. */ + public static PublicJwksSnapshot snapshot(GetCurrentAccountPublicJwksResponse response) { + ReadResult result = result(response); + if (result.preparedDeny()) throw new InvalidFrameException(); + return new PublicJwksSnapshot( + result.sourceIdentity(), result.jwksBytes(), result.committedRecoveryEligible()); + } + + public static ReadResult result(GetCurrentAccountPublicJwksResponse response) { + if (response == null + || response.getSchemaVersion() != SCHEMA_VERSION + || !response.hasSourceIdentity() + || !response.getUnknownFields().asMap().isEmpty() + || !response.getSourceIdentity().getUnknownFields().asMap().isEmpty() + || response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw new InvalidFrameException(); + } + boolean deny; + switch (response.getDisposition()) { + case SNAPSHOT -> { + deny = false; + if (!response.hasCommittedRecoveryEligible()) throw new InvalidFrameException(); + } + case PREPARED_DENY -> { + deny = true; + if (response.hasCommittedRecoveryEligible()) throw new InvalidFrameException(); + } + default -> throw new InvalidFrameException(); + } + var source = response.getSourceIdentity(); + try { + return new ReadResult( + new SourceIdentity( + source.getEnvironmentId(), + source.getClusterId(), + source.getClusterIncarnationUid(), + source.getNamespace(), + source.getNamespaceUid(), + source.getConfigMapUid(), + source.getBindingRevision(), + source.getApiServerOrigin(), + source.getServingCaSha256()), + response.getPublicJwks().toByteArray(), + deny, + response.getCommittedRecoveryEligible()); + } catch (IllegalArgumentException invalid) { + throw new InvalidFrameException(); + } + } + + /** Public-only owner result. Wire presence and closed-disposition checks remain in the codec. */ + public record ReadResult( + SourceIdentity sourceIdentity, + byte[] jwksBytes, + boolean preparedDeny, + boolean committedRecoveryEligible) { + public ReadResult { + if (sourceIdentity == null + || jwksBytes == null + || jwksBytes.length > AccountPublicJwksCache.MAX_JWKS_BYTES + || (preparedDeny + ? jwksBytes.length != 0 || committedRecoveryEligible + : jwksBytes.length == 0)) { + throw new InvalidFrameException(); + } + jwksBytes = jwksBytes.clone(); + } + + @Override + public byte[] jwksBytes() { + return jwksBytes.clone(); + } + } + + public static final class InvalidFrameException extends IllegalArgumentException { + public InvalidFrameException() { + super("Current Account public JWKS frame is invalid"); + } + } +} diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java index e0103e5bdd..ecdabb1343 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java @@ -11,6 +11,9 @@ import java.time.Instant; import java.time.ZoneId; import java.util.Base64; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; @@ -29,6 +32,511 @@ class AccountPublicJwksCacheTest { "https://kubernetes.example:6443", "a".repeat(64)); + @Test + void preparedDenyBlocksWarmKeysAcrossOutageAndOnlyEligibleRecoveryRenewsAge() throws Exception { + KeyPair key = rsa3072(); + String json = jwks(jwk("known", (RSAPublicKey) key.getPublic())); + AtomicReference failure = new AtomicReference<>(); + AtomicReference next = + new AtomicReference<>(snapshot(json)); + MutableClock clock = new MutableClock(INITIAL); + var cache = + cache( + clock, + () -> { + if (failure.get() != null) throw failure.get(); + return next.get(); + }); + cache.refresh(); + assertThat(cache.keyFor("known")).isEqualTo(key.getPublic()); + failure.set(new AccountPublicJwksCache.SourcePreparedDenyException()); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + failure.set(new AccountPublicJwksCache.SourceUnavailableException()); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + clock.advance(Duration.ofSeconds(11)); + failure.set(null); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + next.set( + new AccountPublicJwksCache.PublicJwksSnapshot( + PIN, json.getBytes(java.nio.charset.StandardCharsets.UTF_8), true)); + cache.refresh(); + assertThat(cache.keyFor("known")).isEqualTo(key.getPublic()); + failure.set(new AccountPublicJwksCache.SourceUnavailableException()); + clock.advance(Duration.ofSeconds(11)); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class); + } + + @Test + void separateDenyObservationPreventsOlderFlightInstallWithoutBlockingInvalidation() + throws Exception { + KeyPair key = rsa3072(); + String json = + jwks( + jwk("known", (RSAPublicKey) key.getPublic()) + + "," + + jwk("cut", (RSAPublicKey) key.getPublic())); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var denied = new java.util.concurrent.atomic.AtomicBoolean(); + var epoch = new java.util.concurrent.atomic.AtomicLong(); + AtomicInteger loads = new AtomicInteger(); + var source = + new AccountPublicJwksCache.TrustedPublicJwksSource() { + @Override + public AccountPublicJwksCache.PublicJwksSnapshot load() { + long snapshotEpoch = epoch.get(); + if (loads.incrementAndGet() == 2) { + entered.countDown(); + try { + if (!release.await(5, TimeUnit.SECONDS)) + throw new AssertionError("Release timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + } + return new AccountPublicJwksCache.PublicJwksSnapshot( + PIN, json.getBytes(java.nio.charset.StandardCharsets.UTF_8), true, snapshotEpoch); + } + + @Override + public boolean isPreparedDenied() { + return denied.get(); + } + + @Override + public long preparedDenyEpoch() { + return epoch.get(); + } + }; + var cache = cache(new MutableClock(INITIAL), source); + cache.refresh(); + try (var executor = Executors.newFixedThreadPool(2)) { + var refresh = executor.submit(cache::refresh); + try { + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + epoch.incrementAndGet(); + denied.set(true); + var invalidate = + executor.submit( + () -> { + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + cache.invalidateKid("cut"); + }); + invalidate.get(5, TimeUnit.SECONDS); + // A full source recovery cannot authorize the older cache flight's pre-deny bytes. + denied.set(false); + } finally { + release.countDown(); + } + assertThatThrownBy(() -> refresh.get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + } + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + denied.set(false); + cache.refresh(); + assertThat(cache.keyFor("known")).isEqualTo(key.getPublic()); + assertThatThrownBy(() -> cache.keyFor("cut")) + .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class); + } + + @Test + void separateCustodyObservationPreventsOlderFlightInstallAndCachedReads() throws Exception { + KeyPair key = rsa3072(); + String json = jwks(jwk("known", (RSAPublicKey) key.getPublic())); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var terminal = new java.util.concurrent.atomic.AtomicBoolean(); + AtomicInteger loads = new AtomicInteger(); + var source = + new AccountPublicJwksCache.TrustedPublicJwksSource() { + @Override + public AccountPublicJwksCache.PublicJwksSnapshot load() { + if (loads.incrementAndGet() == 2) { + entered.countDown(); + try { + if (!release.await(5, TimeUnit.SECONDS)) + throw new AssertionError("Release timed out"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + } + return snapshot(json); + } + + @Override + public boolean isCustodyRejected() { + return terminal.get(); + } + }; + var cache = cache(new MutableClock(INITIAL), source); + cache.refresh(); + try (var executor = Executors.newSingleThreadExecutor()) { + var refresh = executor.submit(cache::refresh); + try { + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + terminal.set(true); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + } finally { + release.countDown(); + } + assertThatThrownBy(() -> refresh.get(5, TimeUnit.SECONDS)) + .hasCauseInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + } + terminal.set(false); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + } + + @Test + void terminalCustodyFailureDuringPreparedDenyCannotRecover() throws Exception { + KeyPair key = rsa3072(); + String json = jwks(jwk("known", (RSAPublicKey) key.getPublic())); + AtomicReference failure = + new AtomicReference<>(new AccountPublicJwksCache.SourcePreparedDenyException()); + var cache = + cache( + new MutableClock(INITIAL), + () -> { + if (failure.get() != null) throw failure.get(); + return new AccountPublicJwksCache.PublicJwksSnapshot( + PIN, json.getBytes(java.nio.charset.StandardCharsets.UTF_8), true); + }); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + failure.set(new AccountPublicJwksCache.SourceCustodyRejectedException()); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + failure.set(null); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + } + + @Test + void blockedProactiveLoadAllowsFreshBoundReadsAndImmediateInvalidation() throws Exception { + KeyPair key = rsa3072(); + String first = jwks(jwk("known", (RSAPublicKey) key.getPublic())); + String second = first + "\n"; + var source = new BlockingSource(snapshot(first), () -> snapshot(second)); + var cache = cache(new MutableClock(INITIAL), source); + cache.refresh(); + try (var executor = Executors.newFixedThreadPool(2)) { + var refresh = executor.submit(cache::refresh); + try { + assertThat(source.entered.await(5, TimeUnit.SECONDS)).isTrue(); + var readAndInvalidate = + executor.submit( + () -> { + assertThat(cache.keyFor("known", PIN, sha256(first))).isEqualTo(key.getPublic()); + assertThatThrownBy(() -> cache.keyFor("known", PIN, sha256(second))) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + cache.invalidateKid("known"); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class); + return null; + }); + readAndInvalidate.get(5, TimeUnit.SECONDS); + } finally { + source.release.countDown(); + } + refresh.get(5, TimeUnit.SECONDS); + } + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class); + assertThat(source.loads).hasValue(2); + } + + @Test + void proactiveUnknownAndStaleRequestsShareOneFlightInEitherOrder() throws Exception { + KeyPair key = rsa3072(); + String first = jwks(jwk("known", (RSAPublicKey) key.getPublic())); + String second = + jwks( + jwk("known", (RSAPublicKey) key.getPublic()) + + "," + + jwk("rotated", (RSAPublicKey) key.getPublic())); + for (boolean demandFirst : new boolean[] {false, true}) { + var source = new BlockingSource(snapshot(first), () -> snapshot(second)); + MutableClock clock = new MutableClock(INITIAL); + var cache = cache(clock, source); + cache.refresh(); + try (var executor = Executors.newFixedThreadPool(3)) { + var firstRequest = + executor.submit( + () -> { + if (demandFirst) { + assertThat(cache.keyFor("rotated", PIN, sha256(second))) + .isEqualTo(key.getPublic()); + } else { + cache.refresh(); + } + return null; + }); + try { + assertThat(source.entered.await(5, TimeUnit.SECONDS)).isTrue(); + AtomicReference proactiveThread = new AtomicReference<>(); + var proactive = + executor.submit( + () -> { + proactiveThread.set(Thread.currentThread()); + cache.refresh(); + }); + awaitWaiting(proactiveThread); + clock.advance(Duration.ofSeconds(11)); + AtomicReference staleThread = new AtomicReference<>(); + var stale = + executor.submit( + () -> { + staleThread.set(Thread.currentThread()); + return cache.keyFor("known", PIN, sha256(second)); + }); + awaitWaiting(staleThread); + assertThat(source.loads).hasValue(2); + source.release.countDown(); + firstRequest.get(5, TimeUnit.SECONDS); + proactive.get(5, TimeUnit.SECONDS); + assertThat(stale.get(5, TimeUnit.SECONDS)).isEqualTo(key.getPublic()); + } finally { + source.release.countDown(); + } + } + assertThat(source.loads).hasValue(2); + assertThatThrownBy(() -> cache.keyFor("known", PIN, sha256(first))) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + assertThat(cache.keyFor("rotated", PIN, sha256(second))).isEqualTo(key.getPublic()); + } + } + + @Test + void proactiveJoinPermanentlyRejectsInvalidDemandFlight() throws Exception { + KeyPair key = rsa3072(); + var first = snapshot(jwks(jwk("known", (RSAPublicKey) key.getPublic()))); + var source = new BlockingSource(first, () -> snapshot("{\"keys\":[]}")); + var cache = cache(new MutableClock(INITIAL), source); + cache.refresh(); + try (var executor = Executors.newFixedThreadPool(2)) { + var demand = + executor.submit( + () -> + assertThatThrownBy(() -> cache.keyFor("unknown")) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class)); + try { + assertThat(source.entered.await(5, TimeUnit.SECONDS)).isTrue(); + AtomicReference proactiveThread = new AtomicReference<>(); + var proactive = + executor.submit( + () -> { + proactiveThread.set(Thread.currentThread()); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + }); + awaitWaiting(proactiveThread); + source.release.countDown(); + demand.get(5, TimeUnit.SECONDS); + proactive.get(5, TimeUnit.SECONDS); + } finally { + source.release.countDown(); + } + } + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + assertThat(source.loads).hasValue(2); + } + + @Test + void blockedRefreshOutageCannotUseSnapshotThatExpiredDuringLoad() throws Exception { + KeyPair key = rsa3072(); + var first = snapshot(jwks(jwk("known", (RSAPublicKey) key.getPublic()))); + var source = + new BlockingSource( + first, + () -> { + throw new AccountPublicJwksCache.SourceUnavailableException(); + }); + MutableClock clock = new MutableClock(INITIAL); + var cache = cache(clock, source); + cache.refresh(); + try (var executor = Executors.newSingleThreadExecutor()) { + var refresh = + executor.submit( + () -> + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class)); + try { + assertThat(source.entered.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(cache.keyFor("known")).isEqualTo(key.getPublic()); + clock.advance(Duration.ofSeconds(11)); + } finally { + source.release.countDown(); + } + refresh.get(5, TimeUnit.SECONDS); + } + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class); + } + + private static void awaitWaiting(AtomicReference thread) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while ((thread.get() == null || thread.get().getState() != Thread.State.WAITING) + && System.nanoTime() < deadline) { + Thread.sleep(1); + } + assertThat(thread.get()).isNotNull(); + assertThat(thread.get().getState()).isEqualTo(Thread.State.WAITING); + } + + private static final class BlockingSource + implements AccountPublicJwksCache.TrustedPublicJwksSource { + private final AccountPublicJwksCache.PublicJwksSnapshot initial; + private final AccountPublicJwksCache.TrustedPublicJwksSource next; + private final CountDownLatch entered = new CountDownLatch(1); + private final CountDownLatch release = new CountDownLatch(1); + private final AtomicInteger loads = new AtomicInteger(); + + private BlockingSource( + AccountPublicJwksCache.PublicJwksSnapshot initial, + AccountPublicJwksCache.TrustedPublicJwksSource next) { + this.initial = initial; + this.next = next; + } + + @Override + public AccountPublicJwksCache.PublicJwksSnapshot load() { + if (loads.incrementAndGet() == 1) return initial; + entered.countDown(); + try { + if (!release.await(30, TimeUnit.SECONDS)) { + throw new AssertionError("source release timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError(interrupted); + } + return next.load(); + } + } + + @Test + void unknownKidCustodyRejectionImmediatelyLatchesKnownKeysAndLaterRefresh() throws Exception { + KeyPair key = rsa3072(); + var accepted = snapshot(jwks(jwk("known", (RSAPublicKey) key.getPublic()))); + for (boolean typedCustodyRejection : new boolean[] {true, false}) { + MutableClock clock = new MutableClock(INITIAL); + AtomicInteger loads = new AtomicInteger(); + AtomicReference current = + new AtomicReference<>(accepted); + AtomicReference custodyRejected = new AtomicReference<>(false); + var cache = + cache( + clock, + () -> { + loads.incrementAndGet(); + if (typedCustodyRejection && custodyRejected.get()) { + throw new AccountPublicJwksCache.SourceCustodyRejectedException(); + } + return current.get(); + }); + assertThat(cache.keyFor("known")).isEqualTo(key.getPublic()); + custodyRejected.set(true); + current.set(new AccountPublicJwksCache.PublicJwksSnapshot(otherPin(), accepted.jwksBytes())); + assertThatThrownBy(() -> cache.keyFor("unknown")) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + // Neither a restored source nor another lookup can silently requalify a rejected instance. + custodyRejected.set(false); + current.set(accepted); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + assertThat(loads).hasValue(2); + } + } + + @Test + void proactiveRefreshOutagesNeverExtendAgeAndDeniedKidsStayDenied() throws Exception { + KeyPair key = rsa3072(); + MutableClock clock = new MutableClock(INITIAL); + AtomicReference current = + new AtomicReference<>( + () -> + snapshot( + jwks( + jwk("known", (RSAPublicKey) key.getPublic()) + + "," + + jwk("denied", (RSAPublicKey) key.getPublic())))); + var cache = cache(clock, () -> current.get().load()); + cache.refresh(); + cache.invalidateKid("denied"); + current.set( + () -> { + throw new AccountPublicJwksCache.SourceUnavailableException(); + }); + clock.advance(Duration.ofSeconds(3)); + cache.refresh(); + clock.advance(Duration.ofSeconds(3)); + cache.refresh(); + assertThat(cache.keyFor("known")).isEqualTo(key.getPublic()); + assertThatThrownBy(() -> cache.keyFor("denied")) + .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class); + clock.advance(Duration.ofSeconds(5)); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class); + assertThatThrownBy(() -> cache.keyFor("denied")) + .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class); + } + + @Test + void proactiveInvalidSourcePermanentlyRefusesFreshKnownAndUnknownKids() throws Exception { + KeyPair key = rsa3072(); + var valid = snapshot(jwks(jwk("known", (RSAPublicKey) key.getPublic()))); + var changed = new AccountPublicJwksCache.PublicJwksSnapshot(otherPin(), valid.jwksBytes()); + for (var invalid : + new AccountPublicJwksCache.PublicJwksSnapshot[] { + changed, + snapshot("{\"keys\":[]}"), + snapshot(jwks(jwk("known", (RSAPublicKey) rsa3072().getPublic()))) + }) { + MutableClock clock = new MutableClock(INITIAL); + AtomicReference current = + new AtomicReference<>(valid); + var cache = cache(clock, current::get); + cache.refresh(); + cache.invalidateKid("denied"); + current.set(invalid); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + current.set(valid); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + assertThatThrownBy(() -> cache.keyFor("unknown")) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + assertThatThrownBy(() -> cache.keyFor("denied")) + .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class); + } + } + @Test void snapshotBoundKnownKeyRejectsNewEvidenceUntilOrdinaryRefreshMatchesIt() throws Exception { KeyPair key = rsa3072(); @@ -615,7 +1123,7 @@ private static byte[] unsigned(byte[] value) { } private static final class MutableClock extends Clock { - private Instant current; + private volatile Instant current; private MutableClock(Instant current) { this.current = current; diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksReadCodecTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksReadCodecTest.java new file mode 100644 index 0000000000..5ec076fe42 --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksReadCodecTest.java @@ -0,0 +1,158 @@ +package net.firedevops.firemud.common.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksRequest; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksResponse; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import org.junit.jupiter.api.Test; + +class AccountPublicJwksReadCodecTest { + private static final SourceIdentity PIN = + new SourceIdentity( + "prod", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "firemud-prod", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "api-7", + "https://kubernetes.example:6443", + "a".repeat(64)); + private static final UnknownFieldSet UNKNOWN = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + @Test + void repeatsActualNineFieldIdentityAndExactBytesWithDefensiveCopies() { + byte[] bytes = "public snapshot bytes".getBytes(java.nio.charset.StandardCharsets.UTF_8); + var response = AccountPublicJwksReadCodec.response(new PublicJwksSnapshot(PIN, bytes)); + bytes[0] = 0; + var parsed = AccountPublicJwksReadCodec.snapshot(response); + assertThat(parsed.sourceIdentity()).isEqualTo(PIN); + assertThat(parsed.jwksBytes()).isEqualTo(response.getPublicJwks().toByteArray()); + byte[] copy = parsed.jwksBytes(); + copy[0] = 0; + assertThat(parsed.jwksBytes()).isNotEqualTo(copy); + AccountPublicJwksReadCodec.requireRequest(AccountPublicJwksReadCodec.request()); + } + + @Test + void refusesUnversionedWrongVersionAndUnknownRequestSelectors() { + for (var request : + new GetCurrentAccountPublicJwksRequest[] { + null, + GetCurrentAccountPublicJwksRequest.getDefaultInstance(), + AccountPublicJwksReadCodec.request().toBuilder().setSchemaVersion(1).build(), + AccountPublicJwksReadCodec.request().toBuilder().setUnknownFields(UNKNOWN).build() + }) { + assertThatThrownBy(() -> AccountPublicJwksReadCodec.requireRequest(request)) + .isInstanceOf(AccountPublicJwksReadCodec.InvalidFrameException.class); + } + } + + @Test + void refusesUnknownNestedFieldsMissingIdentityOrBytesAndInvalidIdentity() { + var valid = AccountPublicJwksReadCodec.response(new PublicJwksSnapshot(PIN, new byte[] {1})); + for (var response : + new GetCurrentAccountPublicJwksResponse[] { + null, + GetCurrentAccountPublicJwksResponse.getDefaultInstance(), + valid.toBuilder().setSchemaVersion(1).build(), + valid.toBuilder().setUnknownFields(UNKNOWN).build(), + valid.toBuilder() + .setSourceIdentity(valid.getSourceIdentity().toBuilder().setUnknownFields(UNKNOWN)) + .build(), + valid.toBuilder().clearSourceIdentity().build(), + valid.toBuilder().clearPublicJwks().build(), + valid.toBuilder() + .setSourceIdentity( + valid.getSourceIdentity().toBuilder().setConfigMapUid("caller-label")) + .build(), + valid.toBuilder() + .setPublicJwks( + ByteString.copyFrom(new byte[AccountPublicJwksCache.MAX_JWKS_BYTES + 1])) + .build(), + valid.toBuilder() + .setSourceIdentity( + valid.getSourceIdentity().toBuilder() + .setBindingRevision( + "x".repeat(AccountPublicJwksReadCodec.MAX_RESPONSE_BYTES))) + .build() + }) { + assertThatThrownBy(() -> AccountPublicJwksReadCodec.snapshot(response)) + .isInstanceOf(AccountPublicJwksReadCodec.InvalidFrameException.class); + } + } + + @Test + void closedDispositionAndEligibilityPresenceCannotBeConfusedWithSnapshotBytes() { + var snapshot = + AccountPublicJwksReadCodec.response( + new AccountPublicJwksReadCodec.ReadResult(PIN, new byte[] {1}, false, true)); + assertThat(snapshot.getSchemaVersion()).isEqualTo(2); + assertThat(snapshot.hasCommittedRecoveryEligible()).isTrue(); + assertThat(AccountPublicJwksReadCodec.result(snapshot).committedRecoveryEligible()).isTrue(); + var deny = + AccountPublicJwksReadCodec.response( + new AccountPublicJwksReadCodec.ReadResult(PIN, new byte[0], true, false)); + assertThat(deny.getPublicJwks()).isEmpty(); + assertThat(deny.hasCommittedRecoveryEligible()).isFalse(); + assertThat(AccountPublicJwksReadCodec.result(deny).sourceIdentity()).isEqualTo(PIN); + assertThat(AccountPublicJwksReadCodec.result(deny).preparedDeny()).isTrue(); + assertThatThrownBy(() -> AccountPublicJwksReadCodec.snapshot(deny)) + .isInstanceOf(AccountPublicJwksReadCodec.InvalidFrameException.class); + for (var invalid : + new GetCurrentAccountPublicJwksResponse[] { + snapshot.toBuilder().clearDisposition().build(), + snapshot.toBuilder().setDispositionValue(99).build(), + snapshot.toBuilder().clearCommittedRecoveryEligible().build(), + deny.toBuilder().setCommittedRecoveryEligible(false).build(), + deny.toBuilder().setCommittedRecoveryEligible(true).build(), + deny.toBuilder().setPublicJwks(ByteString.copyFromUtf8("not a deny")).build(), + deny.toBuilder().setUnknownFields(UNKNOWN).build(), + deny.toBuilder().clearSourceIdentity().build(), + deny.toBuilder() + .setSourceIdentity(deny.getSourceIdentity().toBuilder().setUnknownFields(UNKNOWN)) + .build() + }) { + assertThatThrownBy(() -> AccountPublicJwksReadCodec.result(invalid)) + .isInstanceOf(AccountPublicJwksReadCodec.InvalidFrameException.class); + } + } + + @Test + void localResultRejectsDenyWithBytesOrRecoveryClaimAndCopiesBytes() { + for (var invalid : + new Object[][] { + {new byte[] {1}, true, false}, {new byte[0], true, true}, {new byte[0], false, false} + }) { + assertThatThrownBy( + () -> + new AccountPublicJwksReadCodec.ReadResult( + PIN, (byte[]) invalid[0], (boolean) invalid[1], (boolean) invalid[2])) + .isInstanceOf(AccountPublicJwksReadCodec.InvalidFrameException.class); + } + byte[] bytes = {1}; + var result = new AccountPublicJwksReadCodec.ReadResult(PIN, bytes, false, false); + bytes[0] = 2; + assertThat(result.jwksBytes()).containsExactly((byte) 1); + result.jwksBytes()[0] = 3; + assertThat(result.jwksBytes()).containsExactly((byte) 1); + } + + @Test + void producerRefusesMissingEmptyOrOversizedPublicMaterial() { + for (byte[] bytes : + new byte[][] {null, new byte[0], new byte[AccountPublicJwksCache.MAX_JWKS_BYTES + 1]}) { + assertThatThrownBy( + () -> AccountPublicJwksReadCodec.response(new PublicJwksSnapshot(PIN, bytes))) + .isInstanceOf(AccountPublicJwksReadCodec.InvalidFrameException.class); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfiguration.java new file mode 100644 index 0000000000..397150fa1b --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfiguration.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.gamesession.config; + +import java.time.Clock; +import java.time.Duration; +import java.util.List; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.repository.DirectTextAuthenticatedLobbyRepository; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextRedisClient; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCoordinationQualification; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisAttemptClosure; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** Default-off receiving composition; every protected authority must be independently supplied. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.game-session.authenticated-gameplay", + name = "enabled", + havingValue = "true") +public class AuthenticatedGameplayRuntimeConfiguration { + @Bean(initMethod = "initialize", destroyMethod = "close") + CanonicalGameplayLoginAccountClient canonicalGameplayLoginAccountClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + BlockingGrpcStubCustomizer customizer, + AccountAsymmetricJwtVerifier verifier, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new CanonicalGameplayLoginAccountClient( + endpoints, + tls, + channels, + customizer, + namespace, + Clock.systemUTC(), + Duration.ofSeconds(3), + verifier); + } + + @Bean + InitialGameplayLoginOwner initialGameplayLoginOwner( + InitialGameplayLoginRedisBinding binding, + InitialGameplayLoginCoordinationQualification qualification, + CanonicalGameplayLoginAccountClient account, + DSLContext dsl, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + var contexts = + new InitialGameplayLoginContextRedisClient( + binding, + RedisScriptCatalog.fromContributions( + List.of(new InitialGameplayLoginRedisScriptContribution())), + qualification); + var cleanup = + new InitialGameplayLoginCleanupOwner( + new InitialGameplayLoginCoordinationJournalRepository(dsl), + new InitialGameplayLoginRedisAttemptClosure(contexts), + account, + transactions); + return new InitialGameplayLoginOwner(contexts, cleanup, account); + } + + @Bean + DirectTextWorldSelectionService authenticatedDirectTextWorldSelections( + GameplayWorldCatalog catalog, CanonicalPlayerRouteReadService routes) { + return new DirectTextWorldSelectionService(catalog, routes, Clock.systemUTC()); + } + + @Bean + DirectTextAuthenticatedLobbyOwner directTextAuthenticatedLobbyOwner( + DSLContext dsl, + DirectTextWorldSelectionService selections, + AccountClient account, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new DirectTextAuthenticatedLobbyOwner( + new DirectTextAuthenticatedLobbyRepository(dsl), + selections, + account, + transactions, + Clock.systemUTC()); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfiguration.java new file mode 100644 index 0000000000..97caf6eded --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfiguration.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.gamesession.config; + +import java.time.Clock; +import java.time.Duration; +import java.util.Objects; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.gamesession.service.AccountPublicJwksReadClient; +import net.firedevops.firemud.gamesession.service.GameSessionAccountPublicJwksSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** Default-off public-key composition only; does not register LOGIN or grant gameplay authority. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.game-session.account-public-jwks", + name = "enabled", + havingValue = "true") +public class GameSessionAccountPublicJwksConfiguration { + @Bean + AccountPublicJwksReadClient accountPublicJwksReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountPublicJwksReadClient(endpoints, tls, channels, namespace); + } + + @Bean + GameSessionAccountPublicJwksSource gameSessionAccountPublicJwksSource( + AccountPublicJwksReadClient client, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new GameSessionAccountPublicJwksSource(client, namespace); + } + + @Bean + AccountPublicJwksCache accountPublicJwksCache( + GameSessionAccountPublicJwksSource source, + @Value("${firemud.game-session.account-public-jwks.maximum-cache-age-millis:0}") + long maximumAge) { + Duration age = requiredMaximumAge(maximumAge); + var cache = new AccountPublicJwksCache(source, source.sourceIdentity(), Clock.systemUTC(), age); + try { + cache.refresh(); + } catch (AccountPublicJwksCache.SourcePreparedDenyException denied) { + // The verified source and cache already retain the deny. Start empty so the existing + // lifecycle task can later consume exact committed and protected-mount recovery proof. + } + return cache; + } + + @Bean + AccountAsymmetricJwtVerifier accountAsymmetricJwtVerifier(AccountPublicJwksCache cache) { + return new AccountAsymmetricJwtVerifier(cache, Clock.systemUTC()); + } + + @Bean(destroyMethod = "close") + PublicJwksRefresh accountPublicJwksRefresh( + AccountPublicJwksCache cache, + @Value("${firemud.game-session.account-public-jwks.maximum-cache-age-millis:0}") + long maximumAge) { + return new PublicJwksRefresh(cache, requiredMaximumAge(maximumAge)); + } + + static Duration requiredMaximumAge(long millis) { + if (millis < 2_000L || millis > 300_000L) { + throw new IllegalArgumentException("Explicit bounded Account public JWKS cache age required"); + } + return Duration.ofMillis(millis); + } + + /** Owns only this opt-in's bounded public-key refresh, never generic runtime scheduling. */ + static final class PublicJwksRefresh implements AutoCloseable { + private static final Logger LOG = LoggerFactory.getLogger(PublicJwksRefresh.class); + private final ScheduledExecutorService executor; + private final AtomicBoolean terminalRejectionReported = new AtomicBoolean(); + + PublicJwksRefresh(AccountPublicJwksCache cache, Duration maximumAge) { + this( + cache, + maximumAge, + Executors.newSingleThreadScheduledExecutor( + task -> { + Thread thread = new Thread(task, "game-session-account-public-jwks-refresh"); + thread.setDaemon(true); + return thread; + })); + } + + PublicJwksRefresh( + AccountPublicJwksCache cache, Duration maximumAge, ScheduledExecutorService executor) { + Objects.requireNonNull(cache); + this.executor = Objects.requireNonNull(executor); + long delayMillis = requiredMaximumAge(maximumAge.toMillis()).toMillis() / 2L; + executor.scheduleWithFixedDelay( + () -> { + try { + cache.refresh(); + } catch (AccountPublicJwksCache.SourcePreparedDenyException denied) { + LOG.warn("Account public JWKS refresh denied: PREPARED_DENY"); + } catch (SourceUnavailableException unavailable) { + LOG.warn("Account public JWKS refresh unavailable: SOURCE_UNAVAILABLE"); + } catch (InvalidJwksException rejected) { + if (terminalRejectionReported.compareAndSet(false, true)) { + LOG.error( + "Account public JWKS cache refused until explicit requalification: SOURCE_REJECTED"); + } + } + }, + delayMillis, + delayMillis, + TimeUnit.MILLISECONDS); + } + + @Override + public void close() { + executor.shutdownNow(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfiguration.java new file mode 100644 index 0000000000..123648aa36 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfiguration.java @@ -0,0 +1,121 @@ +package net.firedevops.firemud.gamesession.config; + +import io.lettuce.core.RedisCredentials; +import io.lettuce.core.RedisCredentialsProvider; +import io.lettuce.core.RedisURI; +import java.net.URI; +import java.time.Duration; +import java.util.Arrays; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; +import net.firedevops.firemud.gamesession.service.LettuceInitialGameplayLoginConnectionProvider; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Composes the dedicated Coordination source without granting JWT trust, maintenance qualification + * or gameplay. Endpoint, credential and deployment custody must be independently delivered. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.game-session.initial-gameplay-login.protected-sources", + name = "enabled", + havingValue = "true") +public class InitialGameplayLoginProtectedSourcesConfiguration { + @Bean(destroyMethod = "close") + LettuceInitialGameplayLoginConnectionProvider initialGameplayLoginCoordinationConnections( + @Value("${firemud.game-session.initial-gameplay-login.protected-sources.coordination.uri:}") + String configuredUri, + @Value( + "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.command-timeout-millis:0}") + int commandTimeoutMillis) { + try { + return new LettuceInitialGameplayLoginConnectionProvider( + requiredCoordinationUri(configuredUri, commandTimeoutMillis)); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + @Bean + InitialGameplayLoginRedisBinding initialGameplayLoginRedisBinding( + LettuceInitialGameplayLoginConnectionProvider connections, + @Value( + "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.protected-binding-id:}") + String protectedBindingId, + @Value( + "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.profile:}") + String profile, + @Value( + "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.required-local-aof-count:0}") + int localAof, + @Value( + "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.required-replica-aof-count:0}") + int replicaAof, + @Value( + "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.acknowledgement-timeout-millis:0}") + int timeoutMillis) { + final Profile selectedProfile; + try { + selectedProfile = Profile.valueOf(profile == null ? "" : profile); + } catch (IllegalArgumentException invalid) { + // Enum parsing can include a delivered value. Keep only the fixed failure category. + throw new IllegalArgumentException("Protected Coordination profile is invalid"); + } + // These owner validators already expose fixed, cause-free identity and ACK diagnostics. + return new InitialGameplayLoginRedisBinding( + protectedBindingId, + connections::openPinnedConnection, + new AcknowledgementPolicy(selectedProfile, localAof, replicaAof, timeoutMillis)); + } + + static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) { + char[] password = null; + try { + if (configuredUri == null + || configuredUri.length() > 4096 + || timeoutMillis < 1 + || timeoutMillis > 60_000) { + throw unavailable(); + } + URI uri = URI.create(configuredUri); + String userInfo = uri.getUserInfo(); + String principal = InitialGameplayLoginRedisBinding.PRINCIPAL; + if (!"rediss".equals(uri.getScheme()) + || uri.getHost() == null + || uri.getHost().isBlank() + || uri.getPort() < 1 + || uri.getPort() > 65_535 + || !"/0".equals(uri.getRawPath()) + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || userInfo == null + || !userInfo.startsWith(principal + ":") + || userInfo.length() == principal.length() + 1 + || userInfo.chars().anyMatch(Character::isISOControl)) { + throw unavailable(); + } + password = userInfo.substring(principal.length() + 1).toCharArray(); + var credentials = RedisCredentials.just(principal, password); + return RedisURI.Builder.redis(uri.getHost(), uri.getPort()) + .withSsl(true) + .withVerifyPeer(true) + .withAuthentication(RedisCredentialsProvider.from(() -> credentials)) + .withDatabase(0) + .withTimeout(Duration.ofMillis(timeoutMillis)) + .build(); + } catch (RuntimeException failure) { + // URI parsing can include the delivered credential in its message or cause. + throw unavailable(); + } finally { + if (password != null) Arrays.fill(password, '\0'); + } + } + + private static IllegalArgumentException unavailable() { + return new IllegalArgumentException("Protected Game Session initial LOGIN sources required"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPublicJwksReadClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPublicJwksReadClient.java new file mode 100644 index 0000000000..2205e31b20 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPublicJwksReadClient.java @@ -0,0 +1,141 @@ +package net.firedevops.firemud.gamesession.service; + +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.ClientInterceptors; +import io.grpc.ForwardingClientCall.SimpleForwardingClientCall; +import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener; +import io.grpc.Grpc; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountPublicJwksReadServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec.ReadResult; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Same-namespace mTLS current-public-state read, with no bearer or readiness-plan dependency. */ +public final class AccountPublicJwksReadClient { + private static final int ACCOUNT_PORT = 6565; + private static final long DEADLINE_SECONDS = 3L; + private final ServiceEndpointsProperties endpoints; + private final CommonGrpcClientProperties tls; + private final GrpcChannelFactory channels; + private final String accountUri; + + public AccountPublicJwksReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + String namespace) { + this.endpoints = Objects.requireNonNull(endpoints).copy(); + this.tls = Objects.requireNonNull(tls).copy(); + this.channels = Objects.requireNonNull(channels); + if (!GrpcPeerIdentity.isValidNamespace(namespace) + || tls.isPlaintext() + || blank(tls.getCertChain()) + || blank(tls.getPrivateKey()) + || blank(tls.getCaCert()) + || blank(this.endpoints.getAccountService())) { + throw new IllegalArgumentException("Explicit Account endpoint and protected mTLS required"); + } + this.accountUri = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + } + + public ReadResult readCurrent() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new SourceUnavailableException(); + } + ManagedChannel channel = null; + try { + channel = channels.buildChannel(endpoints.getAccountService(), ACCOUNT_PORT, tls, false); + var authenticated = + ClientInterceptors.intercept( + channel, + new GrpcServerPeerIdentityClientInterceptor(accountUri), + new EstablishedPeerFailureFence()); + // CallOptions' inbound limit is applied by gRPC's transport deframer, before protobuf parse. + var response = + AccountPublicJwksReadServiceGrpc.newBlockingStub(authenticated) + .withMaxInboundMessageSize(AccountPublicJwksReadCodec.MAX_RESPONSE_BYTES) + .withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS) + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request()); + return AccountPublicJwksReadCodec.result(response); + } catch (StatusRuntimeException failure) { + Status.Code code = failure.getStatus().getCode(); + if (!hasTlsFailure(failure) + && (code == Status.Code.UNAVAILABLE || code == Status.Code.DEADLINE_EXCEEDED)) { + throw new SourceUnavailableException(); + } + // Authentication, wire-schema and oversized-frame failures are never outage exceptions. + throw new InvalidJwksException(); + } catch (javax.net.ssl.SSLException invalid) { + throw new InvalidJwksException(); + } catch (SourceUnavailableException unavailable) { + throw unavailable; + } catch (RuntimeException invalid) { + throw new InvalidJwksException(); + } finally { + if (channel != null) { + channel.shutdownNow(); + } + } + } + + /** The shared content fence permits unverified non-OK trailers; do not call those outages. */ + private final class EstablishedPeerFailureFence implements ClientInterceptor { + @Override + public ClientCall interceptCall( + MethodDescriptor method, CallOptions options, Channel next) { + ClientCall call = next.newCall(method, options); + return new SimpleForwardingClientCall<>(call) { + @Override + public void start(Listener listener, Metadata headers) { + super.start( + new SimpleForwardingClientCallListener<>(listener) { + @Override + public void onClose(Status status, Metadata trailers) { + var session = call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + if (session != null + && GrpcPeerIdentity.fromSslSession(session) + .filter(peer -> accountUri.equals(peer.uri())) + .isEmpty()) { + super.onClose(Status.UNAUTHENTICATED, new Metadata()); + } else { + super.onClose(status, trailers); + } + } + }, + headers); + } + }; + } + } + + private static boolean hasTlsFailure(Throwable failure) { + Throwable current = failure; + // Bound traversal even if a transport implementation supplied a cyclic cause chain. + for (int depth = 0; current != null && depth < 16; depth++) { + if (current instanceof javax.net.ssl.SSLException) return true; + current = current.getCause(); + } + return false; + } + + private static boolean blank(String value) { + return value == null || value.isBlank(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAccountPublicJwksSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAccountPublicJwksSource.java new file mode 100644 index 0000000000..0a2e7d09a2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionAccountPublicJwksSource.java @@ -0,0 +1,194 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.util.Arrays; +import java.util.Objects; +import java.util.function.Supplier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceCustodyRejectedException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourcePreparedDenyException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.TrustedPublicJwksSource; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec.ReadResult; + +/** + * Pins current Account provenance once and requires the exact protected mounted bytes each load. + */ +public final class GameSessionAccountPublicJwksSource implements TrustedPublicJwksSource { + private final Supplier account; + private final ProtectedAccountPublicJwksProjection projection; + private final String namespace; + private SourceIdentity pinned; + private volatile boolean quarantined; + private volatile boolean preparedDenied; + private final java.util.concurrent.atomic.AtomicLong preparedDenyEpoch = + new java.util.concurrent.atomic.AtomicLong(); + private byte[] lastAcceptedBytes; + + public GameSessionAccountPublicJwksSource(AccountPublicJwksReadClient account, String namespace) { + this( + Objects.requireNonNull(account)::readCurrent, + new ProtectedAccountPublicJwksProjection(), + namespace); + } + + GameSessionAccountPublicJwksSource( + Supplier account, + ProtectedAccountPublicJwksProjection projection, + String namespace) { + this.account = Objects.requireNonNull(account); + this.projection = Objects.requireNonNull(projection); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Game Session workload namespace required"); + } + this.namespace = namespace; + } + + /** Initializes from authenticated Account evidence, never from configured identity strings. */ + public synchronized SourceIdentity sourceIdentity() { + if (quarantined) throw new SourceCustodyRejectedException(); + if (pinned == null) { + try { + load(); + } catch (SourcePreparedDenyException denied) { + // An authenticated deny supplies the lifetime pin without qualifying any keys. + if (pinned == null) throw denied; + } + } + return pinned; + } + + @Override + public boolean isPreparedDenied() { + // Cache calls this under its own monitor; never wait for an in-flight remote read. + return preparedDenied; + } + + @Override + public boolean isCustodyRejected() { + return quarantined; + } + + @Override + public long preparedDenyEpoch() { + return preparedDenyEpoch.get(); + } + + @Override + public synchronized PublicJwksSnapshot load() { + if (quarantined) throw new SourceCustodyRejectedException(); + byte[] first = null; + byte[] last = null; + byte[] rechecked = null; + boolean qualifiedTransition = false; + try { + first = projection.read(); + ReadResult before = requireResult(account.get(), null); + requireBytes(before, first); + ReadResult after = requireResult(account.get(), before.sourceIdentity()); + last = projection.read(); + if (!before.sourceIdentity().equals(after.sourceIdentity())) { + throw new InvalidJwksException(); + } + requireBytes(after, last); + if (!Arrays.equals(first, last)) { + if (pinned == null + || lastAcceptedBytes == null + || !Arrays.equals(first, lastAcceptedBytes)) { + throw new InvalidJwksException(); + } + AccountPublicJwksCache.validatePublicJwks(first); + AccountPublicJwksCache.validatePublicJwks(last); + // Both protected reads matched their authenticated same-pin Account snapshots. A + // publication between those intact reads requires a later stable load, not requalification. + qualifiedTransition = true; + throw new SourceUnavailableException(); + } + if (preparedDenied) { + AccountPublicJwksCache.validatePublicJwks(first); + if (!before.committedRecoveryEligible() || !after.committedRecoveryEligible()) { + throw new SourcePreparedDenyException(); + } + } + pinned = before.sourceIdentity(); + if (lastAcceptedBytes != null) Arrays.fill(lastAcceptedBytes, (byte) 0); + lastAcceptedBytes = first.clone(); + boolean recoveryEligible = + before.committedRecoveryEligible() && after.committedRecoveryEligible(); + preparedDenied = false; + return new PublicJwksSnapshot(pinned, first, recoveryEligible, preparedDenyEpoch.get()); + } catch (SourcePreparedDenyException denied) { + // A valid prepared deny is recoverable and never installs bytes or renews cache age. + throw denied; + } catch (SourceUnavailableException unavailable) { + // A network outage cannot conceal local custody loss or changed projected content. + try { + rechecked = projection.read(); + byte[] expected = qualifiedTransition ? last : first; + if (expected == null + || !Arrays.equals(expected, rechecked) + || (!qualifiedTransition + && lastAcceptedBytes != null + && !Arrays.equals(lastAcceptedBytes, rechecked))) { + throw new InvalidJwksException(); + } + } catch (RuntimeException | IOException invalid) { + quarantined = true; + throw new SourceCustodyRejectedException(); + } + throw unavailable; + } catch (RuntimeException | IOException invalid) { + // No replacement identity, custody mismatch or concurrent divergence can silently recover. + quarantined = true; + throw new SourceCustodyRejectedException(); + } finally { + if (first != null) Arrays.fill(first, (byte) 0); + if (last != null) Arrays.fill(last, (byte) 0); + if (rechecked != null) Arrays.fill(rechecked, (byte) 0); + } + } + + private ReadResult requireResult(ReadResult result, SourceIdentity expected) { + if (result == null + || result.sourceIdentity() == null + || !namespace.equals(result.sourceIdentity().namespace()) + || (pinned != null && !pinned.equals(result.sourceIdentity())) + || (expected != null && !expected.equals(result.sourceIdentity()))) { + throw new InvalidJwksException(); + } + if (result.preparedDeny()) { + if (pinned == null) pinned = result.sourceIdentity(); + if (!preparedDenied) { + if (preparedDenyEpoch.get() == Long.MAX_VALUE) throw new InvalidJwksException(); + preparedDenyEpoch.incrementAndGet(); + } + preparedDenied = true; + throw new SourcePreparedDenyException(); + } + return result; + } + + private void requireBytes(ReadResult snapshot, byte[] expected) { + byte[] actual = snapshot.jwksBytes(); + try { + if (actual == null) throw new InvalidJwksException(); + if (!Arrays.equals(actual, expected)) { + if (pinned != null + && lastAcceptedBytes != null + && Arrays.equals(lastAcceptedBytes, expected)) { + AccountPublicJwksCache.validatePublicJwks(actual); + // Account may publish before this already qualified mount converges. The unavailable + // catch rechecks local custody and requires the unchanged last accepted bytes. + throw new SourceUnavailableException(); + } + throw new InvalidJwksException(); + } + } finally { + if (actual != null) Arrays.fill(actual, (byte) 0); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java index d16bdf6f2c..930276e9ae 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedJwksSource.java @@ -1,79 +1,37 @@ package net.firedevops.firemud.gamesession.service; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.SeekableByteChannel; -import java.nio.file.Files; -import java.nio.file.LinkOption; import java.nio.file.Path; -import java.nio.file.StandardOpenOption; -import java.nio.file.attribute.BasicFileAttributes; -import java.nio.file.attribute.PosixFilePermission; import java.security.MessageDigest; import java.util.Objects; -import java.util.Set; -import net.firedevops.firemud.common.security.AccountPublicJwksCache; import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; import net.firedevops.firemud.common.security.AccountPublicJwksCache.TrustedPublicJwksSource; -import net.firedevops.firemud.common.security.ProtectedProjectionMount; -/** - * Reads only Account's fixed projected public JWKS; it never discovers keys or uses classpath data. - * The volume must use {@code defaultMode: 0444}; a read-only mount alone retains owner-write in the - * projected file mode, which this reader refuses. - */ +/** Finite readiness-only identity and digest fence; never a steady-state LOGIN trust source. */ public final class GameSessionJwtReadinessProtectedJwksSource implements TrustedPublicJwksSource { - public static final Path JWKS_PATH = fixedJwksPath(); - - private static final int MAX_FILE_BYTES = AccountPublicJwksCache.MAX_JWKS_BYTES; + public static final Path JWKS_PATH = ProtectedAccountPublicJwksProjection.JWKS_PATH; private final GameSessionJwtReadinessLocalIdentityProvider identityProvider; - private final Path jwksDirectory; - private final long expectedOwnerUid; - private final boolean allowFixedProductionAlias; - - @SuppressFBWarnings( - value = "DMI_HARDCODED_ABSOLUTE_FILENAME", - justification = - "The Account public JWKS is intentionally fixed to this read-only projected path; alternate paths would permit trust-source substitution.") - private static Path fixedJwksPath() { - return Path.of("/var/run/secrets/firemud/jwks/jwks.json"); - } + private final ProtectedAccountPublicJwksProjection projection; public GameSessionJwtReadinessProtectedJwksSource( GameSessionJwtReadinessLocalIdentityProvider identityProvider) { - this(identityProvider, JWKS_PATH, 0L, true); + this.identityProvider = Objects.requireNonNull(identityProvider); + this.projection = new ProtectedAccountPublicJwksProjection(); } GameSessionJwtReadinessProtectedJwksSource( GameSessionJwtReadinessLocalIdentityProvider identityProvider, Path jwksPath, long expectedOwnerUid) { - this(identityProvider, jwksPath, expectedOwnerUid, false); + this.identityProvider = Objects.requireNonNull(identityProvider); + this.projection = new ProtectedAccountPublicJwksProjection(jwksPath, expectedOwnerUid); } - private GameSessionJwtReadinessProtectedJwksSource( - GameSessionJwtReadinessLocalIdentityProvider identityProvider, - Path jwksPath, - long expectedOwnerUid, - boolean allowFixedProductionAlias) { - this.identityProvider = Objects.requireNonNull(identityProvider); - Path configuredJwksPath = Objects.requireNonNull(jwksPath); - this.jwksDirectory = - Objects.requireNonNull( - configuredJwksPath.getParent(), "The Account JWKS path must have a parent"); - Path fileName = configuredJwksPath.getFileName(); - if (!configuredJwksPath.isAbsolute() - || !configuredJwksPath.equals(configuredJwksPath.normalize()) - || fileName == null - || !"jwks.json".equals(fileName.toString()) - || expectedOwnerUid < 0L) { - throw new IllegalArgumentException("Protected Account JWKS path or owner is invalid"); - } - this.expectedOwnerUid = expectedOwnerUid; - this.allowFixedProductionAlias = allowFixedProductionAlias; + static boolean isCanonicalProductionAlias(Path configuredDirectory, Path realDirectory) { + return ProtectedAccountPublicJwksProjection.isCanonicalProductionAlias( + configuredDirectory, realDirectory); } @Override @@ -81,7 +39,7 @@ public PublicJwksSnapshot load() { try { GameSessionJwtReadinessLocalIdentityProvider.LocalObservation before = Objects.requireNonNull(identityProvider.observe()); - byte[] bytes = readProjectedFile(); + byte[] bytes = projection.read(); try { if (!before.wireIdentity().getAccountPublicJwksSha256().equals(sha256(bytes))) { throw unavailable(); @@ -102,153 +60,6 @@ public PublicJwksSnapshot load() { } } - private byte[] readProjectedFile() throws IOException { - Path normalizedDirectory = jwksDirectory.toAbsolutePath().normalize(); - if (!normalizedDirectory.equals(jwksDirectory) || Files.isSymbolicLink(jwksDirectory)) { - throw unavailable(); - } - Path trustedDirectory = resolveTrustedProjectionRoot(); - Path dataLink = trustedDirectory.resolve("..data"); - Path projectedJwksPath = trustedDirectory.resolve("jwks.json"); - if (!Files.isSymbolicLink(dataLink) - || !Files.isSymbolicLink(projectedJwksPath) - || !Path.of("..data/jwks.json").equals(Files.readSymbolicLink(projectedJwksPath))) { - throw unavailable(); - } - Path dataVersion = Files.readSymbolicLink(dataLink); - if (dataVersion.isAbsolute() - || dataVersion.getNameCount() != 1 - || !dataVersion.toString().matches("\\.\\.[A-Za-z0-9._-]{1,128}")) { - throw unavailable(); - } - ProtectedProjectionMount.Snapshot mountBefore = - verifyOwnedProjectionPath(trustedDirectory, true, true); - Path dataTarget = trustedDirectory.resolve(dataVersion).normalize(); - if (!trustedDirectory.equals(dataTarget.getParent()) - || !Files.isDirectory(dataTarget, LinkOption.NOFOLLOW_LINKS)) { - throw unavailable(); - } - verifyOwnedProjectionPath(dataTarget, true); - Path file = dataTarget.resolve("jwks.json"); - BasicFileAttributes before = - Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - if (!before.isRegularFile() || before.size() <= 0L || before.size() > MAX_FILE_BYTES) { - throw unavailable(); - } - verifyOwnedProjectionPath(file, false); - byte[] bytes = new byte[(int) before.size()]; - try (SeekableByteChannel channel = - Files.newByteChannel(file, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { - ByteBuffer buffer = ByteBuffer.wrap(bytes); - while (buffer.hasRemaining()) { - if (channel.read(buffer) < 0) { - throw unavailable(); - } - } - if (channel.read(ByteBuffer.allocate(1)) != -1) { - throw unavailable(); - } - } - BasicFileAttributes after = - Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - if (!Objects.equals(before.fileKey(), after.fileKey()) - || before.size() != after.size() - || !before.lastModifiedTime().equals(after.lastModifiedTime()) - || !dataVersion.equals(Files.readSymbolicLink(dataLink)) - || !dataTarget.equals(dataLink.toRealPath()) - || !Path.of("..data/jwks.json").equals(Files.readSymbolicLink(projectedJwksPath)) - || !trustedDirectory.equals(resolveTrustedProjectionRoot())) { - java.util.Arrays.fill(bytes, (byte) 0); - throw unavailable(); - } - ProtectedProjectionMount.Snapshot mountAfter = - verifyOwnedProjectionPath(trustedDirectory, true, true); - if (!Objects.equals(mountBefore, mountAfter)) { - java.util.Arrays.fill(bytes, (byte) 0); - throw unavailable(); - } - verifyOwnedProjectionPath(file, false); - return bytes; - } - - private Path resolveTrustedProjectionRoot() throws IOException { - Path realDirectory = jwksDirectory.toRealPath(); - if (realDirectory.equals(jwksDirectory)) { - return jwksDirectory; - } - if (!allowFixedProductionAlias - || !isCanonicalProductionAlias(jwksDirectory, realDirectory) - || !hasExactVarRunAlias()) { - throw unavailable(); - } - return realDirectory; - } - - @SuppressFBWarnings( - value = "DMI_HARDCODED_ABSOLUTE_FILENAME", - justification = - "The only permitted alias is the fixed production /var/run projection resolving to /run.") - static boolean isCanonicalProductionAlias(Path configuredDirectory, Path realDirectory) { - return Path.of("/var/run/secrets/firemud/jwks").equals(configuredDirectory) - && Path.of("/run/secrets/firemud/jwks").equals(realDirectory); - } - - @SuppressFBWarnings( - value = "DMI_HARDCODED_ABSOLUTE_FILENAME", - justification = - "The protected JWKS path may use only the fixed production /var/run to /run alias.") - private static boolean hasExactVarRunAlias() throws IOException { - Path var = Path.of("/var"); - Path varRun = Path.of("/var/run"); - Path run = Path.of("/run"); - if (Files.isSymbolicLink(var) - || !Files.isSymbolicLink(varRun) - || !run.equals(varRun.toRealPath()) - || Files.isSymbolicLink(run)) { - return false; - } - Path directory = run; - Path varRunDirectory = varRun; - for (String child : new String[] {"secrets", "firemud", "jwks"}) { - directory = directory.resolve(child); - varRunDirectory = varRunDirectory.resolve(child); - if (Files.isSymbolicLink(directory) || Files.isSymbolicLink(varRunDirectory)) { - return false; - } - } - return true; - } - - private void verifyOwnedProjectionPath(Path path, boolean directory) throws IOException { - verifyOwnedProjectionPath(path, directory, false); - } - - private ProtectedProjectionMount.Snapshot verifyOwnedProjectionPath( - Path path, boolean directory, boolean projectionRoot) throws IOException { - BasicFileAttributes attributes = - Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); - if ((directory && !attributes.isDirectory()) || (!directory && !attributes.isRegularFile())) { - throw unavailable(); - } - Object owner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); - Set mode = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); - boolean unsafeWrite = - mode.contains(PosixFilePermission.GROUP_WRITE) - || mode.contains(PosixFilePermission.OTHERS_WRITE); - if (!(owner instanceof Number uid) - || uid.longValue() != expectedOwnerUid - || (!directory && mode.contains(PosixFilePermission.OWNER_WRITE))) { - throw unavailable(); - } - if (unsafeWrite) { - if (!projectionRoot) { - throw unavailable(); - } - return ProtectedProjectionMount.read(path); - } - return null; - } - private static String sha256(byte[] bytes) { try { return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProvider.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProvider.java new file mode 100644 index 0000000000..2f4ef07a53 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProvider.java @@ -0,0 +1,62 @@ +package net.firedevops.firemud.gamesession.service; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.codec.ByteArrayCodec; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Owns the dedicated initial-LOGIN Coordination client, never the ambient Spring Redis client. Each + * invocation owns its returned physical connection. Reconnect cannot move a mutation's + * acknowledgement or readback onto another physical connection. + */ +public final class LettuceInitialGameplayLoginConnectionProvider implements AutoCloseable { + private final RedisClient client; + private final AtomicBoolean closed = new AtomicBoolean(); + + public LettuceInitialGameplayLoginConnectionProvider(RedisURI coordinationRedisUri) { + this.client = + Objects.requireNonNull( + RedisClient.create( + Objects.requireNonNull(coordinationRedisUri, "Explicit Coordination URI required")), + "Dedicated Coordination client required"); + try { + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + } catch (RuntimeException failure) { + try { + client.shutdown(); + } catch (RuntimeException shutdownFailure) { + failure.addSuppressed(shutdownFailure); + } + throw failure; + } + } + + public StatefulRedisConnection openPinnedConnection() { + if (closed.get()) throw unavailable(); + StatefulRedisConnection connection = client.connect(ByteArrayCodec.INSTANCE); + if (closed.get()) { + try { + connection.close(); + } catch (RuntimeException closeFailure) { + IllegalStateException failure = unavailable(); + failure.addSuppressed(closeFailure); + throw failure; + } + throw unavailable(); + } + return connection; + } + + @Override + public void close() { + if (closed.compareAndSet(false, true)) client.shutdown(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Initial LOGIN Coordination client is closed"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ProtectedAccountPublicJwksProjection.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ProtectedAccountPublicJwksProjection.java new file mode 100644 index 0000000000..8dab3eed38 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ProtectedAccountPublicJwksProjection.java @@ -0,0 +1,212 @@ +package net.firedevops.firemud.gamesession.service; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.util.Objects; +import java.util.Set; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.ProtectedProjectionMount; + +/** Fixed, bounded, root-owned AtomicWriter public-JWKS projection shared by two distinct owners. */ +final class ProtectedAccountPublicJwksProjection { + static final Path JWKS_PATH = fixedJwksPath(); + + private static final int MAX_FILE_BYTES = AccountPublicJwksCache.MAX_JWKS_BYTES; + + private final Path jwksDirectory; + private final long expectedOwnerUid; + private final boolean allowFixedProductionAlias; + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The Account public JWKS is intentionally fixed to this read-only projected path; alternate paths would permit trust-source substitution.") + private static Path fixedJwksPath() { + return Path.of("/var/run/secrets/firemud/jwks/jwks.json"); + } + + ProtectedAccountPublicJwksProjection() { + this(JWKS_PATH, 0L, true); + } + + ProtectedAccountPublicJwksProjection(Path jwksPath, long expectedOwnerUid) { + this(jwksPath, expectedOwnerUid, false); + } + + private ProtectedAccountPublicJwksProjection( + Path jwksPath, long expectedOwnerUid, boolean allowFixedProductionAlias) { + Path configuredJwksPath = Objects.requireNonNull(jwksPath); + this.jwksDirectory = + Objects.requireNonNull( + configuredJwksPath.getParent(), "The Account JWKS path must have a parent"); + Path fileName = configuredJwksPath.getFileName(); + if (!configuredJwksPath.isAbsolute() + || !configuredJwksPath.equals(configuredJwksPath.normalize()) + || fileName == null + || !"jwks.json".equals(fileName.toString()) + || expectedOwnerUid < 0L) { + throw new IllegalArgumentException("Protected Account JWKS path or owner is invalid"); + } + this.expectedOwnerUid = expectedOwnerUid; + this.allowFixedProductionAlias = allowFixedProductionAlias; + } + + byte[] read() throws IOException { + Path normalizedDirectory = jwksDirectory.toAbsolutePath().normalize(); + if (!normalizedDirectory.equals(jwksDirectory) || Files.isSymbolicLink(jwksDirectory)) { + throw invalid(); + } + Path trustedDirectory = resolveTrustedProjectionRoot(); + Path dataLink = trustedDirectory.resolve("..data"); + Path projectedJwksPath = trustedDirectory.resolve("jwks.json"); + if (!Files.isSymbolicLink(dataLink) + || !Files.isSymbolicLink(projectedJwksPath) + || !Path.of("..data/jwks.json").equals(Files.readSymbolicLink(projectedJwksPath))) { + throw invalid(); + } + Path dataVersion = Files.readSymbolicLink(dataLink); + if (dataVersion.isAbsolute() + || dataVersion.getNameCount() != 1 + || !dataVersion.toString().matches("\\.\\.[A-Za-z0-9._-]{1,128}")) { + throw invalid(); + } + ProtectedProjectionMount.Snapshot mountBefore = + verifyOwnedProjectionPath(trustedDirectory, true, true); + Path dataTarget = trustedDirectory.resolve(dataVersion).normalize(); + if (!trustedDirectory.equals(dataTarget.getParent()) + || !Files.isDirectory(dataTarget, LinkOption.NOFOLLOW_LINKS)) { + throw invalid(); + } + verifyOwnedProjectionPath(dataTarget, true); + Path file = dataTarget.resolve("jwks.json"); + BasicFileAttributes before = + Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0L || before.size() > MAX_FILE_BYTES) { + throw invalid(); + } + verifyOwnedProjectionPath(file, false); + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(file, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw invalid(); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw invalid(); + } + } + BasicFileAttributes after = + Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime()) + || !dataVersion.equals(Files.readSymbolicLink(dataLink)) + || !dataTarget.equals(dataLink.toRealPath()) + || !Path.of("..data/jwks.json").equals(Files.readSymbolicLink(projectedJwksPath)) + || !trustedDirectory.equals(resolveTrustedProjectionRoot())) { + java.util.Arrays.fill(bytes, (byte) 0); + throw invalid(); + } + ProtectedProjectionMount.Snapshot mountAfter = + verifyOwnedProjectionPath(trustedDirectory, true, true); + if (!Objects.equals(mountBefore, mountAfter)) { + java.util.Arrays.fill(bytes, (byte) 0); + throw invalid(); + } + verifyOwnedProjectionPath(file, false); + return bytes; + } + + private Path resolveTrustedProjectionRoot() throws IOException { + Path realDirectory = jwksDirectory.toRealPath(); + if (realDirectory.equals(jwksDirectory)) { + return jwksDirectory; + } + if (!allowFixedProductionAlias + || !isCanonicalProductionAlias(jwksDirectory, realDirectory) + || !hasExactVarRunAlias()) { + throw invalid(); + } + return realDirectory; + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The only permitted alias is the fixed production /var/run projection resolving to /run.") + static boolean isCanonicalProductionAlias(Path configuredDirectory, Path realDirectory) { + return Path.of("/var/run/secrets/firemud/jwks").equals(configuredDirectory) + && Path.of("/run/secrets/firemud/jwks").equals(realDirectory); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The protected JWKS path may use only the fixed production /var/run to /run alias.") + private static boolean hasExactVarRunAlias() throws IOException { + Path var = Path.of("/var"); + Path varRun = Path.of("/var/run"); + Path run = Path.of("/run"); + if (Files.isSymbolicLink(var) + || !Files.isSymbolicLink(varRun) + || !run.equals(varRun.toRealPath()) + || Files.isSymbolicLink(run)) { + return false; + } + Path directory = run; + Path varRunDirectory = varRun; + for (String child : new String[] {"secrets", "firemud", "jwks"}) { + directory = directory.resolve(child); + varRunDirectory = varRunDirectory.resolve(child); + if (Files.isSymbolicLink(directory) || Files.isSymbolicLink(varRunDirectory)) { + return false; + } + } + return true; + } + + private void verifyOwnedProjectionPath(Path path, boolean directory) throws IOException { + verifyOwnedProjectionPath(path, directory, false); + } + + private ProtectedProjectionMount.Snapshot verifyOwnedProjectionPath( + Path path, boolean directory, boolean projectionRoot) throws IOException { + BasicFileAttributes attributes = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if ((directory && !attributes.isDirectory()) || (!directory && !attributes.isRegularFile())) { + throw invalid(); + } + Object owner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set mode = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + boolean unsafeWrite = + mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE); + if (!(owner instanceof Number uid) + || uid.longValue() != expectedOwnerUid + || (!directory && mode.contains(PosixFilePermission.OWNER_WRITE))) { + throw invalid(); + } + if (unsafeWrite) { + if (!projectionRoot) { + throw invalid(); + } + return ProtectedProjectionMount.read(path); + } + return null; + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Protected Account public JWKS projection is invalid"); + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/AccountPublicJwksReadClientMtlsIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/AccountPublicJwksReadClientMtlsIntegrationTest.java new file mode 100644 index 0000000000..f717628ce9 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/AccountPublicJwksReadClientMtlsIntegrationTest.java @@ -0,0 +1,414 @@ +package integration.net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.Date; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountPublicJwksReadServiceGrpc; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksRequest; +import net.firedevops.firemud.account.v1.GetCurrentAccountPublicJwksResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec.ReadResult; +import net.firedevops.firemud.gamesession.service.AccountPublicJwksReadClient; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Real GS client and loopback TLS with a controlled Account-shaped producer, not Account source + * custody or deployment qualification. Only generated protocol and shared codec cross modules. + */ +class AccountPublicJwksReadClientMtlsIntegrationTest { + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final byte[] PUBLIC_BYTES = "{\"keys\":[]}".getBytes(StandardCharsets.US_ASCII); + @TempDir static Path temporaryDirectory; + private static Identity ca; + private static Identity clientIdentity; + private static Identity accountIdentity; + private static List invalidAccounts; + private Server server; + private final AtomicReference upstreamFailure = new AtomicReference<>(); + private final AtomicReference upstreamReply = + new AtomicReference<>(); + private final AtomicReference clientUri = new AtomicReference<>(); + private final AtomicReference authorization = new AtomicReference<>(); + private final AtomicReference request = + new AtomicReference<>(); + + @BeforeAll + static void createControlledTestPki() throws Exception { + if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) { + Security.addProvider(new BouncyCastleProvider()); + } + ca = issue("jwks-test-ca", null, true, List.of()); + clientIdentity = issue("jwks-test-client", ca, false, List.of(SESSION_URI)); + accountIdentity = issue("jwks-test-account", ca, false, List.of(ACCOUNT_URI)); + invalidAccounts = + List.of( + issue( + "wrong-workload", + ca, + false, + List.of("spiffe://firemud/ns/test/sa/world-management-service")), + issue( + "wrong-namespace", + ca, + false, + List.of("spiffe://firemud/ns/other/sa/account-service")), + issue("no-workload-uri", ca, false, List.of()), + issue("multiple-workload-uris", ca, false, List.of(ACCOUNT_URI, SESSION_URI))); + } + + @AfterEach + void stopServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(3, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + @Test + void actualClientReadsOnlyExactAuthenticatedAccountWithNoBearer() throws Exception { + start(accountIdentity, response(), false, false); + ReadResult result = client().readCurrent(); + assertThat(result.sourceIdentity()).isEqualTo(snapshot().sourceIdentity()); + assertThat(result.jwksBytes()).containsExactly(PUBLIC_BYTES); + assertThat(result.preparedDeny()).isFalse(); + assertThat(result.committedRecoveryEligible()).isFalse(); + assertThat(request.get().getSchemaVersion()).isEqualTo(2); + assertThat(clientUri.get()).isEqualTo(SESSION_URI); + assertThat(authorization.get()).isNull(); + assertThat(request.get()).isEqualTo(AccountPublicJwksReadCodec.request()); + byte[] mutable = result.jwksBytes(); + mutable[0] = 0; + assertThat(result.jwksBytes()).containsExactly(PUBLIC_BYTES); + } + + @Test + void rejectsWrongNamespaceWrongWorkloadAbsentAndMultipleUriSans() throws Exception { + for (Identity invalid : invalidAccounts) { + for (GetCurrentAccountPublicJwksResponse reply : List.of(response(), denyResponse())) { + start(invalid, reply, false, false); + assertThatThrownBy(() -> client().readCurrent()).isInstanceOf(InvalidJwksException.class); + stopServer(); + } + } + } + + @Test + void exactAuthenticatedAccountCanReturnPreparedDenyThenExplicitEligibleRecovery() + throws Exception { + start(accountIdentity, denyResponse(), false, false); + var reader = client(); + ReadResult denied = reader.readCurrent(); + assertThat(denied.sourceIdentity()).isEqualTo(snapshot().sourceIdentity()); + assertThat(denied.preparedDeny()).isTrue(); + assertThat(denied.committedRecoveryEligible()).isFalse(); + assertThat(denied.jwksBytes()).isNullOrEmpty(); + upstreamReply.set(response()); + assertThat(reader.readCurrent().committedRecoveryEligible()).isFalse(); + upstreamReply.set( + AccountPublicJwksReadCodec.response( + new ReadResult(snapshot().sourceIdentity(), PUBLIC_BYTES, false, true))); + ReadResult recovered = reader.readCurrent(); + assertThat(recovered.preparedDeny()).isFalse(); + assertThat(recovered.committedRecoveryEligible()).isTrue(); + assertThat(recovered.sourceIdentity()).isEqualTo(denied.sourceIdentity()); + assertThat(recovered.jwksBytes()).containsExactly(PUBLIC_BYTES); + assertThat(authorization.get()).isNull(); + } + + @Test + void malformedDispositionAndRecoveryEligibilityAreTerminalFromExactAccount() throws Exception { + start(accountIdentity, response(), false, false); + var reader = client(); + for (GetCurrentAccountPublicJwksResponse invalid : + List.of( + response().toBuilder().setSchemaVersion(1).build(), + response().toBuilder().clearDisposition().build(), + response().toBuilder().setDispositionValue(99).build(), + response().toBuilder().clearCommittedRecoveryEligible().build(), + denyResponse().toBuilder().setPublicJwks(ByteString.copyFrom(PUBLIC_BYTES)).build(), + denyResponse().toBuilder().setCommittedRecoveryEligible(false).build(), + denyResponse().toBuilder().setCommittedRecoveryEligible(true).build(), + denyResponse().toBuilder().clearSourceIdentity().build())) { + upstreamReply.set(invalid); + assertThatThrownBy(reader::readCurrent).isInstanceOf(InvalidJwksException.class); + } + } + + @Test + void boundedDeadlineIsRetryableUnavailability() throws Exception { + start(accountIdentity, response(), true, false); + Instant started = Instant.now(); + assertThatThrownBy(() -> client().readCurrent()).isInstanceOf(SourceUnavailableException.class); + assertThat(Duration.between(started, Instant.now())) + .isBetween(Duration.ofSeconds(2), Duration.ofSeconds(8)); + } + + @Test + void reachableUnavailableDiffersFromAuthenticationFailure() throws Exception { + start(accountIdentity, response(), false, true); + var reader = client(); + assertThatThrownBy(reader::readCurrent).isInstanceOf(SourceUnavailableException.class); + upstreamFailure.set(null); + assertThat(reader.readCurrent().jwksBytes()).containsExactly(PUBLIC_BYTES); + stopServer(); + start(invalidAccounts.getFirst(), response(), false, true); + assertThatThrownBy(() -> client().readCurrent()).isInstanceOf(InvalidJwksException.class); + } + + @Test + void genericStatusCodesRemainTerminalEvenFromTheExactAccountPeer() throws Exception { + start(accountIdentity, response(), false, false); + var reader = client(); + for (Status failure : + List.of( + Status.UNKNOWN, + Status.CANCELLED, + Status.ABORTED, + Status.INTERNAL, + Status.RESOURCE_EXHAUSTED, + Status.FAILED_PRECONDITION, + Status.INVALID_ARGUMENT)) { + upstreamFailure.set(failure); + assertThatThrownBy(reader::readCurrent).isInstanceOf(InvalidJwksException.class); + } + } + + @Test + void oversizedFrameIsDeniedByActualTransportBeforeCodec() throws Exception { + var huge = + response().toBuilder() + .setPublicJwks( + ByteString.copyFrom(new byte[AccountPublicJwksReadCodec.MAX_RESPONSE_BYTES + 1])) + .build(); + start(accountIdentity, huge, false, false); + assertThatThrownBy(() -> client().readCurrent()).isInstanceOf(InvalidJwksException.class); + } + + @Test + void unknownWireFieldsAreInvalidRatherThanOutage() throws Exception { + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + start(accountIdentity, response().toBuilder().setUnknownFields(unknown).build(), false, false); + assertThatThrownBy(() -> client().readCurrent()).isInstanceOf(InvalidJwksException.class); + } + + private void start( + Identity identity, + GetCurrentAccountPublicJwksResponse reply, + boolean neverReply, + boolean unavailable) + throws Exception { + upstreamFailure.set(unavailable ? Status.UNAVAILABLE : null); + upstreamReply.set(reply); + // This fixture mimics only the private Account read, and enforces the caller's exact URI. + var producer = + new AccountPublicJwksReadServiceGrpc.AccountPublicJwksReadServiceImplBase() { + @Override + public void getCurrentPublicJwks( + GetCurrentAccountPublicJwksRequest incoming, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !SESSION_URI.equals(peer.uri())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + clientUri.set(peer.uri()); + request.set(incoming); + AccountPublicJwksReadCodec.requireRequest(incoming); + Status failure = upstreamFailure.get(); + if (failure != null) observer.onError(failure.asRuntimeException()); + else if (!neverReply) { + observer.onNext(upstreamReply.get()); + observer.onCompleted(); + } + } + }; + ServerInterceptor captureHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + authorization.set( + headers.get(Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER))); + return next.startCall(call, headers); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.key(), identity.certificate())) + .trustManager(ca.certificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + producer, captureHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private AccountPublicJwksReadClient client() throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("localhost:" + server.getPort()); + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + pem("client.crt", "CERTIFICATE", clientIdentity.certificate().getEncoded()).toString()); + tls.setPrivateKey( + pem("client.key", "PRIVATE KEY", clientIdentity.key().getEncoded()).toString()); + tls.setCaCert(pem("ca.crt", "CERTIFICATE", ca.certificate().getEncoded()).toString()); + return new AccountPublicJwksReadClient(endpoints, tls, new GrpcChannelFactory(), "test"); + } + + private static PublicJwksSnapshot snapshot() { + return new PublicJwksSnapshot( + new SourceIdentity( + "test", + "test-cluster", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "revision-1", + "https://kubernetes.example:6443", + "a".repeat(64)), + PUBLIC_BYTES); + } + + private static GetCurrentAccountPublicJwksResponse response() { + return AccountPublicJwksReadCodec.response(snapshot()); + } + + private static GetCurrentAccountPublicJwksResponse denyResponse() { + return AccountPublicJwksReadCodec.response( + new ReadResult(snapshot().sourceIdentity(), new byte[0], true, false)); + } + + private static Path pem(String name, String type, byte[] bytes) throws Exception { + return Files.writeString( + temporaryDirectory.resolve(name), + "-----BEGIN " + + type + + "-----\n" + + Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes) + + "\n-----END " + + type + + "-----\n", + StandardCharsets.US_ASCII); + } + + private static Identity issue(String name, Identity issuer, boolean isCa, List uris) + throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keys = generator.generateKeyPair(); + X500Name subject = new X500Name("CN=" + name); + X500Name issuerName = + issuer == null + ? subject + : new X500Name(issuer.certificate().getSubjectX500Principal().getName()); + Instant now = Instant.now(); + var builder = + new JcaX509v3CertificateBuilder( + issuerName, + new BigInteger(120, new java.security.SecureRandom()).add(BigInteger.ONE), + Date.from(now.minusSeconds(60)), + Date.from(now.plus(Duration.ofDays(1))), + subject, + keys.getPublic()); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(isCa)); + builder.addExtension( + Extension.keyUsage, + true, + new KeyUsage( + isCa + ? KeyUsage.keyCertSign | KeyUsage.cRLSign + : KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); + if (!isCa) { + builder.addExtension( + Extension.extendedKeyUsage, + false, + new ExtendedKeyUsage( + new KeyPurposeId[] {KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); + List sans = new ArrayList<>(); + sans.add(new GeneralName(GeneralName.dNSName, "localhost")); + sans.add(new GeneralName(GeneralName.iPAddress, "127.0.0.1")); + for (String uri : uris) sans.add(new GeneralName(GeneralName.uniformResourceIdentifier, uri)); + builder.addExtension( + Extension.subjectAlternativeName, + false, + new GeneralNames(sans.toArray(GeneralName[]::new))); + } + var signer = + new JcaContentSignerBuilder("SHA256withRSA") + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .build(issuer == null ? keys.getPrivate() : issuer.key()); + X509Certificate certificate = + new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME) + .getCertificate(builder.build(signer)); + return new Identity(keys.getPrivate(), certificate); + } + + private record Identity(PrivateKey key, X509Certificate certificate) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfigurationTest.java new file mode 100644 index 0000000000..48587cb804 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfigurationTest.java @@ -0,0 +1,209 @@ +package net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockingDetails; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCoordinationQualification; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.ComponentScan.Filter; +import org.springframework.context.annotation.FilterType; +import org.springframework.transaction.PlatformTransactionManager; + +class AuthenticatedGameplayRuntimeConfigurationTest { + private static final String ENABLED = "firemud.game-session.authenticated-gameplay.enabled=true"; + + @Test + void absentOrFalseSelectorLeavesRuntimeUnregisteredEvenWithAllAuthorities() { + for (String property : + new String[] {"", "firemud.game-session.authenticated-gameplay.enabled=false"}) { + var runner = infrastructure().withUserConfiguration(ScannedComposition.class); + if (!property.isEmpty()) runner = runner.withPropertyValues(property); + runner.run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(InitialGameplayLoginCoordinationQualification.class); + assertThat(context).hasSingleBean(AccountAsymmetricJwtVerifier.class); + assertThat(context).doesNotHaveBean(CanonicalGameplayLoginAccountClient.class); + assertThat(context).doesNotHaveBean(InitialGameplayLoginOwner.class); + assertThat(context).doesNotHaveBean(DirectTextWorldSelectionService.class); + assertThat(context).doesNotHaveBean(DirectTextAuthenticatedLobbyOwner.class); + }); + } + } + + @Test + void componentScanComposesRealOwnersFromSeparateAuthorities() { + infrastructure() + .withUserConfiguration(ScannedComposition.class) + .withPropertyValues(ENABLED) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(CanonicalGameplayLoginAccountClient.class); + assertThat(context).hasSingleBean(InitialGameplayLoginOwner.class); + assertThat(context).hasSingleBean(DirectTextWorldSelectionService.class); + assertThat(context).hasSingleBean(DirectTextAuthenticatedLobbyOwner.class); + verifyNoInteractions( + context.getBean(InitialGameplayLoginRedisBinding.class), + context.getBean(InitialGameplayLoginCoordinationQualification.class), + context.getBean(AccountAsymmetricJwtVerifier.class), + context.getBean(CanonicalPlayerRouteReadService.class), + context.getBean(DSLContext.class)); + // Spring invokes this ordinary client's @PostConstruct callback, but composition + // must make no Account RPC or other client call. + assertThat(mockingDetails(context.getBean(AccountClient.class)).getInvocations()) + .extracting(invocation -> invocation.getMethod().getName()) + .containsExactly("init"); + }); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void composesWithRuntimeRegisteredBeforeOrAfterAuthorityConfiguration(boolean runtimeFirst) { + var configurations = + runtimeFirst + ? new Class[] { + AuthenticatedGameplayRuntimeConfiguration.class, ZDeliveredAuthorities.class + } + : new Class[] { + ZDeliveredAuthorities.class, AuthenticatedGameplayRuntimeConfiguration.class + }; + infrastructure() + .withUserConfiguration(configurations) + .withPropertyValues(ENABLED) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(CanonicalGameplayLoginAccountClient.class); + assertThat(context).hasSingleBean(InitialGameplayLoginOwner.class); + assertThat(context).hasSingleBean(DirectTextWorldSelectionService.class); + assertThat(context).hasSingleBean(DirectTextAuthenticatedLobbyOwner.class); + }); + } + + @ParameterizedTest + @ValueSource(strings = {"redis", "qualification", "verifier", "routes"}) + void enabledRuntimeFailsStartupForEveryMissingAuthority(String missing) { + infrastructure() + .withUserConfiguration(ScannedComposition.class) + .withPropertyValues(ENABLED, "fixture.authority." + missing + "=false") + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(NoSuchBeanDefinitionException.class); + }); + } + + private static ApplicationContextRunner infrastructure() { + return new ApplicationContextRunner() + .withSystemProperties("firemud.grpc.tls-reload.enabled=false") + .withPropertyValues("firemud.grpc.workload-namespace=test") + .withBean(ServiceEndpointsProperties.class, ServiceEndpointsProperties::new) + .withBean( + CommonGrpcClientProperties.class, + () -> { + var tls = new CommonGrpcClientProperties(); + tls.setCaCert("controlled-ca"); + tls.setCertChain("controlled-certificate"); + tls.setPrivateKey("controlled-private-key"); + return tls; + }) + .withBean(GrpcChannelFactory.class, AuthenticatedGameplayRuntimeConfigurationTest::channels) + .withBean(BlockingGrpcStubCustomizer.class, BlockingGrpcStubCustomizer::noop) + .withBean(DSLContext.class, () -> mock(DSLContext.class)) + .withBean( + "transactionManager", + PlatformTransactionManager.class, + () -> mock(PlatformTransactionManager.class)) + .withBean(AccountClient.class, () -> mock(AccountClient.class)) + .withBean(GameplayWorldCatalog.class, () -> mock(GameplayWorldCatalog.class)); + } + + private static GrpcChannelFactory channels() { + var factory = mock(GrpcChannelFactory.class); + try { + when(factory.buildChannel(anyString(), anyInt(), any(), anyBoolean())) + .thenReturn(mock(ManagedChannel.class)); + } catch (SSLException impossible) { + throw new AssertionError(impossible); + } + return factory; + } + + @TestConfiguration(proxyBeanMethods = false) + @ComponentScan( + basePackageClasses = AuthenticatedGameplayRuntimeConfiguration.class, + useDefaultFilters = false, + includeFilters = + @Filter( + type = FilterType.ASSIGNABLE_TYPE, + classes = { + AuthenticatedGameplayRuntimeConfiguration.class, + ZDeliveredAuthorities.class + })) + static class ScannedComposition {} + + // Controlled authority doubles prove registration only, not external maintenance qualification, + // source custody, authenticated RPCs or gameplay activation. + @TestConfiguration(value = "zDeliveredAuthorities", proxyBeanMethods = false) + static class ZDeliveredAuthorities { + @Bean + @ConditionalOnProperty(prefix = "fixture.authority", name = "redis", matchIfMissing = true) + InitialGameplayLoginRedisBinding redis() { + return mock(InitialGameplayLoginRedisBinding.class); + } + + @Bean + @ConditionalOnProperty( + prefix = "fixture.authority", + name = "qualification", + matchIfMissing = true) + InitialGameplayLoginCoordinationQualification qualification() { + return mock(InitialGameplayLoginCoordinationQualification.class); + } + + @Bean + @ConditionalOnProperty(prefix = "fixture.authority", name = "verifier", matchIfMissing = true) + AccountAsymmetricJwtVerifier verifier() { + return mock(AccountAsymmetricJwtVerifier.class); + } + + @Bean + @ConditionalOnProperty(prefix = "fixture.authority", name = "routes", matchIfMissing = true) + CanonicalPlayerRouteReadService routes() { + return mock(CanonicalPlayerRouteReadService.class); + } + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfigurationTest.java new file mode 100644 index 0000000000..f5079c7290 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfigurationTest.java @@ -0,0 +1,352 @@ +package net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.Base64; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceCustodyRejectedException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.TrustedPublicJwksSource; +import net.firedevops.firemud.gamesession.service.AccountPublicJwksReadClient; +import net.firedevops.firemud.gamesession.service.GameSessionAccountPublicJwksSource; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.slf4j.LoggerFactory; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +class GameSessionAccountPublicJwksConfigurationTest { + private static final String PREFIX = "firemud.game-session.account-public-jwks."; + + @Test + void disabledByDefaultAndWhenExplicitlyDisabled() { + for (String enabled : new String[] {"", PREFIX + "enabled=false"}) { + var runner = + new ApplicationContextRunner() + .withUserConfiguration(GameSessionAccountPublicJwksConfiguration.class); + if (!enabled.isEmpty()) runner = runner.withPropertyValues(enabled); + runner.run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(AccountPublicJwksReadClient.class); + assertThat(context).doesNotHaveBean(GameSessionAccountPublicJwksSource.class); + assertThat(context).doesNotHaveBean(AccountPublicJwksCache.class); + assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); + assertThat(context) + .doesNotHaveBean(GameSessionAccountPublicJwksConfiguration.PublicJwksRefresh.class); + }); + } + } + + @Test + void enablingWithoutDeliveredSourcesFailsComposition() { + new ApplicationContextRunner() + .withUserConfiguration(GameSessionAccountPublicJwksConfiguration.class) + .withPropertyValues(PREFIX + "enabled=true") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void publicOnlyClientRequiresExplicitEndpointMutualTlsAndNamespace() { + var config = new GameSessionAccountPublicJwksConfiguration(); + var endpoints = new ServiceEndpointsProperties(); + var tls = new CommonGrpcClientProperties(); + var channels = new GrpcChannelFactory(); + assertThatThrownBy(() -> config.accountPublicJwksReadClient(endpoints, tls, channels, "test")) + .isInstanceOf(IllegalArgumentException.class); + endpoints.setAccountService("account-service:6565"); + tls.setCaCert("delivered-ca"); + tls.setCertChain("delivered-certificate"); + tls.setPrivateKey("delivered-private-key"); + assertThat(config.accountPublicJwksReadClient(endpoints, tls, channels, "test")).isNotNull(); + tls.setPlaintext(true); + assertThatThrownBy(() -> config.accountPublicJwksReadClient(endpoints, tls, channels, "test")) + .isInstanceOf(IllegalArgumentException.class); + tls.setPlaintext(false); + assertThatThrownBy(() -> config.accountPublicJwksReadClient(endpoints, tls, channels, "")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void cacheAgeMustBeExplicitFiniteAndAllowBoundedRefreshCadence() { + for (long invalid : new long[] {-1, 0, 1, 1999, 300001, Long.MAX_VALUE}) { + assertThatThrownBy( + () -> GameSessionAccountPublicJwksConfiguration.requiredMaximumAge(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat(GameSessionAccountPublicJwksConfiguration.requiredMaximumAge(2000)) + .isEqualTo(Duration.ofSeconds(2)); + assertThat(GameSessionAccountPublicJwksConfiguration.requiredMaximumAge(300000)) + .isEqualTo(Duration.ofMinutes(5)); + } + + @Test + void cacheInitializesFromActualSourcePinAndRefreshesBeforeCompositionReturns() { + var source = mock(GameSessionAccountPublicJwksSource.class); + SourceIdentity identity = + new SourceIdentity( + "test", + "cluster", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "revision-1", + "https://kubernetes.example:6443", + "a".repeat(64)); + when(source.sourceIdentity()).thenReturn(identity); + when(source.load()).thenThrow(new SourceUnavailableException()); + assertThatThrownBy( + () -> + new GameSessionAccountPublicJwksConfiguration() + .accountPublicJwksCache(source, 2000)) + .isInstanceOf(SourceUnavailableException.class); + verify(source).sourceIdentity(); + verify(source).load(); + } + + @Test + void sharedCacheAndVerifierComposeFromAuthenticatedSnapshotWithoutReadinessMetadata() + throws Exception { + // Controlled source only. This is composition proof, not producer or deployment custody. + var source = mock(GameSessionAccountPublicJwksSource.class); + SourceIdentity identity = + new SourceIdentity( + "test", + "cluster", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "revision-1", + "https://kubernetes.example:6443", + "a".repeat(64)); + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey publicKey = (RSAPublicKey) generator.generateKeyPair().getPublic(); + String modulus = unsigned(publicKey.getModulus().toByteArray()); + String exponent = unsigned(publicKey.getPublicExponent().toByteArray()); + byte[] jwks = + ("{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"test-key\"," + + "\"alg\":\"RS256\",\"use\":\"sig\",\"n\":\"" + + modulus + + "\",\"e\":\"" + + exponent + + "\"}]}") + .getBytes(StandardCharsets.US_ASCII); + when(source.sourceIdentity()).thenReturn(identity); + when(source.load()).thenReturn(new PublicJwksSnapshot(identity, jwks)); + var configuration = new GameSessionAccountPublicJwksConfiguration(); + + AccountPublicJwksCache cache = configuration.accountPublicJwksCache(source, 2000); + + assertThat(cache.sourceIdentity()).isEqualTo(identity); + assertThat(cache.keyFor("test-key")).isEqualTo(publicKey); + assertThat(configuration.accountAsymmetricJwtVerifier(cache)).isNotNull(); + verify(source).load(); + } + + private static String unsigned(byte[] bytes) { + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes); + } + + @Test + void preparedStartupStaysEmptyAndScheduledInvocationRequiresEligibleRecovery() throws Exception { + var source = mock(GameSessionAccountPublicJwksSource.class); + SourceIdentity identity = + new SourceIdentity( + "test", + "cluster", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "revision-1", + "https://kubernetes.example:6443", + "a".repeat(64)); + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + var key = (java.security.interfaces.RSAPublicKey) generator.generateKeyPair().getPublic(); + String json = + "{\"keys\":[{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\"," + + "\"kid\":\"known\",\"n\":\"" + + unsigned(key.getModulus().toByteArray()) + + "\",\"e\":\"" + + unsigned(key.getPublicExponent().toByteArray()) + + "\"}]}"; + byte[] bytes = json.getBytes(java.nio.charset.StandardCharsets.UTF_8); + var denied = new java.util.concurrent.atomic.AtomicBoolean(true); + when(source.sourceIdentity()).thenReturn(identity); + when(source.isPreparedDenied()).thenAnswer(invocation -> denied.get()); + when(source.load()).thenThrow(new AccountPublicJwksCache.SourcePreparedDenyException()); + var cache = + new GameSessionAccountPublicJwksConfiguration().accountPublicJwksCache(source, 2000); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + var scheduler = mock(ScheduledExecutorService.class); + var task = ArgumentCaptor.forClass(Runnable.class); + try (var refresh = + new GameSessionAccountPublicJwksConfiguration.PublicJwksRefresh( + cache, Duration.ofSeconds(2), scheduler)) { + verify(scheduler) + .scheduleWithFixedDelay(task.capture(), eq(1000L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + org.mockito.Mockito.doThrow(new SourceUnavailableException()).when(source).load(); + task.getValue().run(); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + denied.set(false); + // An unqualified snapshot, including PREPUBLISHED beside an older commit, cannot recover. + org.mockito.Mockito.doReturn(new PublicJwksSnapshot(identity, bytes, false)) + .when(source) + .load(); + task.getValue().run(); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + // Source tests prove the Account and protected same-pin mount gate behind this flag. + org.mockito.Mockito.doReturn(new PublicJwksSnapshot(identity, bytes, true)) + .when(source) + .load(); + task.getValue().run(); + assertThat(cache.keyFor("known")).isEqualTo(key); + } + verify(scheduler).shutdownNow(); + } + + @Test + void boundedProactiveRefreshSurvivesDenialAndStopsAtContextShutdown() { + for (long age : new long[] {2000, 300000}) { + var cache = mock(AccountPublicJwksCache.class); + var scheduler = mock(ScheduledExecutorService.class); + var task = ArgumentCaptor.forClass(Runnable.class); + var refresh = + new GameSessionAccountPublicJwksConfiguration.PublicJwksRefresh( + cache, Duration.ofMillis(age), scheduler); + verify(scheduler) + .scheduleWithFixedDelay( + task.capture(), eq(age / 2), eq(age / 2), eq(TimeUnit.MILLISECONDS)); + doThrow(new AccountPublicJwksCache.SourcePreparedDenyException()) + .doThrow(new SourceUnavailableException()) + .doNothing() + .when(cache) + .refresh(); + task.getValue().run(); + task.getValue().run(); + task.getValue().run(); + verify(cache, times(3)).refresh(); + refresh.close(); + verify(scheduler).shutdownNow(); + } + } + + @Test + void terminalSourceRejectionLatchesCacheAndLogsOneFixedErrorWithoutEvidence() { + var source = mock(TrustedPublicJwksSource.class); + when(source.load()).thenThrow(new SourceCustodyRejectedException()); + SourceIdentity identity = + new SourceIdentity( + "test", + "cluster", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "revision-1", + "https://kubernetes.example:6443", + "a".repeat(64)); + var cache = + new AccountPublicJwksCache(source, identity, Clock.systemUTC(), Duration.ofSeconds(2)); + var scheduler = mock(ScheduledExecutorService.class); + var task = ArgumentCaptor.forClass(Runnable.class); + Logger logger = + (Logger) + LoggerFactory.getLogger( + GameSessionAccountPublicJwksConfiguration.PublicJwksRefresh.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + + try (var refresh = + new GameSessionAccountPublicJwksConfiguration.PublicJwksRefresh( + cache, Duration.ofSeconds(2), scheduler)) { + verify(scheduler) + .scheduleWithFixedDelay(task.capture(), eq(1000L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + task.getValue().run(); + task.getValue().run(); + verify(source).load(); + assertThat(appender.list).hasSize(1); + var event = appender.list.getFirst(); + assertThat(event.getLevel()).isEqualTo(Level.ERROR); + assertThat(event.getFormattedMessage()) + .isEqualTo( + "Account public JWKS cache refused until explicit requalification: SOURCE_REJECTED"); + assertThat(event.getArgumentArray()).isNullOrEmpty(); + assertThat(event.getThrowableProxy()).isNull(); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + verify(scheduler).shutdownNow(); + } + + @Test + void transientSourceUnavailabilityLogsSeparatelyAndAllowsNextRefresh() { + var cache = mock(AccountPublicJwksCache.class); + doThrow(new SourceUnavailableException()).doNothing().when(cache).refresh(); + var scheduler = mock(ScheduledExecutorService.class); + var task = ArgumentCaptor.forClass(Runnable.class); + Logger logger = + (Logger) + LoggerFactory.getLogger( + GameSessionAccountPublicJwksConfiguration.PublicJwksRefresh.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + + try (var refresh = + new GameSessionAccountPublicJwksConfiguration.PublicJwksRefresh( + cache, Duration.ofSeconds(2), scheduler)) { + verify(scheduler) + .scheduleWithFixedDelay(task.capture(), eq(1000L), eq(1000L), eq(TimeUnit.MILLISECONDS)); + task.getValue().run(); + task.getValue().run(); + verify(cache, times(2)).refresh(); + assertThat(appender.list).hasSize(1); + var event = appender.list.getFirst(); + assertThat(event.getLevel()).isEqualTo(Level.WARN); + assertThat(event.getFormattedMessage()) + .isEqualTo("Account public JWKS refresh unavailable: SOURCE_UNAVAILABLE"); + assertThat(event.getArgumentArray()).isNullOrEmpty(); + assertThat(event.getThrowableProxy()).isNull(); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + verify(scheduler).shutdownNow(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java new file mode 100644 index 0000000000..e0c18fdfee --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java @@ -0,0 +1,216 @@ +package net.firedevops.firemud.gamesession.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import java.time.Duration; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProbeOwnerClient; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCoordinationQualification; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding; +import net.firedevops.firemud.gamesession.service.LettuceInitialGameplayLoginConnectionProvider; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +/** Dedicated Redis composition proof with a controlled client; no live source is contacted. */ +class InitialGameplayLoginProtectedSourcesConfigurationTest { + private static final String PREFIX = + "firemud.game-session.initial-gameplay-login.protected-sources."; + private static final String COORDINATION_URI = + "rediss://gamesession_coord_app:test-only-password@coordination.example.invalid:6380/0"; + private final InitialGameplayLoginProtectedSourcesConfiguration configuration = + new InitialGameplayLoginProtectedSourcesConfiguration(); + + @Test + void sourcesAreDisabledByDefaultAndWhenExplicitlyDisabled() { + for (String enabled : new String[] {"", PREFIX + "enabled=false"}) { + var runner = + new ApplicationContextRunner() + .withUserConfiguration(InitialGameplayLoginProtectedSourcesConfiguration.class); + if (!enabled.isEmpty()) runner = runner.withPropertyValues(enabled); + runner.run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); + assertThat(context).doesNotHaveBean(InitialGameplayLoginRedisBinding.class); + assertThat(context) + .doesNotHaveBean(LettuceInitialGameplayLoginConnectionProvider.class); + }); + } + } + + @Test + void enablingWithoutDeliveredCoordinationInputsFailsComposition() { + new ApplicationContextRunner() + .withUserConfiguration(InitialGameplayLoginProtectedSourcesConfiguration.class) + .withPropertyValues(PREFIX + "enabled=true") + .run(context -> assertThat(context).hasFailed()); + } + + @Test + void dedicatedUriRequiresExactTlsPrincipalDatabaseAndFiniteDeadline() { + RedisURI uri = + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + COORDINATION_URI, 875); + + assertThat(uri.getHost()).isEqualTo("coordination.example.invalid"); + assertThat(uri.getPort()).isEqualTo(6380); + assertThat(uri.isSsl()).isTrue(); + assertThat(uri.isVerifyPeer()).isTrue(); + assertThat(uri.getDatabase()).isZero(); + assertThat(uri.getTimeout()).isEqualTo(Duration.ofMillis(875)); + var credentials = + uri.getCredentialsProvider().resolveCredentials().block(Duration.ofSeconds(1)); + assertThat(credentials).isNotNull(); + assertThat(credentials.getUsername()).isEqualTo(InitialGameplayLoginRedisBinding.PRINCIPAL); + assertThat(credentials.getPassword()).containsExactly("test-only-password".toCharArray()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "", + "redis://gamesession_coord_app:secret@coordination.example.invalid:6380/0", + "rediss://default:secret@coordination.example.invalid:6380/0", + "rediss://account_coord_app:secret@coordination.example.invalid:6380/0", + "rediss://gamesession_coord_app:@coordination.example.invalid:6380/0", + "rediss://gamesession_coord_app:secret@coordination.example.invalid/0", + "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380", + "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380/1", + "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380/0?verifyPeer=false", + "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380/0#alternate", + "rediss://gamesession_coord_app:secret@coordination.example.invalid:99999/0", + "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380/0 bad" + }) + void rejectsAmbientPlaintextChangedOrAmbiguousCoordinationSources(String uri) { + assertThatThrownBy( + () -> + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri(uri, 875)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Protected Game Session initial LOGIN sources required") + .hasNoCause(); + } + + @ParameterizedTest + @ValueSource(ints = {-1, 0, 60_001}) + void rejectsUnboundedCommandDeadlines(int timeoutMillis) { + assertThatThrownBy( + () -> + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + COORDINATION_URI, timeoutMillis)) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause(); + } + + @Test + void sourceBindingRequiresExplicitProfileIdentityAndAcknowledgements() { + var connections = mock(LettuceInitialGameplayLoginConnectionProvider.class); + assertThatThrownBy( + () -> + configuration.initialGameplayLoginRedisBinding( + connections, "", "REPLICATED", 1, 1, 875)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Protected Coordination binding identity required") + .hasNoCause(); + assertThatThrownBy( + () -> + configuration.initialGameplayLoginRedisBinding( + connections, "delivered-binding", "", 1, 1, 875)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Protected Coordination profile is invalid") + .hasNoCause(); + assertThatThrownBy( + () -> + configuration.initialGameplayLoginRedisBinding( + connections, "delivered-binding", "REPLICATED", 1, 0, 875)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Explicit Coordination ACK policy is invalid") + .hasNoCause(); + assertThatThrownBy( + () -> + configuration.initialGameplayLoginRedisBinding( + connections, "delivered-binding", "SINGLE_NODE_NO_FAILOVER", 1, 1, 875)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Explicit Coordination ACK policy is invalid") + .hasNoCause(); + verifyNoInteractions(connections); + } + + @Test + void invalidBindingDiagnosticsDoNotRetainDeliveredValuesOrCauses() { + var connections = mock(LettuceInitialGameplayLoginConnectionProvider.class); + assertThatThrownBy( + () -> + configuration.initialGameplayLoginRedisBinding( + connections, + "delivered-binding", + "rediss://user:do-not-log@private.example.invalid:6380/0", + 1, + 1, + 875)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Protected Coordination profile is invalid") + .hasNoCause(); + assertThatThrownBy( + () -> + configuration.initialGameplayLoginRedisBinding( + connections, "do-not-log-binding\n", "REPLICATED", 1, 1, 875)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Protected Coordination binding identity required") + .hasNoCause(); + verifyNoInteractions(connections); + } + + @Test + void concreteRedisSourceDoesNotSupplyVerifierMaintenanceAuthorityOrLogin() { + var client = mock(RedisClient.class); + try (var factory = mockStatic(RedisClient.class)) { + factory.when(() -> RedisClient.create(any(RedisURI.class))).thenReturn(client); + new ApplicationContextRunner() + .withUserConfiguration( + InitialGameplayLoginProtectedSourcesConfiguration.class, + AuthenticatedGameplayRuntimeConfiguration.class) + .withPropertyValues(completeProperties()) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(GameSessionJwtReadinessProbeOwnerClient.class); + assertThat(context).doesNotHaveBean(AccountPublicJwksCache.class); + assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); + assertThat(context).hasSingleBean(InitialGameplayLoginRedisBinding.class); + assertThat(context) + .doesNotHaveBean(InitialGameplayLoginCoordinationQualification.class); + assertThat(context).doesNotHaveBean(InitialGameplayLoginOwner.class); + var binding = context.getBean(InitialGameplayLoginRedisBinding.class); + assertThat(binding.protectedBindingId()).isEqualTo("delivered-binding"); + assertThat(binding.acknowledgementPolicy().requiredReplicaAofCount()).isEqualTo(1); + }); + verify(client, times(1)).shutdown(); + } + } + + private static String[] completeProperties() { + return new String[] { + PREFIX + "enabled=true", + PREFIX + "coordination.uri=" + COORDINATION_URI, + PREFIX + "coordination.command-timeout-millis=875", + PREFIX + "coordination.protected-binding-id=delivered-binding", + PREFIX + "coordination.profile=REPLICATED", + PREFIX + "coordination.required-local-aof-count=1", + PREFIX + "coordination.required-replica-aof-count=1", + PREFIX + "coordination.acknowledgement-timeout-millis=875" + }; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAccountPublicJwksSourceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAccountPublicJwksSourceTest.java new file mode 100644 index 0000000000..7fa4fb52c4 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAccountPublicJwksSourceTest.java @@ -0,0 +1,748 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.GeneralSecurityException; +import java.security.KeyPairGenerator; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceCustodyRejectedException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourcePreparedDenyException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.TrustedPublicJwksSource; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.UnknownKeyException; +import net.firedevops.firemud.common.security.AccountPublicJwksReadCodec.ReadResult; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Controlled Account snapshots exercise custody checks, not Account producer or deployed PKI. */ +class GameSessionAccountPublicJwksSourceTest { + private static final byte[] BYTES = "{\"keys\":[]}".getBytes(StandardCharsets.US_ASCII); + @TempDir Path temporaryDirectory; + + @Test + void pinsActualAccountIdentityAndCopiesExactProtectedProjectionBytes() throws Exception { + Path root = Files.createDirectory(temporaryDirectory.resolve("projection")); + Path version = Files.createDirectory(root.resolve("..version1")); + Path file = Files.write(version.resolve("jwks.json"), BYTES); + Files.setPosixFilePermissions(root, PosixFilePermissions.fromString("rwxr-xr-x")); + Files.setPosixFilePermissions(version, PosixFilePermissions.fromString("rwxr-xr-x")); + Files.setPosixFilePermissions(file, PosixFilePermissions.fromString("r--r--r--")); + Files.createSymbolicLink(root.resolve("..data"), Path.of("..version1")); + Files.createSymbolicLink(root.resolve("jwks.json"), Path.of("..data/jwks.json")); + long uid = + ((Number) Files.getAttribute(root, "unix:uid", LinkOption.NOFOLLOW_LINKS)).longValue(); + var projection = new ProtectedAccountPublicJwksProjection(root.resolve("jwks.json"), uid); + var source = source(() -> snapshot(identity("test", "revision-1")), projection); + + PublicJwksSnapshot result = source.load(); + byte[] modified = result.jwksBytes(); + modified[0] = 0; + + assertThat(source.sourceIdentity()).isEqualTo(identity("test", "revision-1")); + assertThat(result.jwksBytes()).containsExactly(BYTES); + assertThat(source.load().jwksBytes()).containsExactly(BYTES); + } + + @Test + void rejectsReplacementForeverWithoutSilentlyRepinning() throws Exception { + AtomicReference current = new AtomicReference<>(identity("test", "revision-1")); + var source = source(() -> snapshot(current.get()), projection(BYTES, BYTES)); + assertThat(source.sourceIdentity()).isEqualTo(current.get()); + current.set(identity("test", "revision-2")); + assertInvalid(source); + current.set(identity("test", "revision-1")); + assertInvalid(source); + assertThatThrownBy(source::sourceIdentity).isInstanceOf(SourceCustodyRejectedException.class); + } + + @Test + void crossNamespaceEvidenceIsInvalidEvenWithMatchingBytes() throws Exception { + assertInvalid( + source(() -> snapshot(identity("other", "revision-1")), projection(BYTES, BYTES))); + } + + @Test + void exactBytesMatterEvenForEquivalentJson() throws Exception { + byte[] reformatted = "{ \"keys\": [] }".getBytes(StandardCharsets.US_ASCII); + assertInvalid( + source( + () -> snapshot(identity("test", "revision-1")), projection(reformatted, reformatted))); + } + + @Test + void rejectsMountedBytesChangingAcrossAccountReads() throws Exception { + byte[] changed = "{\"keys\":[{}]}".getBytes(StandardCharsets.US_ASCII); + assertInvalid( + source(() -> snapshot(identity("test", "revision-1")), projection(BYTES, changed))); + } + + @Test + void rejectsAccountIdentityOrBytesChangingAcrossMountedReads() throws Exception { + for (boolean changeIdentity : new boolean[] {false, true}) { + AtomicInteger calls = new AtomicInteger(); + TrustedPublicJwksSource account = + () -> { + if (calls.incrementAndGet() == 1) return snapshot(identity("test", "revision-1")); + return changeIdentity + ? snapshot(identity("test", "revision-2")) + : new PublicJwksSnapshot(identity("test", "revision-1"), new byte[] {1}); + }; + assertInvalid(source(account, projection(BYTES, BYTES))); + } + } + + @Test + void actualAccountOutageIsRetryableAndDoesNotRepin() throws Exception { + AtomicInteger calls = new AtomicInteger(); + TrustedPublicJwksSource account = + () -> { + if (calls.incrementAndGet() == 1) throw new SourceUnavailableException(); + return snapshot(identity("test", "revision-1")); + }; + var source = source(account, projection(BYTES, BYTES)); + assertThatThrownBy(source::load).isInstanceOf(SourceUnavailableException.class); + assertThat(source.load().sourceIdentity()).isEqualTo(identity("test", "revision-1")); + } + + @Test + void outageCannotHideRemovedOrChangedLocalCustody() throws Exception { + var projection = mock(ProtectedAccountPublicJwksProjection.class); + when(projection.read()).thenAnswer(invocation -> BYTES.clone()); + AtomicReference unavailable = new AtomicReference<>(); + TrustedPublicJwksSource account = + () -> { + if (unavailable.get() != null) throw unavailable.get(); + return snapshot(identity("test", "revision-1")); + }; + var source = source(account, projection); + source.load(); + unavailable.set(new SourceUnavailableException()); + when(projection.read()).thenAnswer(invocation -> new byte[] {1}); + assertInvalid(source); + } + + @Test + void validUnchangedProjectionCanSurviveAFiniteAccountOutage() throws Exception { + AtomicReference unavailable = new AtomicReference<>(false); + TrustedPublicJwksSource account = + () -> { + if (unavailable.get()) throw new SourceUnavailableException(); + return snapshot(identity("test", "revision-1")); + }; + var source = source(account, projection(BYTES, BYTES)); + source.load(); + unavailable.set(true); + assertThatThrownBy(source::load).isInstanceOf(SourceUnavailableException.class); + unavailable.set(false); + assertThat(source.load().sourceIdentity()).isEqualTo(identity("test", "revision-1")); + } + + @Test + void missingOrUnsafeProjectionCannotBecomeAnOutageException() throws Exception { + var missing = + new ProtectedAccountPublicJwksProjection(temporaryDirectory.resolve("jwks.json"), 0L); + assertInvalid(source(() -> snapshot(identity("test", "revision-1")), missing)); + var unsafe = mock(ProtectedAccountPublicJwksProjection.class); + when(unsafe.read()).thenThrow(new IllegalArgumentException("unsafe test projection")); + assertInvalid(source(() -> snapshot(identity("test", "revision-1")), unsafe)); + } + + @Test + void absentSnapshotIsInvalid() throws Exception { + assertInvalid(source(() -> null, projection(BYTES, BYTES))); + } + + @Test + void qualifiedPublicationLagRecoversOnTheSameSourceWithoutRepinning() throws Exception { + var fixture = new PublicationFixture(); + fixture.source.load(); + fixture.publishNext(); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourceUnavailableException.class); + assertThat(fixture.source.sourceIdentity()).isEqualTo(identity("test", "revision-1")); + fixture.converge(); + assertThat(fixture.source.load().jwksBytes()).containsExactly(fixture.current.get()); + } + + @Test + void proactiveAndDemandLagPreserveOriginalAgeAndRecoverWithoutAdmittingUnknownKeys() + throws Exception { + for (boolean proactive : new boolean[] {true, false}) { + var fixture = new PublicationFixture(); + var cache = fixture.cache(); + cache.refresh(); + fixture.advance(5); + fixture.publishNext(); + if (proactive) { + cache.refresh(); + } else { + assertThatThrownBy(() -> cache.keyFor("next")).isInstanceOf(UnknownKeyException.class); + } + assertThat(cache.keyFor("known")).isEqualTo(fixture.key); + assertThatThrownBy(() -> cache.keyFor("next")).isInstanceOf(UnknownKeyException.class); + fixture.advance(5); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(SourceUnavailableException.class); + assertThatThrownBy(() -> cache.keyFor("next")) + .isInstanceOfAny(SourceUnavailableException.class, UnknownKeyException.class); + fixture.converge(); + fixture.advance(1); + assertThat(cache.keyFor("next")).isEqualTo(fixture.key); + cache.invalidateKid("known"); + cache.refresh(); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(UnknownKeyException.class); + fixture.pin.set(identity("test", "revision-2")); + assertThatThrownBy(cache::refresh).isInstanceOf(InvalidJwksException.class); + fixture.pin.set(identity("test", "revision-1")); + assertThatThrownBy(cache::refresh).isInstanceOf(InvalidJwksException.class); + assertThatThrownBy(() -> cache.keyFor("next")).isInstanceOf(InvalidJwksException.class); + } + } + + @Test + void hardDeniedKeysRemainDeniedAcrossPublicationLagAndRecovery() throws Exception { + var fixture = new PublicationFixture(); + var cache = fixture.cache(); + cache.refresh(); + cache.invalidateKid("known"); + fixture.publishNext(); + cache.refresh(); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(UnknownKeyException.class); + fixture.converge(); + cache.refresh(); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(UnknownKeyException.class); + assertThat(cache.keyFor("next")).isEqualTo(fixture.key); + } + + @Test + void qualifiedButChangedLocalBytesCannotBecomePublicationLag() throws Exception { + var fixture = new PublicationFixture(); + fixture.source.load(); + fixture.mounted.set(publicJwks(fixture.key, "unexplained")); + assertInvalid(fixture.source); + fixture.converge(); + assertInvalid(fixture.source); + } + + @Test + void fingerprintReplacementRemainsTerminalAfterPublicationLagConverges() throws Exception { + var fixture = new PublicationFixture(); + var cache = fixture.cache(); + cache.refresh(); + fixture.current.set(publicJwks(newPublicKey(), "known")); + cache.refresh(); + assertThat(cache.keyFor("known")).isEqualTo(fixture.key); + fixture.converge(); + assertThatThrownBy(cache::refresh).isInstanceOf(InvalidJwksException.class); + fixture.current.set(publicJwks(fixture.key, "known")); + fixture.converge(); + assertThatThrownBy(cache::refresh).isInstanceOf(InvalidJwksException.class); + } + + @Test + void invalidRemoteProfilesCannotBecomePublicationLag() throws Exception { + var key = newPublicKey(); + String valid = new String(publicJwks(key, "known"), StandardCharsets.US_ASCII); + for (String invalid : + new String[] { + "{broken", + "{\"keys\":[]}", + valid.replace("\"RS256\"", "\"HS256\""), + valid.replace("\"kty\":\"RSA\"", "\"d\":\"private\",\"kty\":\"RSA\"") + }) { + var fixture = new PublicationFixture(); + fixture.source.load(); + fixture.current.set(invalid.getBytes(StandardCharsets.US_ASCII)); + assertInvalid(fixture.source); + fixture.publishNext(); + fixture.converge(); + assertInvalid(fixture.source); + } + } + + @Test + void lagCannotHideChangedOrUnsafeProjectionDuringCustodyRecheck() throws Exception { + for (boolean unsafe : new boolean[] {false, true}) { + var fixture = new PublicationFixture(); + fixture.source.load(); + fixture.publishNext(); + if (unsafe) { + when(fixture.projection.read()) + .thenReturn(fixture.mounted.get().clone()) + .thenThrow(new IllegalArgumentException("unsafe projection")); + } else { + when(fixture.projection.read()) + .thenReturn(fixture.mounted.get().clone()) + .thenReturn(fixture.current.get().clone()); + } + assertInvalid(fixture.source); + } + } + + @Test + void matchedPublicationTransitionPreservesExpiryUntilALaterStableLoad() throws Exception { + for (boolean proactive : new boolean[] {true, false}) { + var fixture = new PublicationFixture(); + var cache = fixture.cache(); + cache.refresh(); + fixture.advance(5); + fixture.afterAccountRead.set( + () -> { + fixture.publishNext(); + fixture.converge(); + }); + if (proactive) { + cache.refresh(); + } else { + assertThatThrownBy(() -> cache.keyFor("next")).isInstanceOf(UnknownKeyException.class); + } + int readsAfterTransition = fixture.accountReads.get(); + assertThat(cache.keyFor("known")).isEqualTo(fixture.key); + assertThat(fixture.accountReads.get()).isEqualTo(readsAfterTransition); + assertThat(fixture.source.sourceIdentity()).isEqualTo(identity("test", "revision-1")); + fixture.advance(5); + assertThat(cache.keyFor("known")).isEqualTo(fixture.key); + assertThat(fixture.accountReads.get()).isEqualTo(readsAfterTransition + 2); + assertThat(cache.keyFor("next")).isEqualTo(fixture.key); + } + } + + @Test + void matchedTransitionDoesNotRenewExpiredCacheOrInstallAnUnknownKey() throws Exception { + var fixture = new PublicationFixture(); + var cache = fixture.cache(); + cache.refresh(); + fixture.advance(10); + fixture.afterAccountRead.set( + () -> { + fixture.publishNext(); + fixture.converge(); + }); + assertThatThrownBy(() -> cache.keyFor("next")).isInstanceOf(SourceUnavailableException.class); + cache.refresh(); + assertThat(cache.keyFor("next")).isEqualTo(fixture.key); + } + + @Test + void matchedTransitionCannotQualifyStartupOrAReplacementIdentity() throws Exception { + for (boolean qualified : new boolean[] {false, true}) { + var fixture = new PublicationFixture(); + if (qualified) fixture.source.load(); + fixture.afterAccountRead.set( + () -> { + fixture.publishNext(); + fixture.converge(); + if (qualified) fixture.pin.set(identity("test", "revision-2")); + }); + assertInvalid(fixture.source); + fixture.pin.set(identity("test", "revision-1")); + assertInvalid(fixture.source); + } + } + + @Test + void transitionRequiresAnExactValidAuthenticatedNewSnapshot() throws Exception { + for (boolean matched : new boolean[] {false, true}) { + var fixture = new PublicationFixture(); + fixture.source.load(); + fixture.afterAccountRead.set( + () -> { + fixture.current.set("{broken".getBytes(StandardCharsets.US_ASCII)); + fixture.mounted.set( + matched ? fixture.current.get() : publicJwks(fixture.key, "unexplained")); + }); + assertInvalid(fixture.source); + fixture.publishNext(); + fixture.converge(); + assertInvalid(fixture.source); + } + } + + @Test + void matchedTransitionCannotHideUnsafeOrChangedProjectionOnRecheck() throws Exception { + for (boolean unsafe : new boolean[] {false, true}) { + var fixture = new PublicationFixture(); + fixture.source.load(); + AtomicInteger projectionReads = new AtomicInteger(); + when(fixture.projection.read()) + .thenAnswer( + invocation -> { + if (projectionReads.incrementAndGet() == 3) { + if (unsafe) throw new IllegalArgumentException("unsafe projection"); + return publicJwks(fixture.key, "unexplained"); + } + return fixture.mounted.get().clone(); + }); + fixture.afterAccountRead.set( + () -> { + fixture.publishNext(); + fixture.converge(); + }); + assertInvalid(fixture.source); + assertInvalid(fixture.source); + } + } + + @Test + void separatelyObservedCustodyRejectionImmediatelyBlocksWarmCachedKeys() throws Exception { + var fixture = new PublicationFixture(); + var cache = fixture.cache(); + cache.refresh(); + assertThat(cache.keyFor("known")).isEqualTo(fixture.key); + byte[] original = fixture.mounted.get(); + fixture.mounted.set("tampered".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + assertInvalid(fixture.source); + assertThat(fixture.source.isCustodyRejected()).isTrue(); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(InvalidJwksException.class); + fixture.mounted.set(original); + assertThatThrownBy(cache::refresh).isInstanceOf(InvalidJwksException.class); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(InvalidJwksException.class); + } + + @Test + void preparedDenyAtStartupPinsIdentityAndRecoversOnlyFromEligibleCommittedSnapshot() + throws Exception { + var fixture = new PublicationFixture(); + assertThat(fixture.source.preparedDenyEpoch()).isZero(); + fixture.denied.set(true); + assertThat(fixture.source.sourceIdentity()).isEqualTo(fixture.pin.get()); + assertThat(fixture.source.isPreparedDenied()).isTrue(); + assertThat(fixture.source.preparedDenyEpoch()).isEqualTo(1); + var cache = fixture.cache(); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(SourcePreparedDenyException.class); + fixture.denied.set(false); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourcePreparedDenyException.class); + assertThat(fixture.source.isPreparedDenied()).isTrue(); + fixture.recoveryEligible.set(true); + cache.refresh(); + assertThat(fixture.source.isPreparedDenied()).isFalse(); + assertThat(cache.keyFor("known")).isEqualTo(fixture.key); + assertThat(fixture.source.sourceIdentity()).isEqualTo(fixture.pin.get()); + assertThat(fixture.source.preparedDenyEpoch()).isEqualTo(1); + fixture.denied.set(true); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourcePreparedDenyException.class); + assertThat(fixture.source.preparedDenyEpoch()).isEqualTo(2); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(SourcePreparedDenyException.class); + } + + @Test + void startupPreparedDenyNeverPermitsSourceReplacement() throws Exception { + for (boolean wrongNamespace : new boolean[] {false, true}) { + var fixture = new PublicationFixture(); + fixture.denied.set(true); + SourceIdentity original = fixture.source.sourceIdentity(); + fixture.pin.set( + wrongNamespace ? identity("other", "revision-1") : identity("test", "revision-2")); + assertInvalid(fixture.source); + fixture.pin.set(original); + fixture.denied.set(false); + fixture.recoveryEligible.set(true); + assertInvalid(fixture.source); + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceCustodyRejectedException.class); + } + } + + @Test + void separatelyObservedDenyBlocksWarmCachedKeysThroughoutOutageWithoutRenewingAge() + throws Exception { + var fixture = new PublicationFixture(); + var cache = fixture.cache(); + cache.refresh(); + fixture.advance(5); + fixture.denied.set(true); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourcePreparedDenyException.class); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(SourcePreparedDenyException.class); + fixture.unavailable.set(true); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourceUnavailableException.class); + assertThatThrownBy(cache::refresh).isInstanceOf(SourcePreparedDenyException.class); + fixture.advance(6); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(SourcePreparedDenyException.class); + fixture.unavailable.set(false); + fixture.denied.set(false); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourcePreparedDenyException.class); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(SourcePreparedDenyException.class); + fixture.recoveryEligible.set(true); + cache.refresh(); + assertThat(cache.keyFor("known")).isEqualTo(fixture.key); + fixture.advance(10); + fixture.unavailable.set(true); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(SourceUnavailableException.class); + } + + @Test + void recoveryRequiresBothEligibleAccountReadsAndCoherentMountedBytes() throws Exception { + var fixture = new PublicationFixture(); + fixture.source.load(); + fixture.denied.set(true); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourcePreparedDenyException.class); + fixture.denied.set(false); + fixture.afterAccountRead.set(() -> fixture.recoveryEligible.set(true)); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourcePreparedDenyException.class); + assertThat(fixture.source.isPreparedDenied()).isTrue(); + fixture.publishNext(); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourceUnavailableException.class); + assertThat(fixture.source.isPreparedDenied()).isTrue(); + fixture.converge(); + PublicJwksSnapshot recovered = fixture.source.load(); + assertThat(recovered.committedRecoveryEligible()).isTrue(); + assertThat(recovered.jwksBytes()).containsExactly(fixture.current.get()); + assertThat(fixture.source.isPreparedDenied()).isFalse(); + } + + @Test + void cachedKeyDenialDoesNotWaitForBlockedSamePinRecoveryLoad() throws Exception { + var fixture = new PublicationFixture(); + var cache = fixture.cache(); + cache.refresh(); + fixture.denied.set(true); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourcePreparedDenyException.class); + fixture.denied.set(false); + fixture.recoveryEligible.set(true); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + fixture.beforeAccountRead.set( + () -> { + entered.countDown(); + try { + if (!release.await(3, TimeUnit.SECONDS)) + throw new IllegalStateException("test timeout"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + }); + try (var executor = Executors.newFixedThreadPool(2)) { + var recovering = executor.submit(fixture.source::load); + try { + assertThat(entered.await(3, TimeUnit.SECONDS)).isTrue(); + var denied = + executor.submit( + () -> { + assertThat(fixture.source.isPreparedDenied()).isTrue(); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(SourcePreparedDenyException.class); + }); + denied.get(1, TimeUnit.SECONDS); + cache.invalidateKid("known"); + } finally { + release.countDown(); + } + assertThat(recovering.get(3, TimeUnit.SECONDS).committedRecoveryEligible()).isTrue(); + } + cache.refresh(); + assertThatThrownBy(() -> cache.keyFor("known")).isInstanceOf(UnknownKeyException.class); + } + + @Test + void secondAccountReadDenyLatchesBeforeReturningAnySnapshot() throws Exception { + var fixture = new PublicationFixture(); + fixture.source.load(); + fixture.afterAccountRead.set(() -> fixture.denied.set(true)); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourcePreparedDenyException.class); + assertThat(fixture.source.isPreparedDenied()).isTrue(); + fixture.denied.set(false); + fixture.recoveryEligible.set(true); + assertThat(fixture.source.load().sourceIdentity()).isEqualTo(fixture.pin.get()); + assertThat(fixture.source.isPreparedDenied()).isFalse(); + } + + @Test + void preparedDenyCannotHideReplacementIdentityOrLocalTampering() throws Exception { + for (boolean replaceIdentity : new boolean[] {false, true}) { + var fixture = new PublicationFixture(); + fixture.source.load(); + fixture.denied.set(true); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourcePreparedDenyException.class); + if (replaceIdentity) fixture.pin.set(identity("test", "revision-2")); + else when(fixture.projection.read()).thenThrow(new IllegalArgumentException("unsafe")); + assertInvalid(fixture.source); + fixture.denied.set(false); + fixture.recoveryEligible.set(true); + fixture.pin.set(identity("test", "revision-1")); + doAnswer(invocation -> fixture.mounted.get().clone()).when(fixture.projection).read(); + assertInvalid(fixture.source); + } + } + + @Test + void malformedSnapshotAfterDenyRemainsTerminalEvenWithoutRecoveryEligibility() throws Exception { + var fixture = new PublicationFixture(); + fixture.source.load(); + fixture.denied.set(true); + assertThatThrownBy(fixture.source::load).isInstanceOf(SourcePreparedDenyException.class); + fixture.denied.set(false); + fixture.current.set("{broken".getBytes(StandardCharsets.US_ASCII)); + fixture.converge(); + assertInvalid(fixture.source); + fixture.publishNext(); + fixture.converge(); + fixture.recoveryEligible.set(true); + assertInvalid(fixture.source); + } + + private static RSAPublicKey newPublicKey() { + try { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + return (RSAPublicKey) generator.generateKeyPair().getPublic(); + } catch (GeneralSecurityException failure) { + throw new ExceptionInInitializerError(failure); + } + } + + private static byte[] publicJwks(RSAPublicKey key, String... kids) { + String modulus = unsignedBase64(key.getModulus().toByteArray()); + String exponent = unsignedBase64(key.getPublicExponent().toByteArray()); + String[] entries = new String[kids.length]; + for (int index = 0; index < kids.length; index++) { + entries[index] = + "{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\"" + + kids[index] + + "\",\"n\":\"" + + modulus + + "\",\"e\":\"" + + exponent + + "\",\"key_ops\":[\"verify\"]}"; + } + return ("{\"keys\":[" + String.join(",", entries) + "]}").getBytes(StandardCharsets.US_ASCII); + } + + private static String unsignedBase64(byte[] value) { + byte[] unsigned = value[0] == 0 ? Arrays.copyOfRange(value, 1, value.length) : value; + return Base64.getUrlEncoder().withoutPadding().encodeToString(unsigned); + } + + private static final class PublicationFixture { + private static final RSAPublicKey SHARED_KEY = newPublicKey(); + private final RSAPublicKey key = SHARED_KEY; + private final AtomicReference beforeAccountRead = new AtomicReference<>(); + private final AtomicReference afterAccountRead = new AtomicReference<>(); + private final AtomicInteger accountReads = new AtomicInteger(); + private final AtomicReference denied = new AtomicReference<>(false); + private final AtomicReference recoveryEligible = new AtomicReference<>(false); + private final AtomicReference unavailable = new AtomicReference<>(false); + private final AtomicReference pin = + new AtomicReference<>(identity("test", "revision-1")); + private final AtomicReference current = new AtomicReference<>(publicJwks(key, "known")); + private final AtomicReference mounted = new AtomicReference<>(current.get()); + private final AtomicReference now = + new AtomicReference<>(Instant.parse("2026-11-10T00:00:00Z")); + private final ProtectedAccountPublicJwksProjection projection = + mock(ProtectedAccountPublicJwksProjection.class); + private final GameSessionAccountPublicJwksSource source; + + private PublicationFixture() throws Exception { + when(projection.read()).thenAnswer(invocation -> mounted.get().clone()); + source = + new GameSessionAccountPublicJwksSource( + () -> { + accountReads.incrementAndGet(); + Runnable before = beforeAccountRead.getAndSet(null); + if (before != null) before.run(); + if (unavailable.get()) throw new SourceUnavailableException(); + var snapshot = + new ReadResult( + pin.get(), + denied.get() ? new byte[0] : current.get(), + denied.get(), + !denied.get() && recoveryEligible.get()); + Runnable action = afterAccountRead.getAndSet(null); + if (action != null) action.run(); + return snapshot; + }, + projection, + "test"); + } + + private AccountPublicJwksCache cache() { + Clock clock = mock(Clock.class); + when(clock.instant()).thenAnswer(invocation -> now.get()); + return new AccountPublicJwksCache( + source, source.sourceIdentity(), clock, Duration.ofSeconds(10)); + } + + private void publishNext() { + current.set(publicJwks(key, "known", "next")); + } + + private void converge() { + mounted.set(current.get()); + } + + private void advance(long seconds) { + now.updateAndGet(value -> value.plusSeconds(seconds)); + } + } + + private static GameSessionAccountPublicJwksSource source( + TrustedPublicJwksSource account, ProtectedAccountPublicJwksProjection projection) { + return new GameSessionAccountPublicJwksSource( + () -> { + PublicJwksSnapshot snapshot = account.load(); + return snapshot == null + ? null + : new ReadResult( + snapshot.sourceIdentity(), + snapshot.jwksBytes(), + false, + snapshot.committedRecoveryEligible()); + }, + projection, + "test"); + } + + private static ProtectedAccountPublicJwksProjection projection(byte[] before, byte[] after) + throws Exception { + var projection = mock(ProtectedAccountPublicJwksProjection.class); + when(projection.read()) + .thenAnswer(invocation -> before.clone()) + .thenAnswer(invocation -> after.clone()); + return projection; + } + + private static PublicJwksSnapshot snapshot(SourceIdentity identity) { + return new PublicJwksSnapshot(identity, BYTES); + } + + private static SourceIdentity identity(String namespace, String revision) { + return new SourceIdentity( + "test", + "test-cluster", + "11111111-1111-4111-8111-111111111111", + namespace, + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + revision, + "https://kubernetes.example:6443", + "a".repeat(64)); + } + + private static void assertInvalid(GameSessionAccountPublicJwksSource source) { + assertThatThrownBy(source::load) + .isInstanceOf(SourceCustodyRejectedException.class) + .hasNoCause(); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java new file mode 100644 index 0000000000..52febd0892 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java @@ -0,0 +1,130 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.codec.ByteArrayCodec; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class LettuceInitialGameplayLoginConnectionProviderTest { + @Test + void disablesReconnectBeforeOpeningDedicatedBinaryConnectionAndOwnsClientLifecycle() { + RedisClient client = mock(RedisClient.class); + StatefulRedisConnection connection = connection(); + RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); + when(client.connect(ByteArrayCodec.INSTANCE)).thenReturn(connection); + try (var factory = mockStatic(RedisClient.class)) { + factory.when(() -> RedisClient.create(uri)).thenReturn(client); + var provider = new LettuceInitialGameplayLoginConnectionProvider(uri); + + assertThat(provider.openPinnedConnection()).isSameAs(connection); + + var options = ArgumentCaptor.forClass(ClientOptions.class); + var order = inOrder(client); + order.verify(client).setOptions(options.capture()); + order.verify(client).connect(ByteArrayCodec.INSTANCE); + assertThat(options.getValue().isAutoReconnect()).isFalse(); + + provider.close(); + provider.close(); + verify(client, times(1)).shutdown(); + assertThatThrownBy(provider::openPinnedConnection) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + verify(client, times(1)).connect(ByteArrayCodec.INSTANCE); + factory.verify(() -> RedisClient.create(uri), times(1)); + } + } + + @Test + void shutsDownClientIfReconnectConfigurationCannotBeApplied() { + RedisClient client = mock(RedisClient.class); + var failure = new IllegalStateException("options rejected"); + doThrow(failure).when(client).setOptions(any(ClientOptions.class)); + RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); + + try (var factory = mockStatic(RedisClient.class)) { + factory.when(() -> RedisClient.create(uri)).thenReturn(client); + assertThatThrownBy(() -> new LettuceInitialGameplayLoginConnectionProvider(uri)) + .isSameAs(failure); + verify(client).shutdown(); + } + } + + @Test + void preservesConfigurationFailureIfClientShutdownAlsoFails() { + RedisClient client = mock(RedisClient.class); + var failure = new IllegalStateException("options rejected"); + var shutdownFailure = new IllegalStateException("shutdown rejected"); + doThrow(failure).when(client).setOptions(any(ClientOptions.class)); + doThrow(shutdownFailure).when(client).shutdown(); + RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); + + try (var factory = mockStatic(RedisClient.class)) { + factory.when(() -> RedisClient.create(uri)).thenReturn(client); + assertThatThrownBy(() -> new LettuceInitialGameplayLoginConnectionProvider(uri)) + .isSameAs(failure) + .hasSuppressedException(shutdownFailure); + } + } + + @Test + void disposesConnectionThatFinishesAfterConcurrentProviderClose() throws Exception { + RedisClient client = mock(RedisClient.class); + StatefulRedisConnection connection = connection(); + RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); + var connectStarted = new CountDownLatch(1); + var finishConnect = new CountDownLatch(1); + when(client.connect(ByteArrayCodec.INSTANCE)) + .thenAnswer( + ignored -> { + connectStarted.countDown(); + if (!finishConnect.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("test connection was not released"); + } + return connection; + }); + var executor = Executors.newSingleThreadExecutor(); + try (var factory = mockStatic(RedisClient.class)) { + factory.when(() -> RedisClient.create(uri)).thenReturn(client); + var provider = new LettuceInitialGameplayLoginConnectionProvider(uri); + var opening = executor.submit(provider::openPinnedConnection); + + assertThat(connectStarted.await(5, TimeUnit.SECONDS)).isTrue(); + provider.close(); + finishConnect.countDown(); + + assertThatThrownBy(() -> opening.get(5, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class); + verify(connection).close(); + provider.close(); + verify(client, times(1)).shutdown(); + } finally { + finishConnect.countDown(); + executor.shutdownNow(); + } + } + + @SuppressWarnings("unchecked") + private static StatefulRedisConnection connection() { + return mock(StatefulRedisConnection.class); + } +}