diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 3980a1dadd..d4f3df054c 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -157,7 +157,9 @@ The handler returns `PERMISSION_DENIED` for a caller that is not the exact verif ### Operator Authorization References -`IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response. +StartSession response recovery preserves the raw `firemud/account-response-envelope/aad/v1` grammar and authenticates the canonical authority-evidence bytes directly; no digest replaces those bytes. The authority bundle is bounded at 128 KiB, the complete canonical binding and exact response plaintext at 144 KiB each, and the AES-GCM envelope by that plaintext maximum plus its bounded header and tag. Repository and PostgreSQL storage allow at most 160 KiB. Forward migration [V126.3](../../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql) replaces only the envelope-size guard and leaves retained ciphertext and the existing immutable/erasure rules intact. + +`IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, the immutable `authorityEvidenceBundle/v1`, and `authenticatedLoggingWorkloadIdentity`, which is copied from the verified same-namespace Logging/Admin TLS peer after successful issue or recovery; Logging checks the returned identity against the action target namespace before accepting the response. Account never exposes that evidence through an external route, logs, audit text, or client-visible response. `IssueAutomationOperatorAuthorizationReferenceRequest` contains no workload identity field: Account derives `workloadIdentity` from the authenticated mTLS transport peer and rejects any serialized or caller-supplied substitute. It contains `automation_policy_id`, `automation_policy_version`, target owner service, typed target scope, action family, action-family schema identifier/version, `controlPlaneRequestId`, and canonical `mutationDigest`, with no account, end-user token, or human identity. The target request is `non_moderation`-only: published schema pairs must select the branch with `action_category` absent, moderation schema pairs are rejected before issuance, and no concrete schema pairs are published while the route remains target-not-routable. For the supported tenant-scoped branch, Account binds the exact `tenant_generation`; global-role or `privileged_control` authority is rejected rather than inferred. The exact authenticated internal response has the same opaque reference, fingerprint, expiry, and immutable authority-evidence shape; its stored binding includes the authenticated workload and policy evidence plus the applicable generation predicate. `controlPlaneRequestId` and `mutationDigest/v1` cannot be reused for moderation; any future moderation automation contract must declare dedicated request identity, digest, and idempotency semantics with `controlPlaneRequestId` correlation-only. Both issuance requests are typed by the published action-family schema pair and contain the target owner, typed scope, action family, typed target, typed expected version, typed mutation, typed audit reason, the applicable mutation identity, correlation-only `controlPlaneRequestId`, canonical digest, the exact authenticated workload binding, the validated actor or automation-policy input, `reservationOwnerId`, and positive `reservationClaimFence`, including every schema-declared bound presence/absence value. `preAuthorizationReservationTuple` is limited to those request, target, mutation, identity, digest, and reservation-claim inputs; it explicitly excludes `issuanceKind`, `authorityTuple`, `membershipVersion`, and `issuanceFence`. For non-moderation families, the mutation identity is `controlPlaneRequestId`; for moderation, the tuple contains exactly `policyIntentRequestId` or `ownerEnforcementRequestId` according to the action-family contract, while `controlPlaneRequestId` remains correlation-only. The appeal-submission identity is not added to this operator tuple. Human actor identity is not a request assertion: Account derives it from the validated `control-ui` evidence forwarded by the exact Logging & Admin mTLS workload. Automation carries no user identity and is authorized only by the exact workload plus versioned automation policy. Account rejects malformed, unsupported, over-limit, missing, aliased, or digest-mismatched identity input before authorization issuance. Account derives `issuanceKind`, the complete applicable `authorityTuple`, independent applicable `membershipVersion`, and positive `issuanceFence` after authorization issuance as post-issuance enrichment. If a transport carries copies of those fields, they are non-authoritative echoes and are excluded from `preAuthorizationReservationTuple` and its digest; Account verifies the current reservation owner and claim fence before issuing. The human and automation requests therefore share the typed pre-authorization tuple while retaining distinct actor-versus-policy authority paths. @@ -177,7 +179,9 @@ Account-authenticated or reference-derived fields are not request authority asse Error precedence is canonical: (1) Account authenticates the exact immediate mTLS caller as an allowed owner/redeemer workload; an unauthenticated or disallowed workload fails at the authentication/transport boundary with the canonical non-OK status and bounded details selected by the shared classifier, before opaque-reference lookup or disclosure; (2) for an authenticated caller, missing or malformed applicable mutation identity, correlation-only `controlPlaneRequestId` when required by the transport, or `reservationClaimFence` is a request-validation failure at that boundary and uses canonical non-OK status with bounded details before durable lookup; (3) a malformed, undecodable, unsupported, or wrong-kind opaque reference is likewise a request-validation/shape failure using canonical non-OK status with bounded details, while a recognized reference whose stored redeemer/workload binding differs returns the typed `OPERATOR_AUTH_REFERENCE_CALLER_MISMATCH` before tuple or evidence disclosure; (4) only after the request is authenticated and validated, the reference is recognized, and the caller binding matches, the applicable mutation identity that identifies a durable record but carries any changed complete-tuple field returns the typed `IDEMPOTENCY_CONFLICT`; for moderation, this is the dedicated `policyIntentRequestId` or `ownerEnforcementRequestId`, never correlation-only `controlPlaneRequestId`; (5) only for an otherwise exact tuple with a supplied syntactically valid `reservationClaimFence` whose durable claim is stale, missing, lower, reused, or no longer held does Account redemption return the typed `FENCE_REJECTED`. Account redemption does not use `FENCE_REJECTED` for a domain-owner or gameplay fence. A domain owner may use the shared wire code only as phase-qualified `OWNER_EXECUTION/FENCE_REJECTED` after atomically persisting no-accept/no-commit proof, and the response must distinguish its owner-execution phase and proof evidence; absent or inconsistent proof leaves `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable and non-rearmable. Expiry returns the typed `OPERATOR_AUTH_REFERENCE_EXPIRED`, explicit revocation returns the typed `OPERATOR_AUTH_REFERENCE_REVOKED`, and changed current authority returns the typed `OPERATOR_AUTH_REFERENCE_AUTHORITY_STALE` when none of the higher-precedence conditions applies. These listed codes and precedence rules are Account-owned expected redemption outcomes only once an authenticated, validated request reaches Account's redemption decision boundary. Current handlers represent them with response-level `ErrorDetail`; the target response channel follows the [gRPC outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification), using a typed domain result when Account produces the declared redemption outcome and canonical non-OK status with bounded details when it cannot produce that result. This paragraph does not assign individual per-RPC mappings or exact gRPC status codes; the shared classifier owns that mapping. Transport uncertainty remains ambiguous: callers retry the same applicable mutation identity and tuple or use read-only recovery with the same identity, correlation, and claim fence, and never mint a replacement identity for the same mutation attempt. A pre-success same-tuple redemption retry may replay the durable redemption result; successful redemption consumes the reference, and the consumed reference cannot authorize a new owner attempt or owner rearm. Owner rearm after a terminal result requires a new explicit operator request, fresh Account authorization, and a new opaque reference. Raw references must not appear in logs, audit records, or mutation digests. Logging & Admin may retain durable intent and the Account-returned fingerprint, and may hold the opaque reference only as protected, bounded in-flight material while the current delivery or redemption attempt is active; it must not retain a second recovery envelope or competing authority record. The owner redeems the exact reference and does not persist it as an authority source. -These RPCs and schemas are accepted target state but are not present in the current Account proto or implementation. Logging & Admin remains the external operator ingress and durable intent/audit coordinator, Account remains the authorization authority and owner of original-reference retention, and the domain service remains the mutation owner. +The broader action-family RPC and schema set remains accepted target state and is not fully present in the current Account proto or implementation. StartSession Account ISSUE/RECOVER/REDEEM and the read-only original redeemed-operation projection are present at source level; source-level Logging & Admin durable handoff and Game Session claim/redemption/prepared-action slices are tracked in the [StartSession action-schema implementation status](../game-session-service/start-session-action-schema.md#implementation-status). Account's receiving adapter and owner service are composed only by the explicit `firemud.account.start-session-operator-authorization` configuration, disabled by default; enabling requires existing owner collaborators, explicit bounded timings, a workload namespace, an owner-supplied fingerprint-key source, and a distinct operator response-envelope mount. The Hosted Validation run `38113324723` at `f6d34031221a3337e7a958ac4b085554460668c9` is historical bounded 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); this does not establish overall CI success, deployed mTLS, full-service boot, production key custody, or activation. The production hosted-terms environment producer plus pinned trusted-provider/key-custody composition remain absent. The Game Design prepared selector/current-Account-projection consumer and full physical cross-service smoke remain unproved. Logging & Admin remains the external operator ingress and durable intent/audit coordinator, Account remains the authorization authority and owner of original-reference retention, and the domain service remains the mutation owner. + +For the redeemed StartSession projection, `ReadRedeemedOperationProjection` accepts the exact canonical pre-authorization tuple bytes, Account-issued authorization-reference fingerprint, original reservation owner and claim fence, and actual Game Session owner-attempt ID and fence. Account authenticates the exact same-namespace Game Design workload over mTLS before parsing or lookup. Its read-only result returns the original request ID, tuple, digest, fingerprint, reservation and owner-attempt bindings, recorded redeemer workload identity, reference expiry and redemption time, issuance operation and fence, bundle reference, and unchanged authority-evidence bundle; it returns neither the forwarded `control-ui` token nor the opaque authorization reference. The normative applicability and authority boundary are owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read). ## REST APIs diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index cfeb4f6035..ac85376d71 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -26,6 +26,8 @@ The configurable cleanup margin controls issued-token registry retention only. G The current runtime still uses the shared-HMAC compatibility profile for issuance and validation and has no asymmetric non-exportable signer delegation. Any Secret-backed asymmetric materialization is the explicit interim fallback/drift, not canonical target custody; the current preflight/manifests still treat signing paths and `jwt-signing-keys` mounts as shared workload configuration rather than enforcing Account as the sole private-material consumer, and the classpath fallback remains permitted when the configured JWKS file is absent. The runtime also retains the legacy creator-share percentage setting and provider-mutating code paths; they are unsupported implementation drift, not an accepted fee policy or product capability. These target-state requirements are not proof of current startup, custody, mount enforcement, or creator-commerce disablement; runtime, preflight, and manifest alignment is outside this documentation slice. +The StartSession operator-authorization receiver and owner service use the explicit `firemud.account.start-session-operator-authorization` composition, disabled by default (`enabled=false`). Enabling it requires the existing Account actor/issuance/hosted-terms and transaction owners, reservation-evidence client, an explicit `OwnerKeySource`, bounded reference/recovery/retention durations, the workload namespace, and a separate absolute operator response-envelope keyring mount. The operator keyring is not the generic Account response-envelope mount. Missing inputs prevent composition; this does not create an external operator ingress or enable gameplay launch/activation. The production hosted-terms environment producer and trusted-provider/key-custody inputs remain absent. + ## Service-Specific Variables Additional variables configure outbound email delivery and payment behavior: @@ -49,10 +51,12 @@ Additional variables configure outbound email delivery and payment behavior: | `FIREMUD_ACCOUNT_TOKENS_PLAYER_BOOTSTRAP_EXPIRATION_MS` | `player-bootstrap` JWT lifetime; target ceiling is `300000` ms (five minutes). Current runtime consumes this override, but target startup/preflight bound validation remains incomplete | `300000` | | `FIREMUD_ACCOUNT_TOKENS_CONNECT_SCOPE_EXPIRATION_MS` | Current Account discovery `connectScopeId` selector lifetime, surfaced as `connectScopeExpiresAt`; target scope proof remains short-lived and expiry-bound | `120000` | | `FIREMUD_ACCOUNT_TOKENS_CONNECT_TOKEN_EXPIRATION_MS` | `gameplay-connect` JWT lifetime; target ceiling is `30000` ms. Current runtime consumes this override, but target startup/preflight bound validation remains incomplete | `30000` | -| `FIREMUD_AUTH_SESSION_SAFETY_MARGIN_MS` | Target-state cleanup margin added to each token's remaining lifetime for issued-token registry TTL only; target startup validation requires `0..Long.MAX_VALUE - configured JWT lifetime` | `300000` | +| `FIREMUD_AUTH_SESSION_SAFETY_MARGIN_MS` | Target-state per-token cleanup margin added to each token's remaining lifetime for issued-token registry TTL only; target signed-64-bit arithmetic requires `0..Long.MAX_VALUE - configured JWT lifetime`, without replacing any stricter profile or storage bound | `300000` | Changing any of the three JWT lifetime variables—`FIREMUD_AUTH_JWT_EXPIRATION_MS`, `FIREMUD_ACCOUNT_TOKENS_PLAYER_BOOTSTRAP_EXPIRATION_MS`, or `FIREMUD_ACCOUNT_TOKENS_CONNECT_TOKEN_EXPIRATION_MS`—changes the `exp` claim only for newly issued JWTs; already issued JWTs retain their existing `exp`. `FIREMUD_ACCOUNT_TOKENS_SESSION_EXPIRATION_MS` is only the current default TTL for legacy session records whose writer omits an explicit lifetime; it does not change JWT `exp`, issued-token-registry retention, or gameplay continuity. The current control-ui, player-bootstrap, and connect-token writers pass their corresponding JWT lifetimes directly, which is implementation drift if target convergence requires one per-token retention rule. `FIREMUD_ACCOUNT_TOKENS_CONNECT_SCOPE_EXPIRATION_MS` separately controls the discovery selector's `connectScopeExpiresAt`; it is not a JWT lifetime, session-record TTL, registry-retention setting, or gameplay-continuity cap. The cleanup margin is applied when new registry records are admitted; it does not change the expiration of existing JWTs or the immutable anchor of an existing gameplay binding. A larger cleanup margin therefore cannot raise the independent gameplay-continuity cap. The separate Account overrides are current runtime controls with target ceilings and startup/preflight proof obligations recorded above; they do not establish target convergence by themselves. +The source-only Control-UI issuance preparation reads the configured margin through `firemud.auth.session-safety-margin-ms`; its nonnegative value is captured for new issuance rows only, and zero is valid. This path denies a negative margin, checked-add overflow, or a resulting absolute cleanup deadline above Redis/Lua's exact-integer ceiling of `9007199254740991` milliseconds; that actual-deadline bound is stricter than the global signed-64-bit margin arithmetic above and does not define a new universal margin policy. Retained rows without a persisted cleanup deadline remain untouched and are not backfilled or retried under a new deadline. + ## Proto Files The gRPC schemas for this service live in [`protos/account/v1`](../../../../protos/account/v1). Use `./gradlew generateProto` to regenerate Java stubs when the definitions change. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 1572f637ab..43554453b7 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -14,6 +14,14 @@ 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 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. + +V126.3 raises only the encrypted StartSession response-envelope size guard after locating its exact single-column constraint. The migration fails closed if the old size guard is absent or ambiguous and performs no retained-row rewrite. The PostgreSQL regression in [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest](../../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java) covers the 160 KiB storage edge and retention of a maximum-size V126.2 ciphertext across the forward migration; its exact-head physical execution 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). + +The StartSession owner preserves request IDs already accepted by the generic response-envelope identifier field. For other canonical NFC request IDs, its envelope binding uses lowercase hexadecimal SHA-256 of the exact UTF-8 request ID; the SHA-256 digest of the complete canonical tuple remains a separate binding field. This Account-local encoding leaves the generic envelope format and cryptography unchanged. + The passive signer repository can abandon only the exact current unprepared generation with its owner-recorded generation result and trust fence. An immutable abort receipt and desired-state CAS preserve both durable and published active fences, retain the original operation/result, and permit an exact retry after repository restart. A subsequent generation advances past the retained operation high-water mark; it does not reuse the aborted generation. Prepared promotion or changed evidence remains rejected. This storage operation is not wired to a cancellation coordinator or runtime activation path. Promotion storage retains the existing non-secret canonical readiness-proof preimage alongside its digest. The database hashes those exact bytes and binds the parsed proof to the locked generation, publication, inventory plan and complete verified probe receipts; altered, incomplete or mismatched evidence is rejected. PostgreSQL execution of these transition and tamper cases is required in the scoped CI proof; local compilation or skipped integration tests alone do not establish those database guarantees. diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index 8f8d1428e5..61805c576b 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -10,6 +10,8 @@ Account now has a bounded passive storage/source-evidence preparation for desire It also includes unregistered, caller-transaction-bound Control-UI creator-source composition and authority/signing-input preparation; this does not establish token issuance, receiver approval, stale-authority rejection, or playable admission. +The same source-only preparation now records one immutable cleanup deadline for each new Control-UI issuance, separate from the JWT's logical `exp`; the exact deadline must match owner readback, the registry record, and Redis physical expiry. Retained rows without that evidence remain unchanged and cannot establish current issuance or be retried as a new identity. This does not register or activate the issuer, rewrite retained Redis bytes/receipts, or claim bounded cleanup or late revocation. + Each registry-backed revocable `control-ui`, `player-bootstrap`, or receiver-specific private player-delegation JWT has exactly one Account-owned Coordination Redis record: `session:auth:token:`. The separate `gameplay-connect` profile is not registry-backed and uses its dedicated single-use replay contract. ## Canonical Authority Tuple diff --git a/design/project-management/implementation-tracking/capability-allocation.md b/design/project-management/implementation-tracking/capability-allocation.md index ec71db3fd4..fbde61f152 100644 --- a/design/project-management/implementation-tracking/capability-allocation.md +++ b/design/project-management/implementation-tracking/capability-allocation.md @@ -18,7 +18,7 @@ The ten permanent implementation trackers are retained as the complete-product p | --- | --- | --- | --- | | `AA-1.1` | [player-access-and-session.md](./player-access-and-session.md) | [shared-runtime-contracts-and-persistence.md](./shared-runtime-contracts-and-persistence.md) | Account Service owns global account and profile identity; shared security and persistence conventions are handoffs, not alternate account authority. | | `AA-1.2` | [player-access-and-session.md](./player-access-and-session.md) | [realm-routing-and-playable-state.md](./realm-routing-and-playable-state.md); [shared-runtime-contracts-and-persistence.md](./shared-runtime-contracts-and-persistence.md) | Account Service owns tenant membership, roles, and delegated grants; Realm Routing consumes grant decisions for admission and Shared Runtime carries authorization context. | -| `AA-1.3` | [player-access-and-session.md](./player-access-and-session.md) | [shared-runtime-contracts-and-persistence.md](./shared-runtime-contracts-and-persistence.md); [platform-operations-and-delivery.md](./platform-operations-and-delivery.md) | Account Service owns credential, recovery, security-policy, and data-rights decisions; Shared Runtime supplies trust propagation and Platform Operations supplies operator and deployment controls. | +| `AA-1.3` | [player-access-and-session.md](./player-access-and-session.md) | [shared-runtime-contracts-and-persistence.md](./shared-runtime-contracts-and-persistence.md); [platform-operations-and-delivery.md](./platform-operations-and-delivery.md) | Account Service owns credential, recovery, security-policy, and data-rights decisions; this row records static ownership only and makes no implementation or runtime-activation claim. Shared Runtime supplies trust propagation; operator lifecycle and deployment controls belong to Platform Operations. | | `AA-1.4` | [player-access-and-session.md](./player-access-and-session.md) | [shared-runtime-contracts-and-persistence.md](./shared-runtime-contracts-and-persistence.md) | Account Service owns subscriptions, purchases, donations, billing, and fees; Shared Runtime carries the local transaction and saga handoff without owning commerce. | | `AA-1.5` | [player-access-and-session.md](./player-access-and-session.md) | [realm-routing-and-playable-state.md](./realm-routing-and-playable-state.md); [game-authoring-publishing-and-activation.md](./game-authoring-publishing-and-activation.md) | Account Service is the canonical entitlement, quota, and hosting-eligibility authority; Realm Routing and Authoring/Activation consume those gates before admission or launch. | | `AA-2.1` | [player-access-and-session.md](./player-access-and-session.md) | [realm-routing-and-playable-state.md](./realm-routing-and-playable-state.md); [player-experience-commands-and-communication.md](./player-experience-commands-and-communication.md) | Player Access owns account-authenticated gameplay login, character selection, and session binding; Realm Routing supplies admissible targets and Player Experience owns the command/presentation handoff. | 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 ff0a3f7f97..dc129a3ad7 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -16,6 +16,14 @@ This preparation is owned by AA-1.3 in [Capability Status](#capability-status), The added `AccountDraftSourceCompositionService`, `AccountControlUiAuthority`, and `AccountControlUiSigningSpec` remain unregistered and transaction-bound source preparation. They do not issue a JWT, authorize receiver execution, or establish runtime currentness/readiness. +### Account operation and signer source preparation + +[V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql) adds one immutable cleanup deadline to newly prepared Control-UI owner rows, separate from the JWT `exp` horizon and bound to the same registry bytes and Redis readback receipt. The retained-row migration case in [AccountControlUiIssuancePostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java) confirms that a pre-deadline row keeps its original fields, retains a null deadline, and is denied current use and advancement after migration. Direct PostgreSQL proof that a newly recorded deadline cannot be changed is still missing. The preparation remains source-only under AA-1.3; bounded cleanup and late revocation remain incomplete, and token issuance is not activated. + +The direct expiry-erasure correction adds [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql) and an owner-only repository primitive, preserving compact authorization and redemption evidence. [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java) defines fresh-install, retained-V126, early-erasure, resurrection and exact-retry proof. The correction passed 35 focused unit cases without failures, errors or skips, jOOQ generation, integration-source compilation, Checkstyle and Spotless. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Account authorization-repository PostgreSQL suite passed 15/15 with zero skips, failures or errors, covering those migration and erasure cases; see the current AA-1.3 proof record in [Capability Status](#capability-status). This is bounded storage proof; automatic cleanup and runtime activation are not claimed. Its local storage consequence is owned by [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). + +The current Account cut adds V126 operator-authorization storage, default-inactive StartSession authorization sources, Control-UI issuance and Redis coordination, Account-owned JWKS and signer-materialization adapters, and readiness-probe sources. This preparation is tracked under AA-1.3, whose state remains `partial` / `drift-found`. StartSession composition is disabled by default. Materializer trust is disabled by default, and absent 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, signer-promotion coordinator, or consumer coordinator is registered. Production anchors include [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java), [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java), and [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql). Focused test anchors include [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java), [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java), [AccountControlUiOwnerWorkflowPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java), [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java), and [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql). At pinned head `22a6c39e3f1754acebf95477d6968c69edde66fd`, Validation run `38096949593` and Account artifact `11686863341` record the nine changed PostgreSQL/Redis integration suites executing 35 cases with zero failures, errors, or skips, plus 23 RestoredInventory unit cases. That proof remains historical and applies only to its recorded head and fixtures. Later hosted Validation run `38113324723` succeeded at head `f6d34031221a3337e7a958ac4b085554460668c9`; Account job `114394304424` and artifact `11693535744` record four owner-workflow PostgreSQL tests physically executed, including signer quarantine. This is bounded physical fixture proof, not deployment or runtime activation. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, Validation run `38117703529`, Account job `114405941820`, and artifact `11693819544` tested merge commit `9ca30839c8a46446f01d0a441e6e830fab8bca86` with ordered parents `4ab98ba1f0a2464349ed21ce59e7ef44ecd79e8c` and `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`; the Control-UI issuance PostgreSQL suite passed 5/5 and the StartSession authorization repository PostgreSQL suite passed 15/15 with zero skips, failures, or errors. This is bounded exact-head fixture proof, not deployment or runtime activation, and aggregate validation remains red on the unrelated Gateway fixture. The Account-owned [reservation-evidence client](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java) uses the existing Logging & Admin proto contract; completing the flow also depends on the out-of-cut Logging & Admin authorization coordinator/client and Game Session redemption composition. mTLS execution, the complete Logging & Admin/Game Session/World flow, player-facing JWT readiness, and activation remain unproved. V126/V126.1/V126.2 remain passive storage/source preparation; bounded cleanup and late revocation remain incomplete. Canonical JWT and signer behavior remains in [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md), with Account-local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). + ### Restricted original-claim evidence continuation preparation This inactive owner continuation may read or replay the exact immutable association pin and create at most one immutable descriptor evidence pin under that same association and original `PENDING` claim, attempt, and fence. Authenticated Account and Game Design reads occur outside SQL; owner and association state is locked and rechecked before descriptor pinning. Initial association creation also requires the exact original Account authorization reference to remain unexpired at the PostgreSQL write, independently of the owner-claim lease. Existing association replay and historical reads retain their reconciliation semantics; this preparation does not renew or reissue authorization or create a replacement claim. Its classes remain unregistered; added proto/schema support does not activate a runtime route or grant mutation authorization or player admission. Descriptor evidence does not complete canonical launch, initial World-backed admission, or historical owner reconciliation. The canonical boundary is [Game Session restricted original-claim evidence continuation](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md). @@ -84,7 +92,7 @@ These links add decision provenance only; they do not upgrade player-access or s | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.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); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. On fresh connect-token issuance/cache misses, issuance revalidates pointer/visibility/membership inputs, while cached-success replay returns before those fresh reads; current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance does not yet validate that grant. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [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); [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) | [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) | [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` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; 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. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [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) | [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) | [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` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; 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. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [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) | [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) | [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) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | 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 text `PLAY` checks membership and entitlement before persisted actor selection, but fresh connect-token issuance does not validate the applicable non-public realm grant; final Account admission and complete private/playtest grant and entitlement authority remain open under [Game Session admission](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). 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. | diff --git a/dev-tools/tests/workflow_version_authority_contract.py b/dev-tools/tests/workflow_version_authority_contract.py index 4b7711a730..5ca9a1b79a 100644 --- a/dev-tools/tests/workflow_version_authority_contract.py +++ b/dev-tools/tests/workflow_version_authority_contract.py @@ -2218,6 +2218,11 @@ def render_busybox_replacement(new_value, new_digest): or "${gradle.gradleVersion}" not in proto ): fail("protobuf diagnostic must derive both canonical versions") + if ( + "all().configureEach { task ->" not in proto + or "task.notCompatibleWithConfigurationCache(protobufConfigurationCacheIncompatibilityReason)" not in proto + ): + fail("all protobuf generation task variants must opt out of the configuration cache") for action in ("setup-gh",): data = (actions / action / "action.yml").read_text() if "sha256sum --check --status" not in data: diff --git a/protos/account/v1/jwt_signer_materialization.proto b/protos/account/v1/jwt_signer_materialization.proto new file mode 100644 index 0000000000..12d647a48a --- /dev/null +++ b/protos/account/v1/jwt_signer_materialization.proto @@ -0,0 +1,206 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// This exact authenticated peer performs only fixed-name Secret observation, pending-slot key +// generation, and an operation-bound private-slot transition after Account durably authorizes a +// PREPARED promotion. Account alone prepares/commits/promotes the lifecycle and publishes JWKS. +service AccountJwtSignerMaterializationService { + rpc EnrollBootstrap(EnrollBootstrapRequest) returns (EnrollBootstrapResponse); + rpc GetCurrentGenerationRequest(GetCurrentGenerationRequestRequest) + returns (GetCurrentGenerationRequestResponse); + rpc RecordSecretObservation(RecordSecretObservationRequest) + returns (GetCurrentGenerationRequestResponse); + rpc RecordGenerationResult(RecordGenerationResultRequest) + returns (RecordGenerationResultResponse); + rpc GetCurrentPromotionRequest(GetCurrentPromotionRequestRequest) + returns (GetCurrentPromotionRequestResponse); + rpc RecordPrivatePromotionResult(RecordPrivatePromotionResultRequest) + returns (RecordPrivatePromotionResultResponse); +} + +// Selector-free, authenticated bootstrap enrollment. The acknowledgment contains only pinned +// identities and the fixed public ConfigMap observation; it carries no private material or +// lifecycle selection authority. +message EnrollBootstrapRequest { + int32 schema_version = 1; +} + +message EnrollBootstrapResponse { + int32 schema_version = 1; + string environment_id = 2; + string cluster_id = 3; + string namespace = 4; + string expected_cluster_incarnation_uid = 5; + string expected_namespace_uid = 6; + string materializer_trust_binding_digest = 7; + string materializer_trust_config_revision = 8; + string api_binding_digest = 9; + string api_config_revision = 10; + string api_server_url = 11; + string api_tls_server_name = 12; + string api_serving_ca_sha256 = 13; + string api_expected_username = 14; + string private_secret_name = 15; + string public_config_map_name = 16; + string public_config_map_uid = 17; + string public_config_map_resource_version = 18; + string public_config_map_snapshot_digest = 19; +} + +message ActiveSigner { + string generation = 1; + string kid = 2; +} + +message GetCurrentGenerationRequestRequest { + int32 schema_version = 1; +} + +message GetCurrentGenerationRequestResponse { + enum Phase { + PHASE_UNSPECIFIED = 0; + OBSERVE_PRIVATE_SECRET = 1; + GENERATE_PENDING = 2; + GENERATION_RECORDED = 3; + } + + int32 schema_version = 1; + Phase phase = 2; + string operation_id = 3; + string operation_digest = 4; + string generation_request_digest = 5; + string desired_state_version = 6; + string environment_id = 7; + string cluster_id = 8; + string namespace = 9; + string expected_cluster_incarnation_uid = 10; + string expected_namespace_uid = 11; + string trust_binding_digest = 12; + string trust_config_revision = 13; + string private_secret_name = 14; + string target_generation = 15; + string target_kid = 16; + string target_algorithm = 17; + string operation_action = 18; + repeated string allowed_private_slots = 19; + ActiveSigner expected_active = 20; + string secret_uid = 21; + string expected_secret_resource_version = 22; + string generation_receipt_digest = 23; + string public_key_fingerprint = 24; + string public_jwk_json = 25; + string observed_secret_resource_version = 26; + ActiveSigner expected_published_active = 27; +} + +message RecordSecretObservationRequest { + int32 schema_version = 1; + string operation_id = 2; + string operation_digest = 3; + string secret_uid = 4; + string observed_resource_version = 5; +} + +message RecordGenerationResultRequest { + int32 schema_version = 1; + string operation_id = 2; + string generation_request_digest = 3; + string secret_uid = 4; + string expected_prior_resource_version = 5; + string observed_resource_version = 6; + // Exactly one bounded public RSA JWK; private RSA members and arbitrary resource names are not + // part of this schema. Account validates and canonicalizes the JWK and derives its fingerprint. + string public_jwk_json = 7; +} + +message RecordGenerationResultResponse { + int32 schema_version = 1; + string operation_id = 2; + string operation_digest = 3; + string generation_request_digest = 4; + string generation_receipt_digest = 5; + string desired_state_version = 6; + string environment_id = 7; + string cluster_id = 8; + string namespace = 9; + string expected_cluster_incarnation_uid = 10; + string expected_namespace_uid = 11; + string trust_binding_digest = 12; + string trust_config_revision = 13; + string private_secret_name = 14; + string secret_uid = 15; + string expected_prior_resource_version = 16; + string observed_resource_version = 17; + string target_generation = 18; + string target_kid = 19; + string target_algorithm = 20; + string public_key_fingerprint = 21; + string public_jwk_json = 22; +} + +// Account-authorized fixed-Secret slot transition. This peer response contains public identity +// fences only; it never selects or publishes the Account-owned JWKS ConfigMap and never commits +// the Account lifecycle. +message GetCurrentPromotionRequestRequest { + int32 schema_version = 1; +} + +message GetCurrentPromotionRequestResponse { + int32 schema_version = 1; + string promotion_operation_id = 2; + string promotion_request_digest = 3; + string generation_operation_id = 4; + string generation_operation_digest = 5; + string generation_receipt_digest = 6; + string environment_id = 7; + string cluster_id = 8; + string namespace = 9; + string expected_cluster_incarnation_uid = 10; + string expected_namespace_uid = 11; + string trust_binding_digest = 12; + string trust_config_revision = 13; + string private_secret_name = 14; + string target_generation = 15; + string target_kid = 16; + string target_algorithm = 17; + string target_public_key_fingerprint = 18; + string expected_secret_uid = 19; + string expected_secret_resource_version = 20; + string expected_previous_generation = 21; + string expected_previous_kid = 22; + string expected_previous_public_key_fingerprint = 23; + repeated string allowed_private_slots = 24; + string operation_action = 25; +} + +message PromotionPublicKeyIdentity { + string generation = 1; + string kid = 2; + string public_key_fingerprint = 3; +} + +message RecordPrivatePromotionResultRequest { + int32 schema_version = 1; + string promotion_operation_id = 2; + string promotion_request_digest = 3; + string generation_operation_id = 4; + string generation_operation_digest = 5; + string secret_uid = 6; + string expected_prior_resource_version = 7; + string observed_resource_version = 8; + PromotionPublicKeyIdentity current = 9; + PromotionPublicKeyIdentity previous = 10; + repeated string resulting_slots = 11; +} + +message RecordPrivatePromotionResultResponse { + int32 schema_version = 1; + string promotion_operation_id = 2; + string generation_operation_id = 3; + string observed_resource_version = 4; + string public_receipt_digest = 5; +} diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 8a4964119e..166c116f20 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -1,4 +1,18 @@ +import org.gradle.api.artifacts.component.ProjectComponentIdentifier +import org.gradle.api.DefaultTask +import org.gradle.api.file.ArchiveOperations +import org.gradle.api.file.ConfigurableFileCollection +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.file.FileSystemOperations +import org.gradle.api.tasks.InputFiles +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.PathSensitive +import org.gradle.api.tasks.PathSensitivity +import org.gradle.api.tasks.TaskAction +import org.gradle.api.tasks.testing.Test +import javax.inject.Inject + apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { @@ -8,15 +22,111 @@ plugins { id("net.firedevops.firemud.jooq-conventions") } +abstract class ExtractClassFilesFromArchives : DefaultTask() { + @get:InputFiles + @get:PathSensitive(PathSensitivity.RELATIVE) + abstract val archives: ConfigurableFileCollection + + @get:OutputDirectory + abstract val destinationDirectory: DirectoryProperty + + @get:Inject + abstract val archiveOperations: ArchiveOperations + + @get:Inject + abstract val fileSystemOperations: FileSystemOperations + + @TaskAction + fun extractClassFiles() { + fileSystemOperations.sync { + archives.forEach { archive -> + from(archiveOperations.zipTree(archive)) { + include("**/*.class") + } + } + into(destinationDirectory.get().asFile) + } + } +} + firemudJooq { packageName.set("net.firedevops.firemud.accountservice.jooq") } +configurations.named("testFixturesImplementation") { + extendsFrom(configurations.implementation.get()) +} + dependencies { + implementation(project(":common-redis-contracts")) implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) + + testFixturesImplementation(platform(libs.spring.boot.dependencies)) + testFixturesImplementation(project(":common-platform-core")) + testFixturesImplementation(project(":common-security")) + testFixturesImplementation(project(":common-data-runtime")) + testFixturesImplementation(libs.spring.boot.starter.test) + testFixturesImplementation(libs.spring.boot.starter.jdbc) + testFixturesImplementation(libs.spring.boot.starter.data.redis) + testFixturesImplementation(libs.spring.aop) + testFixturesImplementation(libs.mapstruct) + testFixturesImplementation(libs.jooq) + testFixturesImplementation(libs.flyway.core) + testFixturesImplementation("com.fasterxml.jackson.core:jackson-databind") + testFixturesImplementation("tools.jackson.core:jackson-databind") + testFixturesImplementation("com.google.protobuf:protobuf-java:${libs.versions.protobuf.get()}") + testFixturesImplementation("io.grpc:grpc-stub:${libs.versions.grpc.get()}") + + testImplementation(libs.grpc.inprocess) + testImplementation(project(":logging-admin-service")) testImplementation(testFixtures(project(":account-service"))) testCompileOnly(libs.spotbugs.annotations) add("integrationTestCompileOnly", libs.spotbugs.annotations) + integrationTestImplementation(testFixtures(project(":account-service"))) + integrationTestImplementation(testFixtures(project(":logging-admin-service"))) +} + +val loggingAdminProjectArtifacts = { configurationName: String -> + configurations + .getByName(configurationName) + .incoming + .artifactView { + componentFilter { componentId -> + componentId is ProjectComponentIdentifier + && componentId.projectPath == ":logging-admin-service" + } + } + .artifacts +} + +val loggingAdminTestArtifacts = loggingAdminProjectArtifacts("testRuntimeClasspath") +val loggingAdminIntegrationTestArtifacts = + loggingAdminProjectArtifacts("integrationTestRuntimeClasspath") + +val extractLoggingAdminTestClasses = + tasks.register("extractLoggingAdminTestClasses") { + dependsOn(loggingAdminTestArtifacts.artifactFiles) + archives.from(loggingAdminTestArtifacts.artifactFiles) + destinationDirectory.set(layout.buildDirectory.dir("account-test-classpath/logging-main")) + } + +val extractLoggingAdminIntegrationTestClasses = + tasks.register("extractLoggingAdminIntegrationTestClasses") { + dependsOn(loggingAdminIntegrationTestArtifacts.artifactFiles) + archives.from(loggingAdminIntegrationTestArtifacts.artifactFiles) + destinationDirectory.set( + layout.buildDirectory.dir("account-test-classpath/logging-integration") + ) + } + +tasks.named("test") { + val loggingArtifacts = loggingAdminTestArtifacts.artifactFiles + classpath = classpath.filter { it !in loggingArtifacts } + files(extractLoggingAdminTestClasses) +} + +tasks.named("integrationTest") { + val loggingArtifacts = loggingAdminIntegrationTestArtifacts.artifactFiles + classpath = classpath.filter { it !in loggingArtifacts } + files(extractLoggingAdminIntegrationTestClasses) } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java new file mode 100644 index 0000000000..82796d30ea --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java @@ -0,0 +1,211 @@ +package net.firedevops.firemud.accountservice.client; + +import com.google.protobuf.ByteString; +import jakarta.annotation.PostConstruct; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** + * Reads and validates Logging/Admin's current StartSession reservation claim snapshot. + * + *

The result is fresh read evidence only. It does not authorize a mutation and is not a + * commit-spanning compare-and-set proof. + */ +@Component +@ConditionalOnProperty( + prefix = "firemud.account.start-session-operator-authorization", + name = "enabled", + havingValue = "true", + matchIfMissing = false) +public final class StartSessionReservationEvidenceClient + extends AbstractReloadingBlockingGrpcClient< + StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private final Clock clock; + + @Autowired + public StartSessionReservationEvidenceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer) { + this(endpoints, tlsProperties, channelFactory, stubCustomizer, Clock.systemUTC()); + } + + StartSessionReservationEvidenceClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + Clock clock) { + super( + endpoints, + tlsProperties, + channelFactory, + stubCustomizer, + StartSessionReservationEvidenceClient.class); + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + @PostConstruct + void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getLoggingAdminService(); + } + + @Override + protected String defaultTarget() { + return "logging-admin-service:6565"; + } + + @Override + protected StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + buildStub(io.grpc.ManagedChannel channel) { + return applyStubCustomizer( + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .withCompression("gzip")); + } + + /** Reads the exact active claim for ISSUE or RECOVER and validates every returned binding. */ + public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + Purpose purpose) { + Objects.requireNonNull(tuple, "reservation tuple is required"); + requireNonNilUuid(reservationOwnerId, "reservationOwnerId"); + requireNonNilUuid(currentClaimOwnerId, "currentClaimOwnerId"); + Objects.requireNonNull(purpose, "read purpose is required"); + if (reservationClaimFence <= 0L || currentClaimFence <= 0L) { + throw new IllegalArgumentException("reservation claim fences must be positive"); + } + requirePurposeOwnership( + purpose, reservationOwnerId, reservationClaimFence, currentClaimOwnerId, currentClaimFence); + + byte[] tupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + ReadCurrentClaimEvidenceRequest request = + ReadCurrentClaimEvidenceRequest.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson(ByteString.copyFrom(tupleBytes)) + .setReservationOwnerId(reservationOwnerId.toString()) + .setReservationClaimFence(reservationClaimFence) + .setClaimOwnerId(currentClaimOwnerId.toString()) + .setClaimFence(currentClaimFence) + .setPurpose(toWirePurpose(purpose)) + .build(); + + var currentStub = stub(); + if (currentStub == null) { + throw new IllegalStateException("Logging/Admin reservation evidence client is unavailable"); + } + ReadCurrentClaimEvidenceResponse response = + currentStub + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .readCurrentClaimEvidence(request); + validateResponse( + response, + tuple, + tupleBytes, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + purpose); + return response; + } + + private void validateResponse( + ReadCurrentClaimEvidenceResponse response, + StartSessionPreAuthorizationReservationTuple tuple, + byte[] tupleBytes, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence, + Purpose purpose) { + long localNowEpochMillis = clock.millis(); + if (!response.getUnknownFields().asMap().isEmpty() + || !tuple.controlPlaneRequestId().equals(response.getControlPlaneRequestId()) + || !Arrays.equals(tupleBytes, response.getPreAuthorizationTupleJson().toByteArray()) + || !tuple.mutationDigest().equals(response.getMutationDigest()) + || !reservationOwnerId.toString().equals(response.getReservationOwnerId()) + || response.getReservationClaimFence() != reservationClaimFence + || !currentClaimOwnerId.toString().equals(response.getClaimOwnerId()) + || response.getClaimFence() != currentClaimFence + || response.getPurpose() != toWirePurpose(purpose) + || response.getObservedAtEpochMillis() <= 0L + || response.getObservedAtEpochMillis() > localNowEpochMillis + || response.getClaimExpiresAtEpochMillis() <= response.getObservedAtEpochMillis() + || response.getClaimExpiresAtEpochMillis() <= localNowEpochMillis) { + throw new IllegalStateException( + "Logging/Admin returned stale or mismatched StartSession reservation evidence"); + } + } + + private static void requirePurposeOwnership( + Purpose purpose, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + if (purpose == Purpose.ISSUE + && (!reservationOwnerId.equals(currentClaimOwnerId) + || reservationClaimFence != currentClaimFence)) { + throw new IllegalArgumentException("ISSUE requires the original reservation owner and fence"); + } + if (purpose == Purpose.RECOVER + && (reservationOwnerId.equals(currentClaimOwnerId) + || currentClaimFence <= reservationClaimFence)) { + throw new IllegalArgumentException("RECOVER requires a fresh recovery owner and fence"); + } + } + + private static void requireNonNilUuid(UUID value, String fieldName) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID"); + } + } + + private static StartSessionReservationEvidencePurpose toWirePurpose(Purpose purpose) { + return switch (purpose) { + case ISSUE -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE; + case RECOVER -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER; + }; + } + + public enum Purpose { + ISSUE, + RECOVER + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java new file mode 100644 index 0000000000..71ba3c2455 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java @@ -0,0 +1,404 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +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.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** + * Reads the independently protected trust binding for Account's narrow JWT materializer RPCs. The + * file must be root-owned and non-writable by the Account/materializer workload. It is read again + * for every RPC so pin rotation or trust withdrawal takes effect without process restart. + */ +@Component +public final class AccountJwtSignerMaterializerTrustBinding { + public static final int MAX_FILE_BYTES = 8 * 1024; + private static final String VERSION = "account-jwt-signer-materializer-binding/v1"; + private static final Set REQUIRED_FIELDS = + Set.of( + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedPeerUri", + "peerSpkiSha256Pins", + "bindingDigest"); + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final boolean enabled; + private final String protectedBindingPath; + + public AccountJwtSignerMaterializerTrustBinding( + @Value("${firemud.account.jwt-signer.materialization.enabled:false}") boolean enabled, + @Value("${firemud.account.jwt-signer.materialization.protected-binding-path:}") + String protectedBindingPath) { + this.enabled = enabled; + this.protectedBindingPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + } + + /** Missing, disabled, malformed, or mutable trust configuration always means no access. */ + public Optional current() { + if (!enabled || protectedBindingPath.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(readProtectedFile(Path.of(protectedBindingPath))); + } catch (Exception ex) { + // Never expose config contents, file paths, or certificate details through RPC errors. + return Optional.empty(); + } + } + + /** Testable parser boundary; production calls still require the protected-file checks above. */ + static AccountJwtSignerMaterializerTrustBinding.Binding parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_FILE_BYTES) { + throw new IllegalArgumentException("JWT materializer trust binding is unavailable"); + } + String text = decodeUtf8(bytes); + String[] lines = text.split("\n", -1); + int count = lines.length; + if (count > 0 && lines[count - 1].isEmpty()) { + count--; + } + Map fields = new LinkedHashMap<>(); + for (int index = 0; index < count; index++) { + String line = lines[index]; + int separator = line.indexOf('='); + if (line.isEmpty() || separator <= 0 || separator == line.length() - 1) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + String key = line.substring(0, separator); + String value = line.substring(separator + 1); + if (!REQUIRED_FIELDS.contains(key) || fields.putIfAbsent(key, value) != null) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + } + if (!fields.keySet().equals(REQUIRED_FIELDS) || !"true".equals(fields.get("enabled"))) { + throw new IllegalArgumentException("JWT materializer trust binding is disabled"); + } + + String environmentId = fields.get("environmentId"); + String clusterId = fields.get("clusterId"); + String namespace = fields.get("namespace"); + String clusterUid = canonicalUuid(fields.get("expectedClusterIncarnationUid")); + String namespaceUid = canonicalUuid(fields.get("expectedNamespaceUid")); + String revision = fields.get("configRevision"); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(revision).matches()) { + throw new IllegalArgumentException("JWT materializer trust binding is malformed"); + } + String expectedUri = fields.get("expectedPeerUri"); + if (!validExpectedPeerUri(namespace, expectedUri)) { + throw new IllegalArgumentException("JWT materializer workload identity is not canonical"); + } + List pins = parsePins(fields.get("peerSpkiSha256Pins")); + String digest = + computeBindingDigest( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins); + if (!digest.equals(fields.get("bindingDigest"))) { + throw new IllegalArgumentException("JWT materializer trust binding digest is invalid"); + } + return new AccountJwtSignerMaterializerTrustBinding.Binding( + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + revision, + digest); + } + + private static Binding readProtectedFile(Path path) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute)) { + throw new IOException("Protected Account JWT materializer binding is not a regular file"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile()) { + throw new IOException("Protected Account JWT materializer binding is not a regular file"); + } + verifyRootOwnedAndNonWritable(absolute); + if (before.size() <= 0 || before.size() > MAX_FILE_BYTES) { + throw new IOException("Protected Account JWT materializer binding size is invalid"); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + int count = channel.read(buffer); + if (count < 0) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime())) { + throw new IOException("Protected Account JWT materializer binding changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + return parseProtectedBytes(bytes); + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected Account JWT materializer binding is unavailable"); + } + Path realParent = parent.toRealPath(); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object directoryOwner = Files.getAttribute(realParent, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + Set directoryMode = Files.getPosixFilePermissions(realParent); + if (!(fileOwner instanceof Number fileUid) + || fileUid.longValue() != 0L + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writable(fileMode) + || writable(directoryMode)) { + throw new IOException("Protected Account JWT materializer binding ownership is invalid"); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static String decodeUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw new IllegalArgumentException("JWT materializer trust binding is not UTF-8", ex); + } + } + + private static List parsePins(String value) { + String[] parts = value.split(",", -1); + if (parts.length == 0 || parts.length > 8) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + List pins = new ArrayList<>(parts.length); + for (String pin : parts) { + if (!SHA256.matcher(pin).matches() || pins.contains(pin)) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + pins.add(pin); + } + return List.copyOf(pins); + } + + private static boolean validExpectedPeerUri(String namespace, String uri) { + String prefix = "spiffe://firemud/ns/" + namespace + "/sa/"; + return uri != null + && uri.startsWith(prefix) + && ENVIRONMENT.matcher(uri.substring(prefix.length())).matches(); + } + + private static String canonicalUuid(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || new UUID(0L, 0L).equals(uuid)) { + throw new IllegalArgumentException("JWT materializer trust UID is malformed"); + } + return uuid.toString(); + } + + public static String computeBindingDigest( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List pins) { + try { + Map binding = new LinkedHashMap<>(); + binding.put("digestVersion", VERSION); + binding.put("configRevision", configRevision); + binding.put("environmentId", environmentId); + binding.put("clusterId", clusterId); + binding.put("namespace", namespace); + binding.put("expectedClusterIncarnationUid", expectedClusterIncarnationUid); + binding.put("expectedNamespaceUid", expectedNamespaceUid); + binding.put("expectedPeerUri", expectedPeerUri); + binding.put("peerSpkiSha256Pins", List.copyOf(pins)); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(binding)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (Exception ex) { + throw new IllegalStateException("JWT materializer trust binding digest is unavailable", ex); + } + } + + public static boolean matchesPeer( + java.security.cert.Certificate[] peerCertificates, Binding binding) { + if (peerCertificates == null || peerCertificates.length == 0 || binding == null) { + return false; + } + if (!(peerCertificates[0] instanceof X509Certificate certificate)) { + return false; + } + try { + certificate.checkValidity(); + Collection> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); + if (subjectAlternativeNames == null) { + return false; + } + String foundUri = null; + int uriCount = 0; + for (List entry : subjectAlternativeNames) { + if (entry.size() < 2 || !(entry.get(0) instanceof Integer type) || type != 6) { + continue; + } + uriCount++; + if (!(entry.get(1) instanceof String uri)) { + return false; + } + foundUri = uri; + } + if (uriCount != 1 || !binding.expectedPeerUri().equals(foundUri)) { + return false; + } + byte[] spkiDigest = + MessageDigest.getInstance("SHA-256").digest(certificate.getPublicKey().getEncoded()); + byte[] configuredPin = HexFormat.of().parseHex(binding.peerSpkiSha256Pins().get(0)); + boolean matched = MessageDigest.isEqual(spkiDigest, configuredPin); + for (int index = 1; index < binding.peerSpkiSha256Pins().size(); index++) { + byte[] pin = HexFormat.of().parseHex(binding.peerSpkiSha256Pins().get(index)); + matched |= MessageDigest.isEqual(spkiDigest, pin); + } + return matched; + } catch (CertificateException | NoSuchAlgorithmException | RuntimeException ex) { + return false; + } + } + + public record Binding( + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List peerSpkiSha256Pins, + String configRevision, + String bindingDigest) { + public Binding { + Objects.requireNonNull(environmentId, "Environment identity is required"); + Objects.requireNonNull(clusterId, "Cluster identity is required"); + Objects.requireNonNull(namespace, "Namespace identity is required"); + canonicalUuid(expectedClusterIncarnationUid); + canonicalUuid(expectedNamespaceUid); + Objects.requireNonNull(expectedPeerUri, "Materializer URI identity is required"); + peerSpkiSha256Pins = List.copyOf(peerSpkiSha256Pins); + if (peerSpkiSha256Pins.isEmpty() || peerSpkiSha256Pins.size() > 8) { + throw new IllegalArgumentException("JWT materializer certificate pins are unavailable"); + } + for (String pin : peerSpkiSha256Pins) { + if (!SHA256.matcher(pin).matches()) { + throw new IllegalArgumentException("JWT materializer certificate pins are malformed"); + } + } + Objects.requireNonNull(configRevision, "Materializer trust revision is required"); + if (!REVISION.matcher(configRevision).matches() || !SHA256.matcher(bindingDigest).matches()) { + throw new IllegalArgumentException("JWT materializer trust binding digest is malformed"); + } + if (peerSpkiSha256Pins.stream().distinct().count() != peerSpkiSha256Pins.size()) { + throw new IllegalArgumentException("JWT materializer certificate pins are duplicated"); + } + AccountJwtSignerDesiredStateRepository.Binding stateBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + environmentId, + clusterId, + namespace, + AccountJwtSignerDesiredStateRepository.CustodyMode + .INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + if (!validExpectedPeerUri(stateBinding.namespace(), expectedPeerUri)) { + throw new IllegalArgumentException("JWT materializer workload identity is not canonical"); + } + String expectedDigest = + computeBindingDigest( + configRevision, + environmentId, + clusterId, + namespace, + expectedClusterIncarnationUid, + expectedNamespaceUid, + expectedPeerUri, + peerSpkiSha256Pins); + if (!expectedDigest.equals(bindingDigest)) { + throw new IllegalArgumentException("JWT materializer trust binding digest is invalid"); + } + } + + public AccountJwtSignerDesiredStateRepository.Binding accountBinding() { + return new AccountJwtSignerDesiredStateRepository.Binding( + environmentId, + clusterId, + namespace, + AccountJwtSignerDesiredStateRepository.CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java new file mode 100644 index 0000000000..8b6a275528 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java @@ -0,0 +1,132 @@ +package net.firedevops.firemud.accountservice.config; + +import java.nio.file.Path; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +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; + +/** + * Explicit, disabled-by-default composition for Account's human StartSession authorization owner. + * + *

Enabling this composition requires real Account owner sources, trusted key custody, and + * configured bounded timing. This configuration supplies no actor, hosted-terms, fingerprint-key, + * or response-encryption defaults. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = AccountStartSessionOperatorAuthorizationConfiguration.PROPERTY_PREFIX, + name = "enabled", + havingValue = "true", + matchIfMissing = false) +public class AccountStartSessionOperatorAuthorizationConfiguration { + static final String PROPERTY_PREFIX = "firemud.account.start-session-operator-authorization"; + static final String OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN = + "startSessionOperatorResponseEnvelopeCryptography"; + + /** Creates Account's explicit active/retained HMAC calculator from an owner-supplied source. */ + @Bean + public AccountOperatorAuthorizationFingerprintKeyring + accountStartSessionOperatorFingerprintKeyring( + OwnerKeySource ownerKeySource, + @Value( + "${firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention}") + Duration requiredPostExpiryRetention) { + return new AccountOperatorAuthorizationFingerprintKeyring( + ownerKeySource, Clock.systemUTC(), requiredPostExpiryRetention); + } + + /** + * Creates a separate response-envelope cryptography instance from the operator-only mount. + * + *

The generic Account envelope bean and control-ui cryptography are deliberately not injected + * or reused. Deployment remains responsible for supplying a distinct protected key mount. + */ + @Bean(name = OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN) + @Qualifier(OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN) + public AccountResponseEnvelopeCryptography + accountStartSessionOperatorResponseEnvelopeCryptography( + @Value( + "${firemud.account.start-session-operator-authorization.response-envelope.keyring-path}") + String operatorKeyringPath, + @Value("${firemud.account.response-envelope.keyring-path:}") + String generalAccountKeyringPath) { + Path operatorMount = requiredAbsoluteMount(operatorKeyringPath, "operator response keyring"); + if (generalAccountKeyringPath != null && !generalAccountKeyringPath.isBlank()) { + Path generalMount = Path.of(generalAccountKeyringPath).toAbsolutePath().normalize(); + if (operatorMount.equals(generalMount)) { + throw new IllegalArgumentException( + "Operator response keyring must use its separately supplied mount"); + } + } + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(operatorMount.toString())); + } + + /** Wires only genuine owner collaborators and a same-namespace workload policy. */ + @Bean + public AccountStartSessionOperatorAuthorizationService + accountStartSessionOperatorAuthorizationService( + AccountControlUiActorService actors, + AccountControlUiIssuanceRepository issuanceOperations, + StartSessionReservationEvidenceClient reservationEvidence, + AccountStartSessionOperatorAuthorizationRepository repository, + AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, + @Qualifier(OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN) + AccountResponseEnvelopeCryptography operatorResponseCryptography, + AccountHostedTermsService hostedTerms, + PlatformTransactionManager transactions, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace, + @Value("${firemud.account.start-session-operator-authorization.reference-lifetime}") + Duration referenceLifetime, + @Value("${firemud.account.start-session-operator-authorization.response-recovery-window}") + Duration responseRecoveryWindow) { + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException( + "A valid configured workload namespace is required for operator authorization"); + } + String peerPrefix = "spiffe://firemud/ns/" + workloadNamespace + "/sa/"; + return new AccountStartSessionOperatorAuthorizationService( + actors, + issuanceOperations, + reservationEvidence, + repository, + fingerprintKeys, + operatorResponseCryptography, + hostedTerms, + transactions, + Clock.systemUTC(), + new SecureRandom(), + peerPrefix + "logging-admin-service", + peerPrefix + "game-session-service", + referenceLifetime, + responseRecoveryWindow); + } + + private static Path requiredAbsoluteMount(String configuredPath, String field) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException("Explicit " + field + " mount is required"); + } + Path path = Path.of(configuredPath); + if (!path.isAbsolute()) { + throw new IllegalArgumentException("Absolute " + field + " mount is required"); + } + return path.normalize(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java new file mode 100644 index 0000000000..5ae811664f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java @@ -0,0 +1,295 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Read-only exact lookup of immutable Account control-ui issuance evidence. */ +@Repository +public class AccountControlUiCommittedIssuanceRepository { + private static final String TABLE = "account_control_ui_issuance_operations"; + private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}"); + private static final int MAX_CLAIMS = 16 * 1024; + private static final int MAX_SOURCE = 131072; + private static final int MAX_BUNDLE = 131072; + private static final int MAX_SIGNER_RECEIPT = 65536; + private static final long MAX_REDIS_SAFE_INTEGER = 9_007_199_254_740_991L; + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"}, + justification = + "Spring injects the shared transaction-aware DSLContext; this proxyable repository only validates that dependency and acquires no resources in its constructor.") + public AccountControlUiCommittedIssuanceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Reads only the exact still-COMMITTED issuance row in the caller's Account transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCommitted(String tokenHash) { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Committed Account issuance read requires an Account transaction"); + } + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw denied(); + } + Record row = + dsl.fetchOne( + "SELECT request_id, operation_id, token_jti, account_uuid, tenant_uuid, " + + "caller_workload, caller_context_id, request_digest, claims_payload, " + + "source_payload, bundle_payload, signer_receipt, issued_at_epoch_second, " + + "expires_at_epoch_second, recovery_expires_at, status, token_hash, " + + "registry_cleanup_deadline_epoch_millis, pending_registry, active_registry, pending_receipt, committed_at, " + + "recovery_failed_at FROM " + + TABLE + + " WHERE token_hash = ? FOR SHARE", + tokenHash); + if (row == null) { + return Optional.empty(); + } + try { + CommittedIssuance evidence = new CommittedIssuance(row); + if (!"COMMITTED".equals(evidence.status()) + || !tokenHash.equals(evidence.tokenHash()) + || evidence.recoveryFailedAt() != null + || evidence.committedAt() == null + || evidence.pendingReceipt().length == 0) { + throw denied(); + } + return Optional.of(evidence); + } catch (RuntimeException malformed) { + throw denied(); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException( + "Exact committed Account control-ui issuance evidence unavailable"); + } + + private static byte[] bytes(Record row, String field, int maximum) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0 || value.length > maximum) { + throw denied(); + } + return value.clone(); + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || isNil(value)) { + throw denied(); + } + return value; + } + + private static boolean isNil(UUID value) { + return value.getMostSignificantBits() == 0L && value.getLeastSignificantBits() == 0L; + } + + private static long positive(Record row, String field) { + Long value = row.get(field, Long.class); + if (value == null || value <= 0L) { + throw denied(); + } + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isBlank()) { + throw denied(); + } + return value; + } + + private static String tokenHash(Record row) { + String value = row.get("token_hash", String.class); + if (value == null || !TOKEN_HASH.matcher(value).matches()) { + throw denied(); + } + return value; + } + + /** Defensive immutable owner row; it does not contain the compact JWT or response envelope. */ + public static final class CommittedIssuance { + private final UUID requestId; + private final UUID operationId; + private final UUID tokenJti; + private final UUID accountId; + private final UUID tenantId; + private final String callerWorkload; + private final UUID callerContextId; + private final String requestDigest; + private final byte[] claims; + private final byte[] source; + private final byte[] bundle; + private final byte[] signerReceipt; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final long registryCleanupDeadlineEpochMillis; + private final String status; + private final String tokenHash; + private final byte[] pendingRegistry; + private final byte[] activeRegistry; + private final byte[] pendingReceipt; + private final java.time.OffsetDateTime committedAt; + private final java.time.OffsetDateTime recoveryFailedAt; + + private CommittedIssuance(Record row) { + requestId = uuid(row, "request_id"); + operationId = uuid(row, "operation_id"); + tokenJti = uuid(row, "token_jti"); + accountId = uuid(row, "account_uuid"); + tenantId = uuid(row, "tenant_uuid"); + callerWorkload = text(row, "caller_workload"); + callerContextId = uuid(row, "caller_context_id"); + requestDigest = digest(row, "request_digest"); + claims = bytes(row, "claims_payload", MAX_CLAIMS); + source = bytes(row, "source_payload", MAX_SOURCE); + bundle = bytes(row, "bundle_payload", MAX_BUNDLE); + signerReceipt = bytes(row, "signer_receipt", MAX_SIGNER_RECEIPT); + issuedAtEpochSecond = positive(row, "issued_at_epoch_second"); + expiresAtEpochSecond = positive(row, "expires_at_epoch_second"); + if (expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond > 300L) { + throw denied(); + } + long expiryMillis; + try { + expiryMillis = Math.multiplyExact(expiresAtEpochSecond, 1000L); + } catch (ArithmeticException malformed) { + throw denied(); + } + Long cleanupDeadline = row.get("registry_cleanup_deadline_epoch_millis", Long.class); + if (cleanupDeadline == null + || cleanupDeadline < expiryMillis + || cleanupDeadline > MAX_REDIS_SAFE_INTEGER) { + throw denied(); + } + registryCleanupDeadlineEpochMillis = cleanupDeadline; + status = text(row, "status"); + tokenHash = AccountControlUiCommittedIssuanceRepository.tokenHash(row); + pendingRegistry = bytes(row, "pending_registry", 32768); + activeRegistry = bytes(row, "active_registry", 32768); + pendingReceipt = bytes(row, "pending_receipt", 8192); + committedAt = row.get("committed_at", java.time.OffsetDateTime.class); + recoveryFailedAt = row.get("recovery_failed_at", java.time.OffsetDateTime.class); + } + + private static String digest(Record row, String field) { + String value = text(row, field); + if (!Pattern.matches("[0-9a-f]{64}", value)) { + throw denied(); + } + return value; + } + + public UUID requestId() { + return requestId; + } + + public UUID operationId() { + return operationId; + } + + public UUID tokenJti() { + return tokenJti; + } + + public UUID accountId() { + return accountId; + } + + public UUID tenantId() { + return tenantId; + } + + public String callerWorkload() { + return callerWorkload; + } + + public UUID callerContextId() { + return callerContextId; + } + + public String requestDigest() { + return requestDigest; + } + + public byte[] claims() { + return claims.clone(); + } + + public byte[] source() { + return source.clone(); + } + + public byte[] bundle() { + return bundle.clone(); + } + + public byte[] signerReceipt() { + return signerReceipt.clone(); + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public String status() { + return status; + } + + public String tokenHash() { + return tokenHash; + } + + public byte[] pendingRegistry() { + return pendingRegistry.clone(); + } + + public byte[] activeRegistry() { + return activeRegistry.clone(); + } + + public byte[] pendingReceipt() { + return pendingReceipt.clone(); + } + + public java.time.OffsetDateTime committedAt() { + return committedAt; + } + + public java.time.OffsetDateTime recoveryFailedAt() { + return recoveryFailedAt; + } + + public long expiryMillis() { + return registryCleanupDeadlineEpochMillis; + } + + public long registryCleanupDeadlineEpochMillis() { + return registryCleanupDeadlineEpochMillis; + } + + @Override + public String toString() { + return "AccountControlUiCommittedIssuanceRepository.CommittedIssuance[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java new file mode 100644 index 0000000000..674a21f5a8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java @@ -0,0 +1,895 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Permanent Account-owned issuance and one-time redemption storage for StartSession operator + * authorization. + * + *

Callers must authenticate the immediate workload peer and establish current Account authority + * before invoking this repository. This storage is not authority evidence and a returned record is + * not a source-snapshot guarantee. Callers enforce the immutable response-envelope expiry before + * recovering or decrypting that envelope. All methods require the caller's ambient Account + * transaction; this repository performs no network calls and creates no credentials, references, or + * keys. + */ +@Repository +public class AccountStartSessionOperatorAuthorizationRepository { + private static final String TABLE = "account_start_session_operator_authorizations"; + private static final String SELECT_COLUMNS = + "control_plane_request_id, pre_authorization_tuple, mutation_digest, " + + "issuance_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "issuance_operation_id, issuance_fence, bundle_version, bundle_source_version, " + + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, " + + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, " + + "reference_expires_at, response_envelope_expires_at, response_envelope_erased_at, status, " + + "redemption_redeemer_workload_uri, redemption_owner_attempt_id, " + + "redemption_owner_fence, redeemed_at, redemption_reference_fingerprint, " + + "redemption_authority_evidence_bundle"; + private static final int MAX_TUPLE_BYTES = 8 * 1024; + private static final int MAX_AUTHORITY_BUNDLE_BYTES = 128 * 1024; + private static final int MAX_ENCRYPTED_ENVELOPE_BYTES = 160 * 1024; + private static final Duration MAX_REFERENCE_LIFETIME = Duration.ofMinutes(5); + private static final Duration MAX_RESPONSE_RECOVERY_WINDOW = Duration.ofMinutes(1); + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern FINGERPRINT = + Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"); + private static final Pattern SPIFFE_WORKLOAD_URI = + Pattern.compile( + "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/" + + "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Constructor validates the injected DSL collaborator without acquiring resources or exposing a partially initialized repository.") + public AccountStartSessionOperatorAuthorizationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Inserts the one permanent issuance row or returns its exact original output on duplicate. + * + *

The stable canonical control-plane request ID is the unique key. Duplicate comparison covers + * every original pre-authorization binding; candidate output fields are deliberately not compared + * or substituted when a row already exists. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CreateOrReadResult createOrReadExact(IssuanceCandidate candidate) { + requireOwnerTransaction(); + validateCandidate(candidate); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (control_plane_request_id, pre_authorization_tuple, mutation_digest, " + + "issuance_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "issuance_operation_id, issuance_fence, bundle_version, bundle_source_version, " + + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, " + + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, " + + "reference_expires_at, response_envelope_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ), " + + "CAST(? AS TIMESTAMPTZ), 'ISSUED') " + + "ON CONFLICT (control_plane_request_id) DO NOTHING", + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + candidate.issuanceWorkloadUri(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + candidate.issuanceOperationId(), + candidate.issuanceFence(), + candidate.bundleReference().bundleVersion(), + candidate.bundleReference().sourceVersion(), + candidate.bundleReference().sourceFence(), + candidate.bundleReference().linearization(), + candidate.authorityEvidenceBundle(), + candidate.authorizationReferenceFingerprint(), + candidate.encryptedResponseEnvelope(), + utc(candidate.issuedAt()), + utc(candidate.referenceExpiresAt()), + utc(candidate.responseEnvelopeExpiresAt())); + + Record row = lockByRequestId(candidate.controlPlaneRequestId()); + IssuanceRecord original = toIssuanceRecord(row); + requireSameOriginalBinding(candidate, original); + return new CreateOrReadResult(inserted == 1, original); + } + + /** Reads the permanent issuance record by its stable canonical request ID. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByControlPlaneRequestId(String controlPlaneRequestId) { + requireOwnerTransaction(); + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + Record row = + dsl.fetchOne( + "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE control_plane_request_id = ?", + controlPlaneRequestId); + return Optional.ofNullable(row == null ? null : toIssuanceRecord(row)); + } + + /** + * Erases only the expired encrypted response envelope for one existing compact issuance row. + * + *

The immutable database expiry and database wall clock decide eligibility. A repeated call + * for a row carrying the closed erasure marker returns that same compact record without writing; + * missing or inconsistent envelope state fails closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ResponseEnvelopeErasureResult eraseExpiredResponseEnvelope(String controlPlaneRequestId) { + requireOwnerTransaction(); + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + IssuanceRecord before = toIssuanceRecord(lockByRequestId(controlPlaneRequestId)); + if (before.responseEnvelopeErasedAt() != null) { + return new ResponseEnvelopeErasureResult(false, before); + } + + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET encrypted_response_envelope = NULL " + + "WHERE control_plane_request_id = ? " + + "AND encrypted_response_envelope IS NOT NULL " + + "AND response_envelope_erased_at IS NULL " + + "AND response_envelope_expires_at <= clock_timestamp()", + controlPlaneRequestId); + if (changed != 1) { + throw unavailable(); + } + + IssuanceRecord erased = toIssuanceRecord(lockByRequestId(controlPlaneRequestId)); + if (!sameErasureIdentity(before, erased) + || erased.encryptedResponseEnvelope() != null + || erased.responseEnvelopeErasedAt() == null + || erased.responseEnvelopeErasedAt().isBefore(erased.responseEnvelopeExpiresAt())) { + throw unavailable(); + } + return new ResponseEnvelopeErasureResult(true, erased); + } + + /** + * Atomically consumes an unexpired exact reference binding for one owner attempt. + * + *

The stored redemption projection contains only the immutable fingerprint and the exact + * source-bound authority bundle. An exact retry returns that same projection with {@code + * replay=true}; it does not authorize a different owner attempt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public RedemptionResult redeemExact(RedemptionRequest request) { + requireOwnerTransaction(); + validateRedemptionRequest(request); + Record row = lockByRequestId(request.controlPlaneRequestId()); + if (row == null) { + throw unavailable(); + } + IssuanceRecord issuance = toIssuanceRecord(row); + requireSameRedemptionBinding(request, issuance); + + if (issuance.status() == Status.REDEEMED) { + if (!request.redeemerWorkloadUri().equals(issuance.redemptionRedeemerWorkloadUri()) + || !request.ownerAttemptId().equals(issuance.redemptionOwnerAttemptId()) + || request.ownerFence() != issuance.redemptionOwnerFence()) { + throw conflict(); + } + return redemptionResult(issuance, true); + } + if (issuance.referenceExpiresAt().compareTo(request.now()) <= 0) { + throw new ReferenceExpiredException(); + } + + int changed = + dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'REDEEMED', redemption_redeemer_workload_uri = ?, " + + "redemption_owner_attempt_id = ?, redemption_owner_fence = ?, " + + "redeemed_at = CAST(? AS TIMESTAMPTZ), " + + "redemption_reference_fingerprint = ?, " + + "redemption_authority_evidence_bundle = ? " + + "WHERE control_plane_request_id = ? AND status = 'ISSUED' " + + "AND reference_expires_at > CAST(? AS TIMESTAMPTZ)", + request.redeemerWorkloadUri(), + request.ownerAttemptId(), + request.ownerFence(), + utc(request.now()), + request.authorizationReferenceFingerprint(), + request.authorityEvidenceBundle(), + request.controlPlaneRequestId(), + utc(request.now())); + if (changed != 1) { + throw unavailable(); + } + + Record redeemedRow = lockByRequestId(request.controlPlaneRequestId()); + IssuanceRecord redeemed = toIssuanceRecord(redeemedRow); + return redemptionResult(redeemed, false); + } + + private Record lockByRequestId(String requestId) { + return dsl.fetchOne( + "SELECT " + + SELECT_COLUMNS + + " FROM " + + TABLE + + " WHERE control_plane_request_id = ? FOR UPDATE", + requestId); + } + + private IssuanceRecord toIssuanceRecord(Record row) { + if (row == null) { + throw unavailable(); + } + IssuanceRecord issuance = + new IssuanceRecord( + requiredControlPlaneRequestId(row.get("control_plane_request_id", String.class)), + requiredBytes(row, "pre_authorization_tuple", MAX_TUPLE_BYTES), + requiredDigest(row.get("mutation_digest", String.class)), + requiredWorkloadUri(row.get("issuance_workload_uri", String.class)), + requiredUuid(row.get("reservation_owner_id", UUID.class), "reservation owner ID"), + requiredPositive( + row.get("reservation_claim_fence", Long.class), "reservation claim fence"), + requiredUuid(row.get("issuance_operation_id", UUID.class), "issuance operation ID"), + requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"), + bundleReference(row), + requiredBytes(row, "authority_evidence_bundle", MAX_AUTHORITY_BUNDLE_BYTES), + requiredFingerprint(row.get("authorization_reference_fingerprint", String.class)), + optionalBytes(row, "encrypted_response_envelope", MAX_ENCRYPTED_ENVELOPE_BYTES), + requiredInstant(row.get("issued_at", OffsetDateTime.class), "issue time"), + requiredInstant( + row.get("reference_expires_at", OffsetDateTime.class), "reference expiry"), + requiredInstant( + row.get("response_envelope_expires_at", OffsetDateTime.class), + "response-envelope expiry"), + optionalInstant( + row.get("response_envelope_erased_at", OffsetDateTime.class), + "response-envelope erasure time"), + parseStatus(row.get("status", String.class)), + optionalWorkloadUri(row.get("redemption_redeemer_workload_uri", String.class)), + optionalUuid(row.get("redemption_owner_attempt_id", UUID.class), "owner attempt ID"), + optionalPositive(row.get("redemption_owner_fence", Long.class), "owner fence"), + optionalInstant(row.get("redeemed_at", OffsetDateTime.class), "redemption time"), + optionalFingerprint(row.get("redemption_reference_fingerprint", String.class)), + optionalBytes(row, "redemption_authority_evidence_bundle", MAX_AUTHORITY_BUNDLE_BYTES)); + validateDurableRecord(issuance); + return issuance; + } + + private static void validateDurableRecord(IssuanceRecord issuance) { + try { + StartSessionPreAuthorizationReservationTuple tuple = + decodeTuple(issuance.preAuthorizationTuple()); + if (!issuance.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(issuance.mutationDigest()) + || !issuance.issuanceWorkloadUri().endsWith("/sa/logging-admin-service") + || issuance.reservationClaimFence() <= 0L + || issuance.issuanceFence() <= 0L + || !Long.toString(issuance.issuanceFence()) + .equals(issuance.bundleReference().sourceFence()) + || !issuance.referenceExpiresAt().isAfter(issuance.issuedAt()) + || issuance.referenceExpiresAt().isAfter(issuance.issuedAt().plus(MAX_REFERENCE_LIFETIME)) + || !issuance.responseEnvelopeExpiresAt().isAfter(issuance.referenceExpiresAt()) + || issuance + .responseEnvelopeExpiresAt() + .isAfter(issuance.referenceExpiresAt().plus(MAX_RESPONSE_RECOVERY_WINDOW))) { + throw unavailable(); + } + if (issuance.status() == Status.REDEEMED + && (!ownerWorkloadUri(issuance.issuanceWorkloadUri(), issuance.preAuthorizationTuple()) + .equals(issuance.redemptionRedeemerWorkloadUri()) + || !issuance + .authorizationReferenceFingerprint() + .equals(issuance.redemptionReferenceFingerprint()) + || !Arrays.equals( + issuance.authorityEvidenceBundle(), + issuance.redemptionAuthorityEvidenceBundle()))) { + throw unavailable(); + } + } catch (IllegalStateException stateFailure) { + throw stateFailure; + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void validateCandidate(IssuanceCandidate candidate) { + Objects.requireNonNull(candidate, "issuance candidate is required"); + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + candidate.controlPlaneRequestId()); + byte[] tupleBytes = requireBytes(candidate.preAuthorizationTuple(), MAX_TUPLE_BYTES, "tuple"); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(tupleBytes); + if (!candidate.controlPlaneRequestId().equals(tuple.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(candidate.mutationDigest())) { + throw new IllegalArgumentException("pre-authorization tuple identity or digest mismatches"); + } + requireDigest(candidate.mutationDigest()); + String issuer = requireWorkloadUri(candidate.issuanceWorkloadUri()); + if (!issuer.endsWith("/sa/logging-admin-service")) { + throw new IllegalArgumentException("StartSession issuer must be Logging/Admin workload"); + } + requireNonNilUuid(candidate.reservationOwnerId(), "reservationOwnerId"); + requirePositive(candidate.reservationClaimFence(), "reservationClaimFence"); + requireNonNilUuid(candidate.issuanceOperationId(), "issuanceOperationId"); + requirePositive(candidate.issuanceFence(), "issuanceFence"); + requireBundleReference(candidate.bundleReference(), candidate.issuanceFence()); + requireBytes( + candidate.authorityEvidenceBundle(), MAX_AUTHORITY_BUNDLE_BYTES, "authority bundle"); + requireFingerprint(candidate.authorizationReferenceFingerprint()); + requireBytes( + candidate.encryptedResponseEnvelope(), + MAX_ENCRYPTED_ENVELOPE_BYTES, + "encrypted response envelope"); + Objects.requireNonNull(candidate.issuedAt(), "issue time is required"); + Objects.requireNonNull(candidate.referenceExpiresAt(), "reference expiry is required"); + Objects.requireNonNull( + candidate.responseEnvelopeExpiresAt(), "response-envelope expiry is required"); + if (!candidate.issuedAt().isAfter(Instant.EPOCH) + || !candidate.referenceExpiresAt().isAfter(candidate.issuedAt()) + || candidate.referenceExpiresAt().isAfter(candidate.issuedAt().plus(MAX_REFERENCE_LIFETIME)) + || !candidate.responseEnvelopeExpiresAt().isAfter(candidate.referenceExpiresAt()) + || candidate + .responseEnvelopeExpiresAt() + .isAfter(candidate.referenceExpiresAt().plus(MAX_RESPONSE_RECOVERY_WINDOW))) { + throw new IllegalArgumentException("authorization reference lifetime is outside its bound"); + } + } + + private static void validateRedemptionRequest(RedemptionRequest request) { + Objects.requireNonNull(request, "redemption request is required"); + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + request.controlPlaneRequestId()); + byte[] tupleBytes = requireBytes(request.preAuthorizationTuple(), MAX_TUPLE_BYTES, "tuple"); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(tupleBytes); + if (!request.controlPlaneRequestId().equals(tuple.controlPlaneRequestId())) { + throw new IllegalArgumentException("pre-authorization tuple request ID mismatches"); + } + requireDigest(tuple.mutationDigest()); + requireFingerprint(request.authorizationReferenceFingerprint()); + requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId"); + requirePositive(request.reservationClaimFence(), "reservationClaimFence"); + String redeemer = requireWorkloadUri(request.redeemerWorkloadUri()); + if (!redeemer.endsWith("/sa/" + tuple.targetOwner())) { + throw new IllegalArgumentException("redeemer workload does not match the typed target owner"); + } + requireNonNilUuid(request.ownerAttemptId(), "ownerAttemptId"); + requirePositive(request.ownerFence(), "ownerFence"); + requireBytes(request.authorityEvidenceBundle(), MAX_AUTHORITY_BUNDLE_BYTES, "authority bundle"); + Objects.requireNonNull(request.now(), "redemption time is required"); + if (!request.now().isAfter(Instant.EPOCH)) { + throw new IllegalArgumentException("redemption time must be after the Unix epoch"); + } + } + + private static void requireSameOriginalBinding( + IssuanceCandidate candidate, IssuanceRecord original) { + if (!Arrays.equals(candidate.preAuthorizationTuple(), original.preAuthorizationTuple()) + || !candidate.mutationDigest().equals(original.mutationDigest()) + || !candidate.issuanceWorkloadUri().equals(original.issuanceWorkloadUri()) + || !candidate.reservationOwnerId().equals(original.reservationOwnerId()) + || candidate.reservationClaimFence() != original.reservationClaimFence()) { + throw conflict(); + } + } + + private static boolean sameErasureIdentity(IssuanceRecord before, IssuanceRecord after) { + return before.controlPlaneRequestId().equals(after.controlPlaneRequestId()) + && Arrays.equals(before.preAuthorizationTuple(), after.preAuthorizationTuple()) + && before.mutationDigest().equals(after.mutationDigest()) + && before.issuanceWorkloadUri().equals(after.issuanceWorkloadUri()) + && before.reservationOwnerId().equals(after.reservationOwnerId()) + && before.reservationClaimFence() == after.reservationClaimFence() + && before.issuanceOperationId().equals(after.issuanceOperationId()) + && before.issuanceFence() == after.issuanceFence() + && before.bundleReference().equals(after.bundleReference()) + && Arrays.equals(before.authorityEvidenceBundle(), after.authorityEvidenceBundle()) + && before + .authorizationReferenceFingerprint() + .equals(after.authorizationReferenceFingerprint()) + && before.issuedAt().equals(after.issuedAt()) + && before.referenceExpiresAt().equals(after.referenceExpiresAt()) + && before.responseEnvelopeExpiresAt().equals(after.responseEnvelopeExpiresAt()) + && before.status() == after.status() + && Objects.equals( + before.redemptionRedeemerWorkloadUri(), after.redemptionRedeemerWorkloadUri()) + && Objects.equals(before.redemptionOwnerAttemptId(), after.redemptionOwnerAttemptId()) + && Objects.equals(before.redemptionOwnerFence(), after.redemptionOwnerFence()) + && Objects.equals(before.redeemedAt(), after.redeemedAt()) + && Objects.equals( + before.redemptionReferenceFingerprint(), after.redemptionReferenceFingerprint()) + && Arrays.equals( + before.redemptionAuthorityEvidenceBundle(), after.redemptionAuthorityEvidenceBundle()); + } + + private static BundleReference bundleReference(Record row) { + return new BundleReference( + row.get("bundle_version", String.class), + row.get("bundle_source_version", String.class), + row.get("bundle_source_fence", String.class), + row.get("bundle_linearization", String.class)); + } + + private static void requireBundleReference(BundleReference reference, long issuanceFence) { + Objects.requireNonNull(reference, "original authority bundle reference is required"); + if (!Long.toString(issuanceFence).equals(reference.sourceFence())) { + throw new IllegalArgumentException( + "original bundle source fence must equal the Account issuance fence"); + } + } + + private static void requireSameRedemptionBinding( + RedemptionRequest request, IssuanceRecord issuance) { + if (!Arrays.equals(request.preAuthorizationTuple(), issuance.preAuthorizationTuple()) + || !request + .authorizationReferenceFingerprint() + .equals(issuance.authorizationReferenceFingerprint()) + || !request.reservationOwnerId().equals(issuance.reservationOwnerId()) + || request.reservationClaimFence() != issuance.reservationClaimFence() + || !Arrays.equals(request.authorityEvidenceBundle(), issuance.authorityEvidenceBundle()) + || !request + .redeemerWorkloadUri() + .equals( + ownerWorkloadUri( + issuance.issuanceWorkloadUri(), request.preAuthorizationTuple()))) { + throw conflict(); + } + } + + private static String ownerWorkloadUri(String issuerWorkloadUri, byte[] tupleBytes) { + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(tupleBytes); + int serviceSeparator = issuerWorkloadUri.lastIndexOf("/sa/"); + if (serviceSeparator < 0) { + throw unavailable(); + } + return issuerWorkloadUri.substring(0, serviceSeparator) + "/sa/" + tuple.targetOwner(); + } + + private static RedemptionResult redemptionResult(IssuanceRecord issuance, boolean replay) { + if (issuance.status() != Status.REDEEMED + || !issuance + .authorizationReferenceFingerprint() + .equals(issuance.redemptionReferenceFingerprint()) + || !Arrays.equals( + issuance.authorityEvidenceBundle(), issuance.redemptionAuthorityEvidenceBundle())) { + throw unavailable(); + } + return new RedemptionResult( + issuance.authorizationReferenceFingerprint(), + issuance.redemptionAuthorityEvidenceBundle(), + issuance.issuanceOperationId(), + issuance.issuanceFence(), + replay); + } + + private static StartSessionPreAuthorizationReservationTuple decodeTuple(byte[] bytes) { + String json = new String(bytes, StandardCharsets.UTF_8); + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json); + if (!Arrays.equals(bytes, tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("pre-authorization tuple bytes are not canonical UTF-8"); + } + return tuple; + } + + private static String requiredControlPlaneRequestId(String value) { + try { + return StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + value); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static String requireWorkloadUri(String value) { + if (value == null + || value.length() > 256 + || !SPIFFE_WORKLOAD_URI.matcher(value).matches() + || !URI.create(value).toASCIIString().equals(value)) { + throw new IllegalArgumentException("authenticated SPIFFE workload URI is malformed"); + } + return value; + } + + private static String requiredWorkloadUri(String value) { + try { + return requireWorkloadUri(value); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static String optionalWorkloadUri(String value) { + return value == null ? null : requiredWorkloadUri(value); + } + + private static String requireDigest(String value) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException("mutation digest is malformed"); + } + return value; + } + + private static String requiredDigest(String value) { + try { + return requireDigest(value); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static String requireFingerprint(String value) { + if (value == null || !FINGERPRINT.matcher(value).matches()) { + throw new IllegalArgumentException("authorization-reference fingerprint is malformed"); + } + return value; + } + + private static String requiredFingerprint(String value) { + try { + return requireFingerprint(value); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static String optionalFingerprint(String value) { + return value == null ? null : requiredFingerprint(value); + } + + private static byte[] requireBytes(byte[] value, int maximum, String field) { + if (value == null || value.length == 0 || value.length > maximum) { + throw new IllegalArgumentException(field + " bytes are missing or exceed their bound"); + } + return value; + } + + private static byte[] requiredBytes(Record row, String field, int maximum) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0 || value.length > maximum) { + throw unavailable(); + } + return value; + } + + private static byte[] optionalBytes(Record row, String field, int maximum) { + byte[] value = row.get(field, byte[].class); + if (value == null) { + return null; + } + if (value.length == 0 || value.length > maximum) { + throw unavailable(); + } + return value; + } + + private static UUID requiredUuid(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw unavailable(); + } + return value; + } + + private static UUID optionalUuid(UUID value, String field) { + return value == null ? null : requiredUuid(value, field); + } + + private static long requiredPositive(Long value, String field) { + if (value == null || value <= 0L) { + throw unavailable(); + } + return value; + } + + private static Long optionalPositive(Long value, String field) { + if (value == null) { + return null; + } + if (value <= 0L) { + throw unavailable(); + } + return value; + } + + private static Instant requiredInstant(OffsetDateTime value, String field) { + if (value == null || !value.toInstant().isAfter(Instant.EPOCH)) { + throw unavailable(); + } + return value.toInstant(); + } + + private static Instant optionalInstant(OffsetDateTime value, String field) { + return value == null ? null : requiredInstant(value, field); + } + + private static Status parseStatus(String value) { + try { + return Status.valueOf(value); + } catch (RuntimeException malformed) { + throw unavailable(); + } + } + + private static void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "StartSession operator authorization storage requires an active Account transaction"); + } + } + + private static UUID requireNonNilUuid(UUID value, String field) { + if (value == null || NIL_UUID.equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical nonnil UUID"); + } + return value; + } + + private static long requirePositive(long value, String field) { + if (value <= 0L) { + throw new IllegalArgumentException(field + " must be positive"); + } + return value; + } + + private static OffsetDateTime utc(Instant instant) { + return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); + } + + private static IllegalStateException conflict() { + return new IllegalStateException( + "StartSession operator authorization request conflicts with its immutable binding"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Exact StartSession operator authorization evidence unavailable"); + } + + public enum Status { + ISSUED, + REDEEMED + } + + public record CreateOrReadResult(boolean created, IssuanceRecord issuance) { + public CreateOrReadResult { + Objects.requireNonNull(issuance, "issuance record is required"); + } + } + + public record ResponseEnvelopeErasureResult(boolean erasedNow, IssuanceRecord issuance) { + public ResponseEnvelopeErasureResult { + Objects.requireNonNull(issuance, "issuance record is required"); + if (issuance.encryptedResponseEnvelope() != null + || issuance.responseEnvelopeErasedAt() == null) { + throw unavailable(); + } + } + } + + /** Candidate output fields must be created by the Account authority service, never this store. */ + public record IssuanceCandidate( + String controlPlaneRequestId, + byte[] preAuthorizationTuple, + String mutationDigest, + String issuanceWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + UUID issuanceOperationId, + long issuanceFence, + BundleReference bundleReference, + byte[] authorityEvidenceBundle, + String authorizationReferenceFingerprint, + byte[] encryptedResponseEnvelope, + Instant issuedAt, + Instant referenceExpiresAt, + Instant responseEnvelopeExpiresAt) { + public IssuanceCandidate { + Objects.requireNonNull(bundleReference, "original authority bundle reference is required"); + preAuthorizationTuple = copy(preAuthorizationTuple); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + encryptedResponseEnvelope = copy(encryptedResponseEnvelope); + } + + @Override + public byte[] preAuthorizationTuple() { + return copy(preAuthorizationTuple); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public byte[] encryptedResponseEnvelope() { + return copy(encryptedResponseEnvelope); + } + + @Override + public String toString() { + return "IssuanceCandidate[controlPlaneRequestId=" + + controlPlaneRequestId + + ", tuple/evidence/envelope redacted]"; + } + } + + /** Immutable durable row view; raw references appear only inside its encrypted envelope. */ + public record IssuanceRecord( + String controlPlaneRequestId, + byte[] preAuthorizationTuple, + String mutationDigest, + String issuanceWorkloadUri, + UUID reservationOwnerId, + long reservationClaimFence, + UUID issuanceOperationId, + long issuanceFence, + BundleReference bundleReference, + byte[] authorityEvidenceBundle, + String authorizationReferenceFingerprint, + byte[] encryptedResponseEnvelope, + Instant issuedAt, + Instant referenceExpiresAt, + Instant responseEnvelopeExpiresAt, + Instant responseEnvelopeErasedAt, + Status status, + String redemptionRedeemerWorkloadUri, + UUID redemptionOwnerAttemptId, + Long redemptionOwnerFence, + Instant redeemedAt, + String redemptionReferenceFingerprint, + byte[] redemptionAuthorityEvidenceBundle) { + public IssuanceRecord { + preAuthorizationTuple = copy(preAuthorizationTuple); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + encryptedResponseEnvelope = copy(encryptedResponseEnvelope); + redemptionAuthorityEvidenceBundle = copy(redemptionAuthorityEvidenceBundle); + if ((encryptedResponseEnvelope == null) != (responseEnvelopeErasedAt != null) + || (responseEnvelopeErasedAt != null + && responseEnvelopeErasedAt.isBefore(responseEnvelopeExpiresAt))) { + throw unavailable(); + } + Objects.requireNonNull(status, "status is required"); + requireBundleReference(bundleReference, issuanceFence); + if (status == Status.ISSUED + && (redemptionRedeemerWorkloadUri != null + || redemptionOwnerAttemptId != null + || redemptionOwnerFence != null + || redeemedAt != null + || redemptionReferenceFingerprint != null + || redemptionAuthorityEvidenceBundle != null)) { + throw unavailable(); + } + if (status == Status.REDEEMED + && (redemptionRedeemerWorkloadUri == null + || redemptionOwnerAttemptId == null + || redemptionOwnerFence == null + || redeemedAt == null + || redemptionReferenceFingerprint == null + || redemptionAuthorityEvidenceBundle == null)) { + throw unavailable(); + } + } + + @Override + public byte[] preAuthorizationTuple() { + return copy(preAuthorizationTuple); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public byte[] encryptedResponseEnvelope() { + return copy(encryptedResponseEnvelope); + } + + @Override + public byte[] redemptionAuthorityEvidenceBundle() { + return copy(redemptionAuthorityEvidenceBundle); + } + + @Override + public String toString() { + return "IssuanceRecord[controlPlaneRequestId=" + + controlPlaneRequestId + + ", status=" + + status + + ", tuple/evidence/envelope redacted]"; + } + } + + public record RedemptionRequest( + String controlPlaneRequestId, + byte[] preAuthorizationTuple, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + String redeemerWorkloadUri, + UUID ownerAttemptId, + long ownerFence, + byte[] authorityEvidenceBundle, + Instant now) { + public RedemptionRequest { + preAuthorizationTuple = copy(preAuthorizationTuple); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + } + + @Override + public byte[] preAuthorizationTuple() { + return copy(preAuthorizationTuple); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public String toString() { + return "RedemptionRequest[controlPlaneRequestId=" + + controlPlaneRequestId + + ", tuple/evidence redacted]"; + } + } + + /** The one-time result contains authority projection only; it never contains the opaque ref. */ + public record RedemptionResult( + String authorizationReferenceFingerprint, + byte[] authorityEvidenceBundle, + UUID issuanceOperationId, + long issuanceFence, + boolean replay) { + public RedemptionResult { + authorityEvidenceBundle = copy(authorityEvidenceBundle); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public String toString() { + return "RedemptionResult[issuanceOperationId=" + + issuanceOperationId + + ", replay=" + + replay + + ", authority bundle redacted]"; + } + } + + public static final class ReferenceExpiredException extends IllegalStateException { + private ReferenceExpiredException() { + super("StartSession operator authorization reference is expired"); + } + } + + private static byte[] copy(byte[] value) { + return value == null ? null : value.clone(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java new file mode 100644 index 0000000000..8c6bea6cd2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java @@ -0,0 +1,73 @@ +package net.firedevops.firemud.accountservice.security; + +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.Status; +import java.util.Optional; +import java.util.function.Supplier; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** Service-local certificate identity gate for only the JWT signer materialization RPCs. */ +@Component("accountJwtSignerMaterializerTlsInterceptor") +public final class AccountJwtSignerMaterializerTlsInterceptor implements ServerInterceptor { + private static final Context.Key AUTHENTICATED_BINDING = + Context.key("account-jwt-signer-materializer-trust-binding"); + + private final Supplier> trustBindingProvider; + + @Autowired + public AccountJwtSignerMaterializerTlsInterceptor( + AccountJwtSignerMaterializerTrustBinding trustBindingProvider) { + this(trustBindingProvider::current); + } + + AccountJwtSignerMaterializerTlsInterceptor(Supplier> trustBindingProvider) { + this.trustBindingProvider = trustBindingProvider; + } + + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Optional current = trustBindingProvider.get(); + if (current.isEmpty()) { + return deny(call, "JWT materializer trust binding is unavailable"); + } + SSLSession sslSession = call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + if (sslSession == null) { + return deny(call, "Authenticated JWT materializer workload is required"); + } + Binding binding = current.orElseThrow(); + java.security.cert.Certificate[] peerCertificates; + try { + peerCertificates = sslSession.getPeerCertificates(); + } catch (SSLPeerUnverifiedException ex) { + return deny(call, "Authenticated JWT materializer workload is required"); + } + if (!AccountJwtSignerMaterializerTrustBinding.matchesPeer(peerCertificates, binding)) { + return deny(call, "Authenticated JWT materializer workload is required"); + } + Context authenticated = Context.current().withValue(AUTHENTICATED_BINDING, binding); + return Contexts.interceptCall(authenticated, call, headers, next); + } + + /** The service re-reads protected configuration and rejects a changed snapshot before storage. */ + public static Binding authenticatedBinding() { + return AUTHENTICATED_BINDING.get(); + } + + private static ServerCall.Listener deny( + ServerCall call, String description) { + call.close(Status.PERMISSION_DENIED.withDescription(description), new Metadata()); + return new ServerCall.Listener<>() {}; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java new file mode 100644 index 0000000000..c13cd5aa4c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java @@ -0,0 +1,741 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.sql.SQLException; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AccountJwtSignerMaterializationServiceGrpc; +import net.firedevops.firemud.account.v1.ActiveSigner; +import net.firedevops.firemud.account.v1.EnrollBootstrapRequest; +import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; +import net.firedevops.firemud.account.v1.RecordSecretObservationRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +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.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.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.BootstrapOperationException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.Stage; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +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.ObservationPurpose; +import org.jooq.exception.DataAccessException; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Narrow Account-owned operation handoff to the interim mounted-key materializer. + * + *

The exact peer can read Account-selected fixed-Secret generation and PREPARED promotion + * operations, report readbacks, and submit public key identities. It cannot select an operation, + * environment, resource, generation, or {@code kid}; submit private material; publish JWKS; commit + * the Account signer lifecycle; sign tokens; or establish readiness. + */ +@GrpcService( + interceptorNames = "accountJwtSignerMaterializerTlsInterceptor", + blendWithGlobalInterceptors = false) +public class AccountJwtSignerMaterializationService + extends AccountJwtSignerMaterializationServiceGrpc + .AccountJwtSignerMaterializationServiceImplBase { + private final AccountJwtSignerDesiredStateRepository repository; + private final AccountJwtReadinessProbeRepository readinessRepository; + private final AccountJwtSignerMaterializerTrustBinding trustBindingProvider; + private final TransactionTemplate accountTransaction; + private final ObjectProvider bootstrapCoordinatorProvider; + private final ObjectProvider validatorInventorySourceProvider; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Spring injects the same owner repositories into this gRPC adapter so lifecycle validation and persistence share the Account authority and transaction boundary.") + @Autowired + public AccountJwtSignerMaterializationService( + AccountJwtSignerDesiredStateRepository repository, + AccountJwtReadinessProbeRepository readinessRepository, + AccountJwtSignerMaterializerTrustBinding trustBindingProvider, + PlatformTransactionManager transactionManager, + ObjectProvider bootstrapCoordinatorProvider, + ObjectProvider validatorInventorySourceProvider) { + this.repository = repository; + this.readinessRepository = readinessRepository; + this.trustBindingProvider = trustBindingProvider; + this.bootstrapCoordinatorProvider = bootstrapCoordinatorProvider; + this.validatorInventorySourceProvider = validatorInventorySourceProvider; + this.accountTransaction = new TransactionTemplate(transactionManager); + this.accountTransaction.setReadOnly(false); + } + + /** + * Retains the narrow unit-test construction path when optional bootstrap composition is absent. + */ + public AccountJwtSignerMaterializationService( + AccountJwtSignerDesiredStateRepository repository, + AccountJwtReadinessProbeRepository readinessRepository, + AccountJwtSignerMaterializerTrustBinding trustBindingProvider, + PlatformTransactionManager transactionManager) { + this(repository, readinessRepository, trustBindingProvider, transactionManager, null, null); + } + + @Override + public void enrollBootstrap( + EnrollBootstrapRequest request, StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + Binding binding = requireCurrentAuthenticatedBinding(); + AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator(); + if (coordinator == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Account JWT signer bootstrap is not enabled") + .asRuntimeException(); + } + AccountJwtSignerBootstrapCoordinator.EnrollmentAcknowledgement acknowledgement = + coordinator.enrollOnce(); + requireUnchangedTrustBinding(binding); + responseObserver.onNext(toEnrollmentResponse(acknowledgement)); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + @Override + public void getCurrentGenerationRequest( + GetCurrentGenerationRequestRequest request, + StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + Binding binding = requireCurrentAuthenticatedBinding(); + GenerationRequest current = + accountTransaction.execute( + status -> { + GenerationRequest requested = + repository.ensureCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + requireUnchangedTrustBinding(binding); + return requested; + }); + if (current == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "JWT signer generation request is unavailable"); + } + requireUnchangedTrustBinding(binding); + if (current.phase() == GenerationPhase.GENERATION_RECORDED) { + AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator(); + if (coordinator != null) { + var progress = coordinator.reconcileCurrentGenerationOnce(current.operationId()); + requireUnchangedTrustBinding(binding); + if (progress.stage() != Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE) { + throw Status.FAILED_PRECONDITION + .withDescription( + "Account signer generation is durable but publication or mount reconciliation is incomplete") + .asRuntimeException(); + } + } + } + responseObserver.onNext(toRequestResponse(current)); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + @Override + public void recordSecretObservation( + RecordSecretObservationRequest request, + StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + UUID operationId = parseOperationId(request.getOperationId()); + Binding binding = requireCurrentAuthenticatedBinding(); + GenerationRequest current = + accountTransaction.execute( + status -> { + GenerationRequest observed = + repository.recordSecretObservation( + binding.accountBinding(), + trustFence(binding), + operationId, + request.getOperationDigest(), + request.getSecretUid(), + request.getObservedResourceVersion()); + requireUnchangedTrustBinding(binding); + return observed; + }); + if (current == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "JWT signer Secret observation is unavailable"); + } + requireUnchangedTrustBinding(binding); + responseObserver.onNext(toRequestResponse(current)); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + @Override + public void recordGenerationResult( + RecordGenerationResultRequest request, + StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + UUID operationId = parseOperationId(request.getOperationId()); + Binding binding = requireCurrentAuthenticatedBinding(); + GenerationResult result = + accountTransaction.execute( + status -> { + GenerationResult persisted = + repository.recordGenerationResult( + binding.accountBinding(), + trustFence(binding), + operationId, + request.getGenerationRequestDigest(), + request.getSecretUid(), + request.getExpectedPriorResourceVersion(), + request.getObservedResourceVersion(), + request.getPublicJwkJson()); + requireUnchangedTrustBinding(binding); + return persisted; + }); + if (result == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "JWT signer generation receipt is unavailable"); + } + requireUnchangedTrustBinding(binding); + responseObserver.onNext(toResultResponse(result)); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + /** Returns only the exact Account PREPARED operation for fixed-Secret reconciliation. */ + @Override + public void getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest request, + StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + Binding binding = requireCurrentAuthenticatedBinding(); + AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator(); + if (coordinator == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Account JWT signer reconciliation is not enabled") + .asRuntimeException(); + } + requireValidatorInventorySourceAvailable(); + PreparedGenerationEvidence preparedForObservation; + try { + preparedForObservation = + accountTransaction.execute( + status -> + repository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding))); + } catch (AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException notPrepared) { + var preparation = coordinator.prepareCurrentPromotionOnce(); + requireUnchangedTrustBinding(binding); + if (preparation.isEmpty()) { + if (ownerConfirmsNoPromotionReadyYet(binding)) { + throw new AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException(); + } + throw new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Account has no complete owner-verified promotion proof"); + } + preparedForObservation = + accountTransaction.execute( + status -> + repository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding))); + } + if (preparedForObservation == null) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared Account signer operation is unavailable"); + } + ObservationContext observationContext = observationContext(preparedForObservation); + // The first PREPARED attempt refreshed ConfigMap and mounted evidence, then sampled the + // protected inventory before its PREPARED transaction. Reobserve here for the dispatch fence; + // recovery of an existing PREPARED operation also gets this independent live recheck. + InventorySnapshot liveInventory = observeCurrentValidatorInventory(observationContext); + requireUnchangedTrustBinding(binding); + PreparedGenerationEvidence prepared = + accountTransaction.execute( + status -> { + PreparedGenerationEvidence current = + repository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding)); + if (!observationContext.equals(observationContext(current))) { + throw new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Prepared signer operation changed during validator inventory proof"); + } + boolean completeProof = + readinessRepository + .readPromotionProof( + binding.accountBinding(), + trustFence(binding), + current.promotion().generationOperationId(), + liveInventory) + .isPresent(); + if (!completeProof) { + throw new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Complete Account readiness proof is unavailable"); + } + PreparedGenerationEvidence evidence = + repository.readAndMarkPreparedPromotionDispatched( + binding.accountBinding(), trustFence(binding)); + requireUnchangedTrustBinding(binding); + return evidence; + }); + if (prepared == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "JWT signer promotion request is unavailable"); + } + requireUnchangedTrustBinding(binding); + responseObserver.onNext(toPromotionRequestResponse(prepared)); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + /** Records Account's public-identity-only readback of the exact fixed-Secret CAS. */ + @Override + public void recordPrivatePromotionResult( + RecordPrivatePromotionResultRequest request, + StreamObserver responseObserver) { + try { + validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); + if (request.hasCurrent() == false + || request.getCurrent().getUnknownFields().asMap().isEmpty() == false + || (request.hasPrevious() + && request.getPrevious().getUnknownFields().asMap().isEmpty() == false)) { + throw new IllegalArgumentException("Promotion result identity is malformed"); + } + UUID promotionOperationId = parseOperationId(request.getPromotionOperationId()); + UUID generationOperationId = parseOperationId(request.getGenerationOperationId()); + Binding binding = requireCurrentAuthenticatedBinding(); + AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator(); + if (coordinator == null) { + throw Status.FAILED_PRECONDITION + .withDescription("Account JWT signer reconciliation is not enabled") + .asRuntimeException(); + } + PrivatePromotionObservation observation = + new PrivatePromotionObservation( + promotionOperationId, + request.getPromotionRequestDigest(), + generationOperationId, + request.getGenerationOperationDigest(), + request.getSecretUid(), + request.getExpectedPriorResourceVersion(), + request.getObservedResourceVersion(), + publicIdentity(request.getCurrent()), + request.hasPrevious() + ? java.util.Optional.of(publicIdentity(request.getPrevious())) + : java.util.Optional.empty(), + request.getResultingSlotsList()); + PrivatePromotionReceipt receipt = + accountTransaction.execute( + status -> { + PrivatePromotionReceipt persisted = + repository.recordPrivatePromotionResult( + binding.accountBinding(), trustFence(binding), observation); + requireUnchangedTrustBinding(binding); + return persisted; + }); + if (receipt == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "JWT signer private promotion receipt is unavailable"); + } + requireUnchangedTrustBinding(binding); + coordinator.reconcilePreparedPromotionOnce(observation, receipt); + requireUnchangedTrustBinding(binding); + responseObserver.onNext( + RecordPrivatePromotionResultResponse.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(receipt.promotionOperationId().toString()) + .setGenerationOperationId(receipt.generationOperationId().toString()) + .setObservedResourceVersion(receipt.observedResourceVersion()) + .setPublicReceiptDigest(receipt.receiptDigest()) + .build()); + responseObserver.onCompleted(); + } catch (RuntimeException ex) { + responseObserver.onError(statusFor(ex).asRuntimeException()); + } + } + + private Binding requireCurrentAuthenticatedBinding() { + Binding authenticated = AccountJwtSignerMaterializerTlsInterceptor.authenticatedBinding(); + Binding current = trustBindingProvider.current().orElse(null); + if (authenticated == null || current == null || !authenticated.equals(current)) { + throw Status.PERMISSION_DENIED + .withDescription("Authenticated JWT materializer workload is required") + .asRuntimeException(); + } + return current; + } + + private AccountJwtSignerBootstrapCoordinator currentBootstrapCoordinator() { + return bootstrapCoordinatorProvider == null + ? null + : bootstrapCoordinatorProvider.getIfAvailable(); + } + + private InventorySnapshot observeCurrentValidatorInventory( + ObservationContext observationContext) { + AccountJwtValidatorInventorySource source = currentValidatorInventorySource(); + try { + return source.observe(observationContext); + } catch (AccountJwtValidatorInventorySource.InventoryUnavailableException failure) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Protected live validator inventory is unavailable"); + } + } + + private static ObservationContext observationContext( + PreparedGenerationEvidence preparedGeneration) { + if (preparedGeneration == null) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared Account generation evidence is unavailable"); + } + var promotion = preparedGeneration.promotion(); + if (!promotion.expectedPreviousActive().equals(promotion.expectedPublishedActive())) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared Account active signer fence is inconsistent"); + } + return new ObservationContext( + promotion.expectedPreviousActive().isEmpty() + ? ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES + : ObservationPurpose.STRICT_READY, + promotion.generationOperationId(), + promotion.generationOperationDigest()); + } + + private void requireValidatorInventorySourceAvailable() { + if (currentValidatorInventorySource() == null) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Protected live validator inventory is unavailable"); + } + } + + private AccountJwtValidatorInventorySource currentValidatorInventorySource() { + return validatorInventorySourceProvider == null + ? null + : validatorInventorySourceProvider.getIfAvailable(); + } + + private void requireUnchangedTrustBinding(Binding expected) { + if (trustBindingProvider.current().filter(expected::equals).isEmpty()) { + throw Status.PERMISSION_DENIED + .withDescription("JWT materializer trust binding changed during the request") + .asRuntimeException(); + } + } + + private boolean ownerConfirmsNoPromotionReadyYet(Binding binding) { + requireUnchangedTrustBinding(binding); + DesiredState state = + accountTransaction.execute(status -> repository.read(binding.accountBinding())); + requireUnchangedTrustBinding(binding); + if (state == null || state.enrollmentIdentity().isEmpty()) { + return false; + } + EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow(); + TrustFence currentTrust = trustFence(binding); + if (!enrollment + .expectedClusterIncarnationUid() + .equals(currentTrust.expectedClusterIncarnationUid()) + || !enrollment.expectedNamespaceUid().equals(currentTrust.expectedNamespaceUid()) + || !enrollment.materializerTrustBindingDigest().equals(currentTrust.bindingDigest()) + || !enrollment.materializerTrustConfigRevision().equals(currentTrust.configRevision()) + || state.preparedOperationId().isPresent()) { + return false; + } + if (state.generationOperationId().isEmpty()) { + boolean unselectedInitialEnrollment = + state.recordVersion() == 1 + && state.durableActive().isEmpty() + && state.publishedActive().isEmpty(); + requireUnchangedTrustBinding(binding); + return unselectedInitialEnrollment; + } + GenerationRequest current = + accountTransaction.execute( + status -> + repository.readCurrentGenerationRequest(binding.accountBinding(), currentTrust)); + requireUnchangedTrustBinding(binding); + return current != null + && (current.phase() == GenerationPhase.OBSERVE_PRIVATE_SECRET + || current.phase() == GenerationPhase.GENERATE_PENDING); + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static GetCurrentGenerationRequestResponse toRequestResponse(GenerationRequest request) { + GetCurrentGenerationRequestResponse.Builder response = + GetCurrentGenerationRequestResponse.newBuilder() + .setSchemaVersion(1) + .setPhase(toWirePhase(request.phase())) + .setOperationId(request.operationId().toString()) + .setOperationDigest(request.operationDigest()) + .setGenerationRequestDigest(request.generationRequestDigest()) + .setDesiredStateVersion(Long.toString(request.desiredStateVersion())) + .setEnvironmentId(request.binding().environmentId()) + .setClusterId(request.binding().clusterId()) + .setNamespace(request.binding().namespace()) + .setExpectedClusterIncarnationUid(request.trustFence().expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(request.trustFence().expectedNamespaceUid()) + .setTrustBindingDigest(request.trustFence().bindingDigest()) + .setTrustConfigRevision(request.trustFence().configRevision()) + .setPrivateSecretName(request.privateSecretName()) + .setTargetGeneration(request.targetGeneration()) + .setTargetKid(request.targetKid()) + .setTargetAlgorithm(request.targetAlgorithm()) + .setOperationAction(request.operationAction()) + .addAllAllowedPrivateSlots(request.allowedPrivateSlots()) + .setSecretUid(request.secretUid()) + .setExpectedSecretResourceVersion(request.expectedSecretResourceVersion()) + .setGenerationReceiptDigest(request.generationReceiptDigest()) + .setPublicKeyFingerprint(request.publicKeyFingerprint()) + .setPublicJwkJson(request.publicJwkJson()) + .setObservedSecretResourceVersion(request.observedSecretResourceVersion()); + request.expectedActive().ifPresent(active -> response.setExpectedActive(toWireActive(active))); + request + .expectedPublishedActive() + .ifPresent(active -> response.setExpectedPublishedActive(toWireActive(active))); + return response.build(); + } + + private static EnrollBootstrapResponse toEnrollmentResponse( + AccountJwtSignerBootstrapCoordinator.EnrollmentAcknowledgement acknowledgement) { + return EnrollBootstrapResponse.newBuilder() + .setSchemaVersion(1) + .setEnvironmentId(acknowledgement.environmentId()) + .setClusterId(acknowledgement.clusterId()) + .setNamespace(acknowledgement.namespace()) + .setExpectedClusterIncarnationUid(acknowledgement.expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(acknowledgement.expectedNamespaceUid()) + .setMaterializerTrustBindingDigest(acknowledgement.materializerTrustBindingDigest()) + .setMaterializerTrustConfigRevision(acknowledgement.materializerTrustConfigRevision()) + .setApiBindingDigest(acknowledgement.apiBindingDigest()) + .setApiConfigRevision(acknowledgement.apiConfigRevision()) + .setApiServerUrl(acknowledgement.apiServerUrl()) + .setApiTlsServerName(acknowledgement.apiTlsServerName()) + .setApiServingCaSha256(acknowledgement.apiServingCaSha256()) + .setApiExpectedUsername(acknowledgement.apiExpectedUsername()) + .setPrivateSecretName(acknowledgement.privateSecretName()) + .setPublicConfigMapName(acknowledgement.publicConfigMapName()) + .setPublicConfigMapUid(acknowledgement.publicConfigMapUid()) + .setPublicConfigMapResourceVersion(acknowledgement.publicConfigMapResourceVersion()) + .setPublicConfigMapSnapshotDigest(acknowledgement.publicConfigMapSnapshotDigest()) + .build(); + } + + private static ActiveSigner toWireActive( + AccountJwtSignerDesiredStateRepository.ActiveSigner active) { + return ActiveSigner.newBuilder() + .setGeneration(active.generation()) + .setKid(active.kid()) + .build(); + } + + private static GetCurrentGenerationRequestResponse.Phase toWirePhase(GenerationPhase phase) { + return switch (phase) { + case OBSERVE_PRIVATE_SECRET -> + GetCurrentGenerationRequestResponse.Phase.OBSERVE_PRIVATE_SECRET; + case GENERATE_PENDING -> GetCurrentGenerationRequestResponse.Phase.GENERATE_PENDING; + case GENERATION_RECORDED -> GetCurrentGenerationRequestResponse.Phase.GENERATION_RECORDED; + }; + } + + private static RecordGenerationResultResponse toResultResponse(GenerationResult result) { + return RecordGenerationResultResponse.newBuilder() + .setSchemaVersion(1) + .setOperationId(result.operationId().toString()) + .setOperationDigest(result.operationDigest()) + .setGenerationRequestDigest(result.generationRequestDigest()) + .setGenerationReceiptDigest(result.receiptDigest()) + .setDesiredStateVersion(Long.toString(result.desiredStateVersion())) + .setEnvironmentId(result.binding().environmentId()) + .setClusterId(result.binding().clusterId()) + .setNamespace(result.binding().namespace()) + .setExpectedClusterIncarnationUid(result.trustFence().expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(result.trustFence().expectedNamespaceUid()) + .setTrustBindingDigest(result.trustFence().bindingDigest()) + .setTrustConfigRevision(result.trustFence().configRevision()) + .setPrivateSecretName(result.privateSecretName()) + .setSecretUid(result.secretUid()) + .setExpectedPriorResourceVersion(result.expectedPriorResourceVersion()) + .setObservedResourceVersion(result.observedResourceVersion()) + .setTargetGeneration(result.targetGeneration()) + .setTargetKid(result.targetKid()) + .setTargetAlgorithm(result.targetAlgorithm()) + .setPublicKeyFingerprint(result.publicKeyFingerprint()) + .setPublicJwkJson(result.publicJwkJson()) + .build(); + } + + private static GetCurrentPromotionRequestResponse toPromotionRequestResponse( + PreparedGenerationEvidence prepared) { + var promotion = prepared.promotion(); + var generation = prepared.generationResult(); + GetCurrentPromotionRequestResponse.Builder response = + GetCurrentPromotionRequestResponse.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(promotion.operationId().toString()) + .setPromotionRequestDigest(promotion.requestDigest()) + .setGenerationOperationId(generation.operationId().toString()) + .setGenerationOperationDigest(generation.operationDigest()) + .setGenerationReceiptDigest(generation.receiptDigest()) + .setEnvironmentId(promotion.binding().environmentId()) + .setClusterId(promotion.binding().clusterId()) + .setNamespace(promotion.binding().namespace()) + .setExpectedClusterIncarnationUid( + promotion.trustFence().expectedClusterIncarnationUid()) + .setExpectedNamespaceUid(promotion.trustFence().expectedNamespaceUid()) + .setTrustBindingDigest(promotion.trustFence().bindingDigest()) + .setTrustConfigRevision(promotion.trustFence().configRevision()) + .setPrivateSecretName(AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME) + .setTargetGeneration(promotion.targetGeneration()) + .setTargetKid(promotion.targetKid()) + .setTargetAlgorithm(promotion.targetAlgorithm()) + .setTargetPublicKeyFingerprint(promotion.targetPublicKeyFingerprint()) + .setExpectedSecretUid(promotion.secretUid()) + .setExpectedSecretResourceVersion(promotion.expectedPrivateResourceVersion()) + .setOperationAction("PROMOTE_PENDING") + .addAllowedPrivateSlots("current.key") + .addAllowedPrivateSlots("pending.key") + .addAllowedPrivateSlots("previous.key"); + promotion + .expectedPreviousActive() + .ifPresent( + previous -> { + response.setExpectedPreviousGeneration(previous.generation()); + response.setExpectedPreviousKid(previous.kid()); + response.setExpectedPreviousPublicKeyFingerprint( + promotion.expectedPreviousPublicKeyFingerprint().orElseThrow()); + }); + return response.build(); + } + + private static PublicKeyIdentity publicIdentity(PromotionPublicKeyIdentity identity) { + return new PublicKeyIdentity( + identity.getGeneration(), identity.getKid(), identity.getPublicKeyFingerprint()); + } + + private static void validateRequest(int schemaVersion, boolean unknownFieldsEmpty) { + if (schemaVersion != 1 || !unknownFieldsEmpty) { + throw Status.INVALID_ARGUMENT + .withDescription("Exact JWT materialization request schema is required") + .asRuntimeException(); + } + } + + private static UUID parseOperationId(String value) { + try { + UUID operationId = UUID.fromString(value); + if (operationId.version() != 4 || !operationId.toString().equals(value)) { + throw new IllegalArgumentException("UUIDv4 required"); + } + return operationId; + } catch (RuntimeException ex) { + throw Status.INVALID_ARGUMENT + .withDescription("JWT signer operation ID must be canonical UUIDv4") + .asRuntimeException(); + } + } + + private static Status statusFor(RuntimeException exception) { + if (exception instanceof StatusRuntimeException statusException) { + return statusException.getStatus(); + } + if (exception instanceof IllegalArgumentException) { + return Status.INVALID_ARGUMENT.withDescription("JWT materialization request is malformed"); + } + if (exception instanceof AccountJwtSignerDesiredStateRepository.IdempotencyConflictException) { + return Status.ALREADY_EXISTS.withDescription( + "JWT materialization operation or public result conflicts with retained Account evidence"); + } + if (exception instanceof BootstrapOperationException) { + return Status.FAILED_PRECONDITION.withDescription( + "Account JWT signer bootstrap enrollment is quarantined"); + } + if (exception instanceof AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException) { + return Status.NOT_FOUND.withDescription("No Account-authorized signer promotion is pending"); + } + if (exception instanceof AccountJwtSignerDesiredStateRepository.StorageUnavailableException + || exception instanceof DataAccessResourceFailureException + || hasConnectionFailure(exception)) { + return Status.UNAVAILABLE.withDescription( + "Account JWT materialization storage is unavailable"); + } + if (exception instanceof AccountJwtSignerDesiredStateRepository.MissingDesiredStateException + || exception + instanceof AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException + || exception + instanceof AccountJwtSignerDesiredStateRepository.MissingGenerationObservationException + || exception + instanceof AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException + || exception instanceof AccountJwtSignerDesiredStateRepository.BindingMismatchException + || exception instanceof AccountJwtSignerDesiredStateRepository.VersionConflictException + || exception instanceof AccountJwtSignerDesiredStateRepository.QuarantinedStateException + || exception + instanceof + AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException) { + return Status.FAILED_PRECONDITION.withDescription( + "No exact current Account JWT signer generation phase is available"); + } + if (exception instanceof DataAccessException) { + return Status.INTERNAL.withDescription( + "Account JWT generation evidence could not be recorded"); + } + return Status.INTERNAL.withDescription("Account JWT materialization could not be completed"); + } + + private static boolean hasConnectionFailure(Throwable failure) { + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current instanceof SQLException sqlException) { + String state = sqlException.getSQLState(); + if (state != null && state.startsWith("08")) { + return true; + } + } + } + return false; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index b3218042c6..15f6f65935 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -1961,6 +1961,47 @@ private Optional findAccountForAuthentication(String usernameOrEmail) { return accountRepository.findByUsername(usernameOrEmail); } + /** + * Explicit internal control-ui owner hook. It performs real primary authentication and consumes + * the exact OTP in the caller's writable issuance transaction; it issues no token or session. The + * owner must catch primary credential denial inside that transaction so failed-attempt accounting + * commits, then report the denial outside it. Successful OTP consumption remains rollback-capable + * when later issuance preparation fails. + */ + @Transactional( + propagation = org.springframework.transaction.annotation.Propagation.MANDATORY, + noRollbackFor = AuthenticationException.class) + public ControlUiPrimaryIdentity authenticateControlUiPrimaryIdentity( + String email, String secret) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable Account issuance transaction required"); + } + PrimaryAuthentication result = authenticateAccountIdentity(email, secret, true); + result.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete); + Account account = result.account(); + UUID accountUuid = UUID.fromString(accountMapper.toDto(account).id()); + return new ControlUiPrimaryIdentity(accountUuid); + } + + /** No external constructor: only successful Account primary authentication creates this proof. */ + public static final class ControlUiPrimaryIdentity { + private final UUID accountId; + + private ControlUiPrimaryIdentity(UUID accountId) { + this.accountId = accountId; + } + + public UUID accountId() { + return accountId; + } + + @Override + public String toString() { + return "ControlUiPrimaryIdentity[redacted]"; + } + } + private PrimaryAuthentication authenticateAccountIdentity( String username, String password, boolean allowEmailLoginOtp) { Optional accountOpt = findAccountForAuthentication(username); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java new file mode 100644 index 0000000000..278e50a59a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java @@ -0,0 +1,617 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyUnavailableException; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.CryptographyUnavailableException; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorityBundle.BundleReference; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.AuthorizationResponse; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.IssueRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RecoverRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.exception.DataAccessException; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.CannotCreateTransactionException; + +/** Disabled-by-default, same-namespace mTLS receiver for human StartSession authorization. */ +@GrpcService +@ConditionalOnProperty( + prefix = "firemud.account.start-session-operator-authorization", + name = "enabled", + havingValue = "true", + matchIfMissing = false) +public final class StartSessionOperatorAuthorizationGrpcService + extends StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceImplBase { + private static final int MAX_TUPLE_BYTES = 8 * 1024; + private static final int MAX_CONTROL_UI_JWT_BYTES = 16 * 1024; + private static final int MAX_AUTHORIZATION_REFERENCE_BYTES = 128; + private static final int MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES = 128 * 1024; + private static final int MAX_FINGERPRINT_BYTES = 137; + private static final UUID NIL_UUID = new UUID(0L, 0L); + private static final String AUTHORIZATION_REFERENCE = "[A-Za-z0-9_-]{43}"; + private static final String AUTHORIZATION_REFERENCE_FINGERPRINT = + "arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}"; + private static final String MUTATION_DIGEST = "[0-9a-f]{64}"; + + private final AccountStartSessionOperatorAuthorizationService authorizationService; + private final String workloadNamespace; + + public StartSessionOperatorAuthorizationGrpcService( + AccountStartSessionOperatorAuthorizationService authorizationService, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.authorizationService = Objects.requireNonNull(authorizationService); + this.workloadNamespace = workloadNamespace; + } + + @Override + public void issueHumanOperatorAuthorizationReference( + IssueHumanOperatorAuthorizationReferenceRequest request, + StreamObserver responseObserver) { + if (!isAllowedPeer("logging-admin-service")) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Logging/Admin workload identity is required"); + return; + } + + final IssueRequest parsed; + try { + parsed = parseIssueRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical StartSession issue input is required"); + return; + } + + invoke( + responseObserver, + () -> { + AuthorizationResponse authorization = authorizationService.issue(parsed); + return toIssueResponse(authorization, verifiedLoggingPeerUri()); + }); + } + + @Override + public void recoverOperatorAuthorizationReference( + RecoverOperatorAuthorizationReferenceRequest request, + StreamObserver responseObserver) { + if (!isAllowedPeer("logging-admin-service")) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Logging/Admin workload identity is required"); + return; + } + + final RecoverRequest parsed; + try { + parsed = parseRecoverRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical StartSession recovery input is required"); + return; + } + + invoke( + responseObserver, + () -> { + AuthorizationResponse authorization = authorizationService.recover(parsed); + return toRecoverResponse(authorization, verifiedLoggingPeerUri()); + }); + } + + @Override + public void redeemOperatorAuthorization( + RedeemOperatorAuthorizationRequest request, + StreamObserver responseObserver) { + if (!isAllowedPeer("game-session-service")) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Game Session workload identity is required"); + return; + } + + final RedeemRequest parsed; + try { + parsed = parseRedeemRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical StartSession redemption input is required"); + return; + } + + invoke(responseObserver, () -> toRedeemResponse(authorizationService.redeem(parsed))); + } + + @Override + public void readRedeemedOperationProjection( + ReadRedeemedOperationProjectionRequest request, + StreamObserver responseObserver) { + if (!isAllowedPeer("game-design-service")) { + fail( + responseObserver, + Status.PERMISSION_DENIED, + "Verified same-namespace Game Design workload identity is required"); + return; + } + + final AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest + parsed; + try { + parsed = parseReadRedeemedOperationProjectionRequest(request); + } catch (IllegalArgumentException malformed) { + fail( + responseObserver, + Status.INVALID_ARGUMENT, + "Canonical StartSession operation projection input is required"); + return; + } + + invoke( + responseObserver, + () -> + toReadRedeemedOperationProjectionResponse( + authorizationService.readRedeemedOperationProjection(parsed), parsed)); + } + + private IssueRequest parseIssueRequest(IssueHumanOperatorAuthorizationReferenceRequest request) { + rejectUnknownFields(request.getUnknownFields().asMap().isEmpty()); + byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes()); + decodeCanonicalTuple(tupleBytes); + String token = requireControlUiJwt(request.getControlUiJwt()); + UUID reservationOwnerId = + canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId"); + long reservationFence = + positiveFence(request.getReservationClaimFence(), "reservationClaimFence"); + UUID claimOwnerId = + canonicalNonNilUuid(request.getCurrentClaimOwnerId(), "currentClaimOwnerId"); + long claimFence = positiveFence(request.getCurrentClaimFence(), "currentClaimFence"); + return new IssueRequest( + token, tupleBytes, reservationOwnerId, reservationFence, claimOwnerId, claimFence); + } + + private RecoverRequest parseRecoverRequest(RecoverOperatorAuthorizationReferenceRequest request) { + rejectUnknownFields(request.getUnknownFields().asMap().isEmpty()); + byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes()); + decodeCanonicalTuple(tupleBytes); + UUID reservationOwnerId = + canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId"); + long reservationFence = + positiveFence(request.getReservationClaimFence(), "reservationClaimFence"); + UUID claimOwnerId = + canonicalNonNilUuid(request.getCurrentClaimOwnerId(), "currentClaimOwnerId"); + long claimFence = positiveFence(request.getCurrentClaimFence(), "currentClaimFence"); + return new RecoverRequest( + tupleBytes, reservationOwnerId, reservationFence, claimOwnerId, claimFence); + } + + private RedeemRequest parseRedeemRequest(RedeemOperatorAuthorizationRequest request) { + rejectUnknownFields(request.getUnknownFields().asMap().isEmpty()); + byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes()); + decodeCanonicalTuple(tupleBytes); + String authorizationReference = + requireAuthorizationReference(request.getOperatorAuthorizationReference()); + String fingerprint = requireFingerprint(request.getAuthorizationReferenceFingerprint()); + UUID reservationOwnerId = + canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId"); + long reservationFence = + positiveFence(request.getReservationClaimFence(), "reservationClaimFence"); + UUID ownerAttemptId = canonicalNonNilUuid(request.getOwnerAttemptId(), "ownerAttemptId"); + long ownerFence = positiveFence(request.getOwnerFence(), "ownerFence"); + return new RedeemRequest( + tupleBytes, + authorizationReference, + fingerprint, + reservationOwnerId, + reservationFence, + ownerAttemptId, + ownerFence); + } + + private AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest + parseReadRedeemedOperationProjectionRequest(ReadRedeemedOperationProjectionRequest request) { + rejectUnknownFields(request.getUnknownFields().asMap().isEmpty()); + byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes()); + decodeCanonicalTuple(tupleBytes); + String fingerprint = requireFingerprint(request.getAuthorizationReferenceFingerprint()); + UUID reservationOwnerId = + canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId"); + long reservationFence = + positiveFence(request.getReservationClaimFence(), "reservationClaimFence"); + UUID ownerAttemptId = canonicalNonNilUuid(request.getOwnerAttemptId(), "ownerAttemptId"); + long ownerFence = positiveFence(request.getOwnerFence(), "ownerFence"); + return new AccountStartSessionOperatorAuthorizationService + .ReadRedeemedOperationProjectionRequest( + tupleBytes, fingerprint, reservationOwnerId, reservationFence, ownerAttemptId, ownerFence); + } + + private boolean isAllowedPeer(String serviceAccount) { + if (SessionContext.hasAuthenticatedCallerContext() + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + return false; + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + return peer != null + && workloadNamespace.equals(peer.namespace()) + && peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/" + serviceAccount); + } + + /** Returns only the exact peer identity authenticated on this successful RPC's TLS context. */ + private String verifiedLoggingPeerUri() { + if (SessionContext.hasAuthenticatedCallerContext() + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalStateException("verified Logging/Admin peer is unavailable"); + } + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !workloadNamespace.equals(peer.namespace()) + || !"logging-admin-service".equals(peer.service()) + || !peer.uri() + .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/logging-admin-service")) { + throw new IllegalStateException("verified Logging/Admin peer is unavailable"); + } + return peer.uri(); + } + + private static byte[] boundedTuple(ByteString tuple) { + if (tuple.isEmpty() || tuple.size() > MAX_TUPLE_BYTES) { + throw new IllegalArgumentException("bounded canonical tuple bytes are required"); + } + return tuple.toByteArray(); + } + + private static StartSessionPreAuthorizationReservationTuple decodeCanonicalTuple( + byte[] exactBytes) { + final String json; + try { + json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(exactBytes)) + .toString(); + } catch (CharacterCodingException malformedUtf8) { + throw new IllegalArgumentException("tuple is not strict UTF-8", malformedUtf8); + } + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json); + if (!Arrays.equals(exactBytes, tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("tuple bytes are not the exact canonical encoding"); + } + return tuple; + } + + private static String requireControlUiJwt(String value) { + if (value == null + || value.isBlank() + || value.length() > MAX_CONTROL_UI_JWT_BYTES + || value.chars().anyMatch(character -> character < 0x21 || character > 0x7e)) { + throw new IllegalArgumentException("bounded compact control-ui JWT is required"); + } + return value; + } + + private static UUID canonicalNonNilUuid(String value, String fieldName) { + if (value == null || value.length() > 36) { + throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID"); + } + try { + UUID parsed = UUID.fromString(value); + if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID", malformed); + } + } + + private static long positiveFence(long value, String fieldName) { + // A protobuf uint64 above Long.MAX_VALUE is exposed as a negative Java long and is rejected. + if (value <= 0L) { + throw new IllegalArgumentException(fieldName + " must be a positive supported uint64"); + } + return value; + } + + private static String requireAuthorizationReference(String value) { + if (value == null + || value.getBytes(StandardCharsets.UTF_8).length > MAX_AUTHORIZATION_REFERENCE_BYTES + || !value.matches(AUTHORIZATION_REFERENCE)) { + throw new IllegalArgumentException("canonical authorization reference is required"); + } + return value; + } + + private static String requireFingerprint(String value) { + if (value == null + || value.getBytes(StandardCharsets.UTF_8).length > MAX_FINGERPRINT_BYTES + || !value.matches(AUTHORIZATION_REFERENCE_FINGERPRINT)) { + throw new IllegalArgumentException("canonical authorization fingerprint is required"); + } + return value; + } + + private static void rejectUnknownFields(boolean requestHasNoUnknownFields) { + if (!requestHasNoUnknownFields) { + throw new IllegalArgumentException("unknown request fields are not supported"); + } + } + + private static IssueHumanOperatorAuthorizationReferenceResponse toIssueResponse( + AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) { + requireResponse(response); + return IssueHumanOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(response.operatorAuthorizationReference()) + .setAuthorizationReferenceFingerprint(response.authorizationReferenceFingerprint()) + .setExpiresAt(timestamp(response.expiresAt())) + .setAuthorityEvidenceBundle(ByteString.copyFrom(response.authorityEvidenceBundle())) + .setBundleReference(toWireBundleReference(response.bundleReference())) + .setAuthenticatedLoggingWorkloadIdentity(authenticatedLoggingWorkloadIdentity) + .build(); + } + + private static RecoverOperatorAuthorizationReferenceResponse toRecoverResponse( + AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) { + requireResponse(response); + return RecoverOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(response.operatorAuthorizationReference()) + .setAuthorizationReferenceFingerprint(response.authorizationReferenceFingerprint()) + .setExpiresAt(timestamp(response.expiresAt())) + .setAuthorityEvidenceBundle(ByteString.copyFrom(response.authorityEvidenceBundle())) + .setBundleReference(toWireBundleReference(response.bundleReference())) + .setAuthenticatedLoggingWorkloadIdentity(authenticatedLoggingWorkloadIdentity) + .build(); + } + + private static void requireResponse(AuthorizationResponse response) { + if (response == null + || response.operatorAuthorizationReference() == null + || response.operatorAuthorizationReference().getBytes(StandardCharsets.UTF_8).length + > MAX_AUTHORIZATION_REFERENCE_BYTES + || !response.operatorAuthorizationReference().matches(AUTHORIZATION_REFERENCE) + || response.authorizationReferenceFingerprint() == null + || response.authorizationReferenceFingerprint().getBytes(StandardCharsets.UTF_8).length + > MAX_FINGERPRINT_BYTES + || !response + .authorizationReferenceFingerprint() + .matches(AUTHORIZATION_REFERENCE_FINGERPRINT) + || response.expiresAt() == null + || !response.expiresAt().isAfter(Instant.EPOCH) + || response.authorityEvidenceBundle() == null + || response.authorityEvidenceBundle().length == 0 + || response.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES + || response.bundleReference() == null) { + throw new IllegalStateException( + "Account produced an invalid StartSession authorization result"); + } + } + + private static AuthorityEvidenceBundleReference toWireBundleReference(BundleReference reference) { + if (reference == null) { + throw new IllegalStateException("Account bundle reference is missing"); + } + return AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(reference.bundleVersion()) + .setSourceVersion(reference.sourceVersion()) + .setSourceFence(reference.sourceFence()) + .setLinearization(reference.linearization()) + .build(); + } + + private static RedeemOperatorAuthorizationResponse toRedeemResponse(RedemptionResult result) { + if (result == null + || result.authorizationReferenceFingerprint() == null + || result.authorizationReferenceFingerprint().getBytes(StandardCharsets.UTF_8).length + > MAX_FINGERPRINT_BYTES + || !result.authorizationReferenceFingerprint().matches(AUTHORIZATION_REFERENCE_FINGERPRINT) + || result.authorityEvidenceBundle() == null + || result.authorityEvidenceBundle().length == 0 + || result.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES + || result.issuanceOperationId() == null + || NIL_UUID.equals(result.issuanceOperationId()) + || result.issuanceFence() <= 0L) { + throw new IllegalStateException("Account produced an invalid StartSession redemption result"); + } + return RedeemOperatorAuthorizationResponse.newBuilder() + .setAuthorizationReferenceFingerprint(result.authorizationReferenceFingerprint()) + .setAuthorityEvidenceBundle(ByteString.copyFrom(result.authorityEvidenceBundle())) + .setIssuanceOperationId(result.issuanceOperationId().toString()) + .setIssuanceFence(result.issuanceFence()) + .setReplay(result.replay()) + .build(); + } + + private ReadRedeemedOperationProjectionResponse toReadRedeemedOperationProjectionResponse( + RedeemedOperationProjection projection, + AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest + request) { + if (projection == null) { + throw new IllegalStateException("Account produced an invalid redeemed operation projection"); + } + byte[] requestTupleBytes = request.canonicalPreAuthorizationTuple(); + byte[] projectionTupleBytes = projection.canonicalPreAuthorizationTuple(); + StartSessionPreAuthorizationReservationTuple tuple = decodeCanonicalTuple(requestTupleBytes); + String expectedRedeemerUri = + "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service"; + if (!StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + projection.controlPlaneRequestId()) + .equals(tuple.controlPlaneRequestId()) + || !Arrays.equals(projectionTupleBytes, requestTupleBytes) + || projection.mutationDigest() == null + || !projection.mutationDigest().matches(MUTATION_DIGEST) + || !tuple.mutationDigest().equals(projection.mutationDigest()) + || !request + .authorizationReferenceFingerprint() + .equals(projection.authorizationReferenceFingerprint()) + || !request.reservationOwnerId().equals(projection.reservationOwnerId()) + || request.reservationClaimFence() != projection.reservationClaimFence() + || !request.ownerAttemptId().equals(projection.ownerAttemptId()) + || request.ownerFence() != projection.ownerFence() + || !GrpcPeerIdentity.isValidNamespace(workloadNamespace) + || !expectedRedeemerUri.equals(projection.redeemerWorkloadUri()) + || projection.referenceExpiresAt() == null + || projection.redeemedAt() == null + || !projection.referenceExpiresAt().isAfter(projection.redeemedAt()) + || projection.issuanceOperationId() == null + || NIL_UUID.equals(projection.issuanceOperationId()) + || projection.issuanceFence() <= 0L + || projection.bundleReference() == null + || projection.authorityEvidenceBundle() == null + || projection.authorityEvidenceBundle().length == 0 + || projection.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES) { + throw new IllegalStateException("Account produced an invalid redeemed operation projection"); + } + return ReadRedeemedOperationProjectionResponse.newBuilder() + .setControlPlaneRequestId(projection.controlPlaneRequestId()) + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(projectionTupleBytes)) + .setMutationDigest(projection.mutationDigest()) + .setAuthorizationReferenceFingerprint(projection.authorizationReferenceFingerprint()) + .setReservationOwnerId(projection.reservationOwnerId().toString()) + .setReservationClaimFence(projection.reservationClaimFence()) + .setAuthenticatedRedeemerWorkloadIdentity(projection.redeemerWorkloadUri()) + .setOwnerAttemptId(projection.ownerAttemptId().toString()) + .setOwnerFence(projection.ownerFence()) + .setReferenceExpiresAt(timestamp(projection.referenceExpiresAt())) + .setRedeemedAt(timestamp(projection.redeemedAt())) + .setIssuanceOperationId(projection.issuanceOperationId().toString()) + .setIssuanceFence(projection.issuanceFence()) + .setBundleReference(toWireBundleReference(projection.bundleReference())) + .setAuthorityEvidenceBundle(ByteString.copyFrom(projection.authorityEvidenceBundle())) + .build(); + } + + private static Timestamp timestamp(Instant instant) { + return Timestamp.newBuilder() + .setSeconds(instant.getEpochSecond()) + .setNanos(instant.getNano()) + .build(); + } + + private static void invoke(StreamObserver observer, Supplier operation) { + try { + observer.onNext(operation.get()); + observer.onCompleted(); + } catch (AccountStartSessionOperatorAuthorizationService.NotFoundException missing) { + fail(observer, Status.NOT_FOUND, "No original StartSession authorization exists"); + } catch (ResponseRecoveryExpiredException expired) { + fail( + observer, + Status.FAILED_PRECONDITION, + "Original StartSession authorization response is no longer recoverable"); + } catch (CannotCreateTransactionException unavailable) { + fail( + observer, + Status.UNAVAILABLE, + "Account operator authorization is temporarily unavailable"); + } catch (KeyUnavailableException + | AccountResponseEnvelopeKeyring.KeyUnavailableException + | CryptographyUnavailableException unavailable) { + fail( + observer, + Status.UNAVAILABLE, + "Account operator authorization is temporarily unavailable"); + } catch (DataAccessException | org.springframework.dao.DataAccessException failure) { + Status status = hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL; + fail( + observer, + status, + status.getCode() == Status.Code.UNAVAILABLE + ? "Account operator authorization is temporarily unavailable" + : "Account operator authorization could not be completed"); + } catch (StatusRuntimeException upstream) { + Status mapped = mapUpstreamStatus(Status.fromThrowable(upstream).getCode()); + fail(observer, mapped, descriptionFor(mapped)); + } catch (IllegalArgumentException malformed) { + fail(observer, Status.INVALID_ARGUMENT, "StartSession authorization input is invalid"); + } catch (IllegalStateException rejected) { + fail( + observer, + Status.FAILED_PRECONDITION, + "Current Account authorization evidence is unavailable"); + } catch (RuntimeException failure) { + fail(observer, Status.INTERNAL, "Account operator authorization could not be completed"); + } + } + + private static boolean hasConnectionFailureSqlState(Throwable failure) { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException exception) { + String sqlState = exception.getSQLState(); + if (sqlState != null && sqlState.startsWith("08")) { + return true; + } + } + } + return false; + } + + private static Status mapUpstreamStatus(Status.Code code) { + return switch (code) { + case INVALID_ARGUMENT -> Status.INVALID_ARGUMENT; + case NOT_FOUND -> Status.NOT_FOUND; + case PERMISSION_DENIED -> Status.PERMISSION_DENIED; + case FAILED_PRECONDITION, ABORTED -> Status.FAILED_PRECONDITION; + case UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED -> Status.UNAVAILABLE; + default -> Status.INTERNAL; + }; + } + + private static String descriptionFor(Status status) { + return switch (status.getCode()) { + case INVALID_ARGUMENT -> "StartSession authorization input is invalid"; + case NOT_FOUND -> "No original StartSession authorization exists"; + case PERMISSION_DENIED -> "Account rejected the authenticated StartSession caller"; + case FAILED_PRECONDITION -> "Current Account authorization evidence is unavailable"; + case UNAVAILABLE -> "Account operator authorization is temporarily unavailable"; + default -> "Account operator authorization could not be completed"; + }; + } + + private static void fail(StreamObserver observer, Status status, String description) { + observer.onError(status.withDescription(description).asRuntimeException()); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java new file mode 100644 index 0000000000..2c42841b14 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -0,0 +1,376 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Genuine creator actor/currentness and same-transaction original Draft ordering; unregistered. */ +public final class AccountControlUiActorService { + private static final AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy POLICY = + new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy( + "account-internal-creator-draft", + "control-ui", + "control-ui", + "firemud-account-service", + "control-ui", + ControlUiJwtProfileValidator.REQUIRED_CLAIMS, + ControlUiJwtProfileValidator.OPTIONAL_CLAIMS, + 300, + 0, + 16384, + claims -> ControlUiJwtProfileValidator.validateClaims(claims, 1)); + private final AccountControlUiIssuanceRepository operations; + private final AccountControlUiAuthority authority; + private final AccountControlUiSignerOwner signers; + private final AccountControlUiCoordination registry; + private final AccountJwtJwksTrustedSource publicSource; + private final SourceIdentity publicSourcePin; + private final AccountPublicJwksCache publicJwksCache; + private final DraftAuthorizationFenceRepository fences; + private final TransactionTemplate transaction; + private final Clock clock; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Draft fence repository is an internal Account owner transaction collaborator.") + public AccountControlUiActorService( + AccountControlUiIssuanceRepository operations, + AccountControlUiAuthority authority, + AccountControlUiSignerOwner signers, + AccountControlUiCoordination registry, + AccountJwtJwksTrustedSource publicSource, + DraftAuthorizationFenceRepository fences, + PlatformTransactionManager transactions, + Clock clock) { + this.operations = Objects.requireNonNull(operations); + this.authority = Objects.requireNonNull(authority); + this.signers = Objects.requireNonNull(signers); + this.registry = Objects.requireNonNull(registry); + this.publicSource = Objects.requireNonNull(publicSource); + this.fences = Objects.requireNonNull(fences); + this.clock = Objects.requireNonNull(clock); + this.publicSourcePin = this.publicSource.sourceIdentity(); + this.publicJwksCache = + new AccountPublicJwksCache( + this.publicSource, publicSourcePin, this.clock, Duration.ofSeconds(30)); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + public AuthenticatedActor authenticate( + String compactJwt, UUID selectedTenant, CapturedEnvironmentBoundary environment) { + return withCurrent( + compactJwt, + selectedTenant, + environment, + current -> + new AuthenticatedActor( + current.stored.accountId, + current.stored.tenantId, + current.stored.operationId, + current.stored.tokenHash)); + } + + /** Exact retained producer recovery; absence alone permits a fresh authenticated claim. */ + boolean readHeldOriginalDraft(DraftAuthorizationFenceBinding original) { + outsideSql(); + return Objects.requireNonNull( + transaction.execute( + ignored -> { + var retained = fences.readOriginalBinding(original.operationId()); + if (retained.isEmpty()) return false; + if (!Arrays.equals(retained.get().canonicalBytes(), original.canonicalBytes())) + throw io.grpc.Status.FAILED_PRECONDITION.asRuntimeException(); + var order = fences.read(original); + if (order.ordering() != DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER + || order.reservedAt() == null + || order.orderedAt() == null + || !Arrays.equals(order.binding(), original.canonicalBytes()) + || fences.readSettlement(original) + != DraftAuthorizationFenceRepository.Settlement.PENDING) + throw io.grpc.Status.FAILED_PRECONDITION.asRuntimeException(); + return true; + })); + } + + /** No transport or World mutation: original Account reservation/order is the only effect. */ + public DraftAuthorizationFenceRepository.FenceSnapshot claimOriginalDraft( + String compactJwt, + DraftAuthorizationFenceBinding original, + CapturedEnvironmentBoundary environment) { + Objects.requireNonNull(original); + return withCurrent( + compactJwt, + original.tenantId(), + environment, + current -> { + if (!original.actorAccountId().equals(current.stored.accountId) + || !exactSources(original.sources(), current.source.sources())) { + throw denied(); + } + // Never wait for a source-first writer while retaining captured owner rows. + fences.lockProducerSourcesNowait(current.source.sources()); + fences.reserve(original); + var order = fences.claimCommitOrder(original); + if (fences.readSettlement(original) + != DraftAuthorizationFenceRepository.Settlement.PENDING) throw denied(); + return order; + }); + } + + T withCurrent( + String compactJwt, + UUID selectedTenant, + CapturedEnvironmentBoundary environment, + Function action) { + outsideSql(); + var signed = verifySigned(compactJwt); + String tokenHash = + AccountControlUiIssuanceRepository.hash(compactJwt.getBytes(StandardCharsets.US_ASCII)); + byte[] exactRegistry = registry.readActive(tokenHash); + return transaction.execute( + ignored -> { + var stored = operations.findToken(tokenHash); + if (stored == null + || !selectedTenant.equals(stored.tenantId) + || !"COMMITTED".equals(stored.status) + || !Arrays.equals(stored.activeRegistry, exactRegistry) + || !Arrays.equals( + stored.claims, AccountControlUiAuthority.canonical(signed.claims.claims()))) { + throw denied(); + } + requireSignerIdentity(stored, signed); + signers.requireOriginal(stored.signerReceipt); + var current = authority.capture(stored.accountId, selectedTenant, environment); + if (!Arrays.equals(current.evidence(), stored.sources)) { + throw denied(); + } + var committed = operations.requireCommitted(stored); + if (!committed.tokenHash().equals(tokenHash)) { + throw denied(); + } + return action.apply(new Current(stored, current)); + }); + } + + /** + * Revalidates an already committed control-ui actor without requiring the caller to forward its + * JWT again. The token jti selects Account's immutable issuance record; active registry readback, + * original signer provenance, expiry, and current Account sources are still independently + * required. The supplied action runs in the same owner transaction as source capture. + */ + T withCurrentCommitted( + UUID actorAccountId, + UUID selectedTenant, + UUID tokenJti, + CapturedEnvironmentBoundary environment, + Function action) { + outsideSql(); + Objects.requireNonNull(actorAccountId, "actor account is required"); + Objects.requireNonNull(selectedTenant, "selected tenant is required"); + Objects.requireNonNull(tokenJti, "control-ui token jti is required"); + Objects.requireNonNull(environment, "captured Account environment is required"); + Objects.requireNonNull(action, "current actor action is required"); + var original = transaction.execute(ignored -> operations.findTokenJti(tokenJti)); + if (original == null + || !actorAccountId.equals(original.accountId) + || !selectedTenant.equals(original.tenantId) + || !tokenJti.equals(original.jti) + || !"COMMITTED".equals(original.status) + || original.tokenHash == null + || original.expiresAt == null + || !clock.instant().isBefore(original.expiresAt)) { + throw denied(); + } + + byte[] exactRegistry = registry.readActive(original.tokenHash); + return transaction.execute( + ignored -> { + var observed = operations.findTokenJti(tokenJti); + if (!sameCommittedOperation(original, observed) + || !Arrays.equals(observed.activeRegistry, exactRegistry)) { + throw denied(); + } + requireStoredActorIdentity(observed, actorAccountId, selectedTenant, tokenJti); + signers.requireOriginal(observed.signerReceipt); + var current = authority.capture(actorAccountId, selectedTenant, environment); + if (!Arrays.equals(current.evidence(), observed.sources) + || !clock.instant().isBefore(observed.expiresAt)) { + throw denied(); + } + operations.requireCommitted(observed); + var committed = operations.findTokenJti(tokenJti); + if (!sameCommittedOperation(observed, committed) + || !Arrays.equals(committed.activeRegistry, exactRegistry)) { + throw denied(); + } + return action.apply(new Current(committed, current)); + }); + } + + /** Production asymmetric/profile verification, also used before any candidate is persisted. */ + SignedObservation verifySigned(String compactJwt) { + outsideSql(); + return new SignedObservation( + new AccountAsymmetricJwtVerifier(publicJwksCache, clock).verify(compactJwt, POLICY), + publicSourcePin); + } + + void requireSignerIdentity( + AccountControlUiIssuanceRepository.Stored stored, SignedObservation observation) { + var signed = observation.claims; + var receipt = AccountControlUiIssuanceRepository.object(stored.signerReceipt); + var pin = observation.pin; + if (!signed.keyId().equals(receipt.get("kid")) + || !pin.environmentId().equals(receipt.get("environmentId")) + || !pin.clusterId().equals(receipt.get("clusterId")) + || !pin.clusterIncarnationUid().equals(receipt.get("clusterIncarnationUid")) + || !pin.namespace().equals(receipt.get("namespace")) + || !pin.namespaceUid().equals(receipt.get("namespaceUid")) + || !pin.configMapUid().equals(receipt.get("publicConfigMapUid")) + || !pin.bindingRevision().equals(receipt.get("apiConfigRevision")) + || !stored.accountId.toString().equals(signed.claims().get("sub")) + || !stored.accountId.toString().equals(signed.claims().get("accountId")) + || !stored.jti.toString().equals(signed.claims().get("jti")) + || !Map.of(stored.tenantId.toString(), List.of("tenantAdmin")) + .equals(signed.claims().get("scopedRoles")) + || signed.claims().containsKey("globalRoles")) { + throw denied(); + } + } + + private static boolean exactSources( + List first, + List second) { + if (first.size() != second.size()) { + return false; + } + for (int index = 0; index < first.size(); index++) { + if (!Arrays.equals(first.get(index).canonicalBytes(), second.get(index).canonicalBytes())) { + return false; + } + } + return true; + } + + private static boolean sameCommittedOperation( + AccountControlUiIssuanceRepository.Stored first, + AccountControlUiIssuanceRepository.Stored second) { + return second != null + && "COMMITTED".equals(second.status) + && first.requestId.equals(second.requestId) + && first.operationId.equals(second.operationId) + && first.jti.equals(second.jti) + && first.accountId.equals(second.accountId) + && first.tenantId.equals(second.tenantId) + && first.callerContextId.equals(second.callerContextId) + && first.caller.equals(second.caller) + && first.requestMacKeyId.equals(second.requestMacKeyId) + && first.requestDigest.equals(second.requestDigest) + && Objects.equals(first.tokenHash, second.tokenHash) + && first.issuedAt.equals(second.issuedAt) + && first.expiresAt.equals(second.expiresAt) + && first.recoveryExpiry.equals(second.recoveryExpiry) + && Arrays.equals(first.claims, second.claims) + && Arrays.equals(first.sources, second.sources) + && Arrays.equals(first.bundle, second.bundle) + && Arrays.equals(first.signerReceipt, second.signerReceipt) + && Arrays.equals(first.pendingRegistry, second.pendingRegistry) + && Arrays.equals(first.activeRegistry, second.activeRegistry); + } + + private static void requireStoredActorIdentity( + AccountControlUiIssuanceRepository.Stored stored, + UUID actorAccountId, + UUID tenantId, + UUID tokenJti) { + Map claims = AccountControlUiIssuanceRepository.object(stored.claims); + if (!actorAccountId.toString().equals(claims.get("sub")) + || !actorAccountId.toString().equals(claims.get("accountId")) + || !tenantId.toString().equals(stored.tenantId.toString()) + || !tokenJti.toString().equals(claims.get("jti")) + || !tokenJti.equals(stored.jti) + || !"control-ui".equals(claims.get("aud"))) { + throw denied(); + } + } + + record Current( + AccountControlUiIssuanceRepository.Stored stored, + AccountControlUiAuthority.Snapshot source) {} + + static final class SignedObservation { + final AccountAsymmetricJwtVerifier.VerifiedClaims claims; + final AccountPublicJwksCache.SourceIdentity pin; + + private SignedObservation( + AccountAsymmetricJwtVerifier.VerifiedClaims claims, + AccountPublicJwksCache.SourceIdentity pin) { + this.claims = claims; + this.pin = pin; + } + } + + /** No externally callable constructor; workload possession or a claimed UUID cannot create it. */ + public static final class AuthenticatedActor { + private final UUID accountId, tenantId, issuanceOperationId; + private final String tokenHash; + + private AuthenticatedActor(UUID accountId, UUID tenantId, UUID operationId, String tokenHash) { + this.accountId = accountId; + this.tenantId = tenantId; + this.issuanceOperationId = operationId; + this.tokenHash = tokenHash; + } + + public UUID accountId() { + return accountId; + } + + public UUID tenantId() { + return tenantId; + } + + public UUID issuanceOperationId() { + return issuanceOperationId; + } + + public String tokenHash() { + return tokenHash; + } + + @Override + public String toString() { + return "AccountControlUiActorService.AuthenticatedActor[redacted]"; + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Signature/registry reads must precede owner SQL locks"); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Exact current authenticated initial creator required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java new file mode 100644 index 0000000000..bb45d3cbe4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java @@ -0,0 +1,242 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual private Coordination reader/CAS with exact catalog, ACL, physical connection and WAITAOF. + */ +public final class AccountControlUiCoordination { + private final AccountCoordinationPinnedConnectionProvider connections; + private final AccountControlUiRegistryReader registryReader; + private final AcknowledgementRequirements acknowledgements; + private final RedisScriptCatalog catalog; + + public AccountControlUiCoordination( + AccountCoordinationPinnedConnectionProvider connections, + AcknowledgementRequirements acknowledgements, + RedisScriptCatalog catalog) { + this.connections = Objects.requireNonNull(connections); + this.registryReader = new AccountControlUiRegistryReader(this.connections); + this.acknowledgements = Objects.requireNonNull(acknowledgements); + this.catalog = Objects.requireNonNull(catalog); + } + + /** Read-only pinned GET and physical expiry; no repair or gameplay-profile interpretation. */ + public byte[] readActive(String tokenHash) { + return registryReader.readActive(tokenHash); + } + + /** Exact readback for the owner's protected delivery workflow. */ + public void requireExactActive(String tokenHash, byte[] exactActive, long expiryMillis) { + outsideSql(); + withConnection( + commands -> { + byte[] key = key(tokenHash); + if (!Arrays.equals(exactActive, commands.get(key))) { + throw denied(); + } + Long expiry = commands.pexpiretime(key); + if (expiry == null || expiry != expiryMillis) { + throw denied(); + } + return null; + }); + } + + /** Only package-local owner workflow may register a non-authorizing pending candidate. */ + Receipt registerPending(String tokenHash, byte[] exactPending, long expiryMillis) { + return cas(tokenHash, new byte[0], exactPending, expiryMillis); + } + + /** The private committed owner readback is mandatory; arbitrary byte callers cannot activate. */ + Receipt activate(AccountControlUiIssuanceRepository.Committed original) { + return cas( + original.tokenHash(), + original.pendingRegistry(), + original.activeRegistry(), + original.expiryMillis()); + } + + /** Durable owner intent is non-authorizing even if this external CAS cannot complete. */ + Receipt revoke(AccountControlUiIssuanceRepository.Stored original) { + outsideSql(); + byte[] replacement = AccountControlUiIssuanceRepository.revokedRegistry(original); + byte[] expected = + withConnection( + commands -> { + byte[] observed = commands.get(key(original.tokenHash)); + Long expiry = commands.pexpiretime(key(original.tokenHash)); + if (expiry == null + || expiry != original.expiryMillis() + || (!Arrays.equals(observed, original.pendingRegistry) + && !Arrays.equals(observed, original.activeRegistry) + && !Arrays.equals(observed, replacement))) { + throw denied(); + } + return observed; + }); + return cas(original.tokenHash, expected, replacement, original.expiryMillis()); + } + + private Receipt cas(String tokenHash, byte[] expected, byte[] replacement, long expiryMillis) { + outsideSql(); + if (expected == null + || replacement == null + || replacement.length == 0 + || replacement.length > 32768 + || expected.length > 32768 + || expiryMillis <= 0) { + throw denied(); + } + var descriptor = AccountControlUiRegistryContract.descriptor(); + if (!descriptor.equals(catalog.require(descriptor.scriptId()))) { + throw denied(); + } + byte[] source; + try (var stream = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + if (stream == null) { + throw denied(); + } + source = stream.readNBytes(32769); + if (source.length == 0 + || source.length > 32768 + || !digest("SHA-256", source).equals(descriptor.sha256())) { + throw denied(); + } + } catch (java.io.IOException | RuntimeException failure) { + throw denied(); + } + return withConnection( + commands -> { + byte[] key = key(tokenHash); + String sha = commands.scriptLoad(source); + if (!digest("SHA-1", source).equals(sha)) { + throw denied(); + } + Long outcome = + commands.evalsha( + sha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + expected, + replacement, + Long.toString(expiryMillis).getBytes(StandardCharsets.US_ASCII)); + if (outcome == null || (outcome != 0L && outcome != 1L)) { + throw denied(); + } + List counts = + commands.dispatch( + WaitAof.INSTANCE, + new ArrayOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE) + .add(acknowledgements.requiredLocalAofCount()) + .add(acknowledgements.requiredReplicaAofCount()) + .add(acknowledgements.timeoutMillis())); + if (counts == null + || counts.size() != 2 + || !(counts.get(0) instanceof Long local) + || !(counts.get(1) instanceof Long replicas) + || local < acknowledgements.requiredLocalAofCount() + || replicas < acknowledgements.requiredReplicaAofCount()) { + throw denied(); + } + Long expiry = commands.pexpiretime(key); + if (!Arrays.equals(replacement, commands.get(key)) + || expiry == null + || expiry != expiryMillis) { + throw denied(); + } + return new Receipt( + tokenHash, + digest("SHA-256", replacement), + expiryMillis, + acknowledgements.requiredLocalAofCount(), + acknowledgements.requiredReplicaAofCount()); + }); + } + + private T withConnection( + java.util.function.Function, T> action) { + try (var connection = connections.openPinnedConnection()) { + if (connection == null + || !connection.isOpen() + || connection.getOptions() == null + || connection.getOptions().isAutoReconnect()) { + throw denied(); + } + var commands = connection.sync(); + if (!"account_coord_app".equals(commands.aclWhoami())) { + throw denied(); + } + return action.apply(commands); + } catch (RuntimeException failure) { + throw denied(); + } + } + + private static byte[] key(String tokenHash) { + if (tokenHash == null || !tokenHash.matches("[0-9a-f]{64}")) { + throw denied(); + } + return ("session:auth:token:" + tokenHash).getBytes(StandardCharsets.US_ASCII); + } + + static String digest(String algorithm, byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(value)); + } catch (java.security.NoSuchAlgorithmException | RuntimeException failure) { + throw denied(); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Coordination calls cannot retain owner SQL locks"); + } + } + + /** Non-authorizing receipt, constructible only after actual durable exact Redis readback. */ + static final class Receipt { + final String tokenHash; + final String recordDigest; + final long expiryMillis; + final long localAof; + final long replicas; + + private Receipt( + String tokenHash, String recordDigest, long expiryMillis, long localAof, long replicas) { + this.tokenHash = tokenHash; + this.recordDigest = recordDigest; + this.expiryMillis = expiryMillis; + this.localAof = localAof; + this.replicas = replicas; + } + } + + private enum WaitAof implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Exact Account control-ui Coordination evidence unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java new file mode 100644 index 0000000000..1bdb46bb2e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java @@ -0,0 +1,858 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Duration; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository.CommittedIssuance; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Read-only Account verification of a signed control-ui actor against committed issuance, + * Coordination, protected signer/JWKS state, and current Account tenant membership sources. + * + *

The returned object is authenticated-current actor evidence only. This class does not issue or + * redeem operator references, select a privileged route, or turn a creator grant into owner + * authority. It deliberately denies global-role claims; callers must perform the approved route + * predicate separately against this current tenant-scoped evidence. + */ +public final class AccountControlUiCurrentActorVerifier { + private static final String ISSUER = "firemud-account-service"; + private static final int MAX_BUNDLE_BYTES = 131072; + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Set SIGNER_RECEIPT_FIELDS = + Set.of( + "schema", + "environmentId", + "clusterId", + "namespace", + "clusterIncarnationUid", + "namespaceUid", + "trustBindingDigest", + "trustConfigRevision", + "apiBindingDigest", + "apiConfigRevision", + "promotionOperationId", + "promotionRequestDigest", + "generationOperationId", + "signerGeneration", + "kid", + "algorithm", + "publicKeyFingerprint", + "privateReceiptDigest", + "privateResourceVersion", + "publicReceiptDigest", + "publicResourceVersion", + "publicConfigMapUid", + "publicDataDigest"); + private static final Set PENDING_RECEIPT_FIELDS = + Set.of( + "schema", + "tokenHash", + "recordDigest", + "expiryMillis", + "aclIdentity", + "localAofCount", + "replicaAofCount"); + private static final Set BUNDLE_FIELDS = + Set.of( + "schema", + "bundleRef", + "snapshotIdentity", + "evaluationIdentity", + "issuer", + "profile", + "audience", + "scope", + "operation", + "tokenIdentity", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "authoritySourceVersions", + "accountIdentitySource", + "outboxCheckpoints", + "roleEvidence"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> OBJECT = new TypeReference<>() {}; + private static final ExplicitRouteProfilePolicy POLICY = + new ExplicitRouteProfilePolicy( + "account-control-ui-current-actor", + ControlUiJwtProfileValidator.PROFILE, + ControlUiJwtProfileValidator.TOKEN_TYPE, + ISSUER, + ControlUiJwtProfileValidator.AUDIENCE, + ControlUiJwtProfileValidator.REQUIRED_CLAIMS, + Set.of(), + 300, + 0, + 16384, + claims -> ControlUiJwtProfileValidator.validateClaims(claims, 1)); + + private final AccountJwtJwksTrustedSource publicJwks; + private final SourceIdentity publicSourcePin; + private final AccountPublicJwksCache publicJwksCache; + private final AccountJwtSignerDesiredStateRepository signerStates; + private final AccountJwtSignerMaterializerTrustBinding materializerTrust; + private final AccountJwtJwksApiBinding jwksApiBinding; + private final AccountControlUiRegistryReader registry; + private final AccountControlUiCommittedIssuanceRepository issuances; + private final AccountAuthoritySourceEvidenceRepository sourceEvidence; + private final AccountAuthorityGenerationRepository generations; + private final AccountTenantAuthorityEventRepository tenantEvents; + private final AccountTenantMembershipRepository memberships; + private final AccountMembershipPairAuthorityRepository membershipPairs; + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots; + private final AccountAuthorityOutboxRepository outbox; + private final TransactionTemplate accountTransaction; + private final Clock clock; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected Account repositories are shared owner services; they must retain their transaction and current-state identity rather than be copied.") + public AccountControlUiCurrentActorVerifier( + AccountJwtJwksTrustedSource publicJwks, + AccountJwtSignerDesiredStateRepository signerStates, + AccountJwtSignerMaterializerTrustBinding materializerTrust, + AccountJwtJwksApiBinding jwksApiBinding, + AccountControlUiRegistryReader registry, + AccountControlUiCommittedIssuanceRepository issuances, + AccountAuthoritySourceEvidenceRepository sourceEvidence, + AccountAuthorityGenerationRepository generations, + AccountTenantAuthorityEventRepository tenantEvents, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository membershipPairs, + AccountTenantMembershipRoleSnapshotRepository roleSnapshots, + AccountAuthorityOutboxRepository outbox, + PlatformTransactionManager transactionManager, + Clock clock) { + this.publicJwks = Objects.requireNonNull(publicJwks); + this.signerStates = Objects.requireNonNull(signerStates); + this.materializerTrust = Objects.requireNonNull(materializerTrust); + this.jwksApiBinding = Objects.requireNonNull(jwksApiBinding); + this.registry = Objects.requireNonNull(registry); + this.issuances = Objects.requireNonNull(issuances); + this.sourceEvidence = Objects.requireNonNull(sourceEvidence); + this.generations = Objects.requireNonNull(generations); + this.tenantEvents = Objects.requireNonNull(tenantEvents); + this.memberships = Objects.requireNonNull(memberships); + this.membershipPairs = Objects.requireNonNull(membershipPairs); + this.roleSnapshots = Objects.requireNonNull(roleSnapshots); + this.outbox = Objects.requireNonNull(outbox); + this.clock = Objects.requireNonNull(clock); + this.publicSourcePin = this.publicJwks.sourceIdentity(); + this.publicJwksCache = + new AccountPublicJwksCache( + this.publicJwks, publicSourcePin, this.clock, Duration.ofSeconds(30)); + accountTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + accountTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + accountTransaction.setReadOnly(false); + } + + /** Verifies one signed actor for its selected canonical tenant; no authorization is returned. */ + public CurrentActor verify(String compactJwt, UUID selectedTenant) { + outsideSql(); + requireTenant(selectedTenant); + byte[] compactBytes = compactBytes(compactJwt); + VerifiedClaims signed = + new AccountAsymmetricJwtVerifier(publicJwksCache, clock).verify(compactJwt, POLICY); + PublicJwksSnapshot currentJwks = publicJwks.load(); + String tokenHash = sha256(compactBytes); + byte[] activeRegistry = registry.readActive(tokenHash); + + CurrentActor result = + accountTransaction.execute( + ignored -> + verifyOwnerState( + tokenHash, + selectedTenant, + signed, + publicSourcePin, + currentJwks, + activeRegistry)); + if (result == null) { + throw denied(); + } + return result; + } + + private CurrentActor verifyOwnerState( + String tokenHash, + UUID selectedTenant, + VerifiedClaims signed, + SourceIdentity pin, + PublicJwksSnapshot currentJwks, + byte[] activeRegistry) { + Map claims = signed.claims(); + UUID accountId = uuid(claims.get("accountId")); + UUID tokenTenant = selectedScopedTenant(claims, selectedTenant); + if (!selectedTenant.equals(tokenTenant) || claims.containsKey("globalRoles")) { + throw denied(); + } + CommittedIssuance issuance = + issuances + .readCommitted(tokenHash) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + Map registryRecord = + AccountControlUiRegistryReader.parseActiveRecord(activeRegistry, tokenHash); + if (!ISSUER.equals(claims.get("iss")) + || !claims.get("sub").equals(accountId.toString()) + || !issuance.tokenHash().equals(tokenHash) + || !issuance.accountId().equals(accountId) + || !issuance.tenantId().equals(selectedTenant) + || !issuance.tokenJti().equals(uuid(claims.get("jti"))) + || !issuance.requestId().equals(uuid(registryRecord.get("requestId"))) + || !issuance.operationId().equals(uuid(registryRecord.get("operationId"))) + || !Arrays.equals(activeRegistry, issuance.activeRegistry()) + || !Arrays.equals(canonicalBytes(claims), issuance.claims()) + || !signed.keyId().equals(registryRecord.get("kid")) + || !accountId.toString().equals(registryRecord.get("accountId")) + || !claims.get("jti").equals(registryRecord.get("jti")) + || !canonicalMapEquals(registryRecord.get("authorityTuple"), claims.get("authorityTuple")) + || !canonicalMapEquals( + registryRecord.get("membershipVersion"), claims.get("membershipVersion")) + || !numericEquals( + registryRecord.get("tokenGeneration"), positiveLong(claims.get("tokenGeneration"))) + || !numericEquals( + registryRecord.get("issuanceFence"), positiveLong(claims.get("issuanceFence"))) + || !numericEquals(claims.get("iat"), issuance.issuedAtEpochSecond()) + || !numericEquals(claims.get("nbf"), issuance.issuedAtEpochSecond()) + || !numericEquals(claims.get("exp"), issuance.expiresAtEpochSecond()) + || !numericEquals(registryRecord.get("iat"), issuance.issuedAtEpochSecond()) + || !numericEquals(registryRecord.get("nbf"), issuance.issuedAtEpochSecond()) + || !numericEquals(registryRecord.get("exp"), issuance.expiresAtEpochSecond()) + || !numericEquals( + registryRecord.get("registryCleanupDeadlineEpochMillis"), issuance.expiryMillis()) + || !Arrays.equals(issuance.pendingRegistry(), derivePendingRegistry(activeRegistry))) { + throw denied(); + } + requireBundle(issuance, claims, registryRecord); + requirePendingReceipt(issuance); + requireSignerReceipt(issuance, signed.keyId(), pin, currentJwks); + return requireCurrentAccountAuthority(issuance, claims, selectedTenant, tokenHash); + } + + private void requireBundle( + CommittedIssuance issuance, Map claims, Map registryRecord) { + Map storedClaims = parseCanonicalObject(issuance.claims(), 16384); + Map bundle = parseCanonicalObject(issuance.bundle(), MAX_BUNDLE_BYTES); + Map bundleRef = object(bundle.get("bundleRef")); + Map scope = object(bundle.get("scope")); + Map operation = object(bundle.get("operation")); + Map tokenIdentity = object(bundle.get("tokenIdentity")); + Map roleEvidence = object(bundle.get("roleEvidence")); + if (!bundle.keySet().equals(BUNDLE_FIELDS) + || !bundleRef + .keySet() + .equals(Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization")) + || !scope.keySet().equals(Set.of("kind", "accountId", "tenantIds")) + || !operation + .keySet() + .equals( + Set.of( + "operationId", + "requestId", + "requestDigest", + "callerWorkload", + "callerContextId", + "accountId")) + || !tokenIdentity.keySet().equals(Set.of("jti", "tokenGeneration", "iat", "nbf", "exp")) + || !roleEvidence.keySet().equals(Set.of("scopedRoles", "freshnessSource")) + || !Arrays.equals(canonicalBytes(claims), canonicalBytes(storedClaims)) + || !"account-auth-evidence-bundle/v1".equals(bundle.get("schema")) + || !ISSUER.equals(bundle.get("issuer")) + || !"control-ui".equals(bundle.get("profile")) + || !"control-ui".equals(bundle.get("audience")) + || !issuance.operationId().toString().equals(operation.get("operationId")) + || !issuance.requestId().toString().equals(operation.get("requestId")) + || !issuance.requestDigest().equals(operation.get("requestDigest")) + || !issuance.accountId().toString().equals(operation.get("accountId")) + || !issuance.callerWorkload().equals(operation.get("callerWorkload")) + || !issuance.callerContextId().toString().equals(operation.get("callerContextId")) + || !issuance.accountId().toString().equals(scope.get("accountId")) + || !List.of(issuance.tenantId().toString()).equals(scope.get("tenantIds")) + || !"TENANT".equals(scope.get("kind")) + || !canonicalMapEquals(bundle.get("authorityTuple"), claims.get("authorityTuple")) + || !canonicalMapEquals(bundle.get("membershipVersion"), claims.get("membershipVersion")) + || !numericEquals(bundle.get("issuanceFence"), positiveLong(claims.get("issuanceFence"))) + || !canonicalMapEquals( + bundle.get("authoritySourceVersions"), registryRecord.get("authoritySourceVersions")) + || !canonicalMapEquals(tokenIdentity, tokenIdentity(claims)) + || !canonicalMapEquals(roleEvidence.get("scopedRoles"), claims.get("scopedRoles"))) { + throw denied(); + } + parseCanonicalObject(issuance.source(), 131072); + String sourceIdentity = sha256(issuance.source()); + if (!sourceIdentity.equals(bundle.get("snapshotIdentity")) + || !sourceIdentity.equals(roleEvidence.get("freshnessSource"))) { + throw denied(); + } + Map expectedReference = new LinkedHashMap<>(bundleRef); + expectedReference.put("canonicalSha256", sha256(issuance.bundle())); + if (!canonicalMapEquals(expectedReference, registryRecord.get("authEvidenceBundle"))) { + throw denied(); + } + Map evaluation = + Map.of( + "operation", operation, + "claims", claims, + "bundleRef", bundleRef, + "snapshotIdentity", sourceIdentity); + if (!sha256(canonicalBytes(evaluation)).equals(bundle.get("evaluationIdentity"))) { + throw denied(); + } + } + + private void requirePendingReceipt(CommittedIssuance issuance) { + Map receipt = parseCanonicalObject(issuance.pendingReceipt(), 8192); + if (!receipt.keySet().equals(PENDING_RECEIPT_FIELDS) + || !"account-control-ui-pending-readback/v1".equals(receipt.get("schema")) + || !issuance.tokenHash().equals(receipt.get("tokenHash")) + || !sha256(issuance.pendingRegistry()).equals(receipt.get("recordDigest")) + || !"account_coord_app".equals(receipt.get("aclIdentity")) + || !numericEquals(receipt.get("expiryMillis"), issuance.expiryMillis()) + || !atLeastOne(receipt.get("localAofCount")) + || !atLeastOne(receipt.get("replicaAofCount"))) { + throw denied(); + } + } + + private void requireSignerReceipt( + CommittedIssuance issuance, + String verifiedKid, + SourceIdentity pin, + PublicJwksSnapshot currentJwks) { + Map receipt = parseCanonicalObject(issuance.signerReceipt(), 65536); + Optional fingerprint = + AccountJwtJwksTrustedSource.publicKeyFingerprint(currentJwks, pin, verifiedKid); + Map registryRecord = + AccountControlUiRegistryReader.parseActiveRecord( + issuance.activeRegistry(), issuance.tokenHash()); + if (!receipt.keySet().equals(SIGNER_RECEIPT_FIELDS) + || !"account-control-ui-committed-signer/v1".equals(receipt.get("schema")) + || !pin.environmentId().equals(receipt.get("environmentId")) + || !pin.clusterId().equals(receipt.get("clusterId")) + || !pin.clusterIncarnationUid().equals(receipt.get("clusterIncarnationUid")) + || !pin.namespace().equals(receipt.get("namespace")) + || !pin.namespaceUid().equals(receipt.get("namespaceUid")) + || !pin.configMapUid().equals(receipt.get("publicConfigMapUid")) + || !pin.bindingRevision().equals(receipt.get("apiConfigRevision")) + || !verifiedKid.equals(receipt.get("kid")) + || !verifiedKid.equals(registryRecord.get("kid")) + || !"RS256".equals(receipt.get("algorithm")) + || !fingerprint.orElse("").equals(receipt.get("publicKeyFingerprint")) + || !registryRecord.get("signerGeneration").equals(receipt.get("signerGeneration")) + || !issuance.operationId().toString().equals(registryRecord.get("operationId")) + || !issuance.requestId().toString().equals(registryRecord.get("requestId")) + || !issuance.requestDigest().equals(registryRecord.get("requestDigest")) + || !sha256(issuance.signerReceipt()) + .equals(registryRecord.get("originalSignerReceiptDigest")) + || !DIGEST.matcher(text(receipt.get("trustBindingDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("apiBindingDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("promotionRequestDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("privateReceiptDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicReceiptDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicDataDigest"))).matches() + || !DIGEST.matcher(text(receipt.get("publicKeyFingerprint"))).matches()) { + throw denied(); + } + requireOriginalCommittedSigner(receipt, verifiedKid); + } + + private void requireOriginalCommittedSigner(Map receipt, String verifiedKid) { + var materializer = + materializerTrust.current().orElseThrow(AccountControlUiCurrentActorVerifier::denied); + var api = jwksApiBinding.current(); + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid()) + || !text(receipt.get("apiBindingDigest")).equals(api.bindingDigest()) + || !text(receipt.get("apiConfigRevision")).equals(api.configRevision()) + || !text(receipt.get("trustBindingDigest")).equals(materializer.bindingDigest()) + || !text(receipt.get("trustConfigRevision")).equals(materializer.configRevision())) { + throw denied(); + } + Binding binding = + new Binding( + materializer.environmentId(), + materializer.clusterId(), + materializer.namespace(), + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + TrustFence trust = + new TrustFence( + materializer.expectedClusterIncarnationUid(), + materializer.expectedNamespaceUid(), + materializer.bindingDigest(), + materializer.configRevision()); + var original = + signerStates + .readOriginalCommittedSigner( + binding, + trust, + api.bindingDigest(), + api.configRevision(), + uuid(receipt.get("promotionOperationId")), + uuid(receipt.get("generationOperationId"))) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + var promotion = original.promotion(); + var generation = original.generationResult(); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.operationId().toString().equals(receipt.get("promotionOperationId")) + || !promotion.requestDigest().equals(receipt.get("promotionRequestDigest")) + || !generation.operationId().toString().equals(receipt.get("generationOperationId")) + || !verifiedKid.equals(generation.targetKid()) + || !generation.targetGeneration().equals(receipt.get("signerGeneration")) + || !"RS256".equals(generation.targetAlgorithm()) + || !generation.publicKeyFingerprint().equals(receipt.get("publicKeyFingerprint")) + || !original.privateReceipt().receiptDigest().equals(receipt.get("privateReceiptDigest")) + || !original + .privateReceipt() + .observedResourceVersion() + .equals(receipt.get("privateResourceVersion")) + || !original.publicReceipt().receiptDigest().equals(receipt.get("publicReceiptDigest")) + || !original + .publicReceipt() + .observedResourceVersion() + .equals(receipt.get("publicResourceVersion")) + || !original.publicReceipt().configMapUid().equals(receipt.get("publicConfigMapUid")) + || !original.publicReceipt().publicDataDigest().equals(receipt.get("publicDataDigest"))) { + throw denied(); + } + } + + private CurrentActor requireCurrentAccountAuthority( + CommittedIssuance issuance, Map claims, UUID tenantId, String tokenHash) { + UUID accountId = issuance.accountId(); + IssuerAccountSourceSnapshot source = + sourceEvidence.readCurrentIssuerAccountSources(ISSUER, accountId); + CompositeSnapshot snapshot = + generations.readCompositeSnapshot(ISSUER, accountId, List.of(tenantId), List.of(tenantId)); + if (source.issuer().generation() != snapshot.issuer().generation() + || source.issuer().sourceVersion() != snapshot.issuer().sourceVersion() + || source.account().generation() != snapshot.account().generation() + || source.account().sourceVersion() != snapshot.account().sourceVersion() + || !source.issuanceFence().equals(snapshot.issuanceFence())) { + throw denied(); + } + var tenantState = only(snapshot.tenants(), "tenant authority"); + var membershipState = only(snapshot.memberships(), "membership authority"); + Event currentTenant = tenantEvents.readCurrentByTenant(tenantId); + if (!tenantId.equals(currentTenant.tenantId()) + || currentTenant.tenantAuthorityGeneration() != tenantState.generation() + || currentTenant.tenantAuthoritySourceVersion() != tenantState.sourceVersion()) { + throw denied(); + } + + PairAuthority pair = + membershipPairs + .readPositive(accountId, tenantId) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + AccountTenantMembership membership = + memberships + .findFreshMembership(accountId, tenantId) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + if (!pair.membershipExists() + || pair.eventSequence() <= 0L + || pair.lastTransitionInvalidated() + || membership.getId() == null + || membership.getAccount() == null + || membership.getAccount().getId() == null + || !accountId.equals(membership.getAccount().getAccountUuid()) + || !tenantId.equals(membership.getTenantUuid()) + || !"ACTIVE".equals(membership.getLifecycleState()) + || membership.getMembershipVersion() != pair.membershipVersion() + || membership.getMembershipAuthorityGeneration() != pair.membershipAuthorityGeneration() + || pair.membershipAuthorityGeneration() != membershipState.generation()) { + throw denied(); + } + MembershipEvent currentMembershipEvent = + requireCurrentMembershipEvent(accountId, tenantId, pair, membershipState.generation()); + RoleSnapshot roles = + roleSnapshots + .findForCanonicalUpdate( + accountId, + tenantId, + pair.provenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + if (!roles.roles().equals(currentMembershipEvent.roles())) { + throw denied(); + } + requireClaimsCurrent( + claims, accountId, tenantId, source, snapshot, currentTenant, pair, membership, roles); + return new CurrentActor( + accountId, + tenantId, + issuance.operationId(), + tokenHash, + roles.roles(), + snapshot.issuer().generation(), + snapshot.account().generation(), + tenantState.generation(), + membershipState.generation(), + membership.getMembershipVersion(), + snapshot.issuanceFence().value()); + } + + private MembershipEvent requireCurrentMembershipEvent( + UUID accountId, UUID tenantId, PairAuthority pair, long membershipGeneration) { + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + accountId + + "/" + + tenantId; + var stored = + outbox + .findEvent(streamKey, pair.eventSequence()) + .orElseThrow(AccountControlUiCurrentActorVerifier::denied); + MembershipEvent event = + MembershipAuthorityEventV1Codec.verify( + new String(stored.payload(), StandardCharsets.UTF_8)); + if (!stored.outboxStreamKey().equals(streamKey) + || !stored.eventId().equals(event.eventId()) + || !stored.eventDigest().equals(event.eventDigest()) + || !Long.toString(stored.outboxSequence()).equals(event.outboxSequence()) + || !pair.eventId().equals(event.eventId()) + || !pair.eventDigest().equals(event.eventDigest()) + || !accountId.toString().equals(event.accountId()) + || !tenantId.toString().equals(event.tenantId()) + || !Long.toString(pair.membershipVersion()) + .equals(event.membershipVersion().get(tenantId.toString())) + || !Long.toString(membershipGeneration).equals(event.membershipAuthorityGeneration()) + || !"ACTIVE".equals(event.membershipLifecycleState()) + || event.callerBoundAuthorityInvalidated() != pair.lastTransitionInvalidated()) { + throw denied(); + } + return event; + } + + private void requireClaimsCurrent( + Map claims, + UUID accountId, + UUID tenantId, + IssuerAccountSourceSnapshot source, + CompositeSnapshot snapshot, + Event tenantEvent, + PairAuthority pair, + AccountTenantMembership membership, + RoleSnapshot roles) { + Map tuple = object(claims.get("authorityTuple")); + Map tenantGenerations = + Map.of(tenantId.toString(), only(snapshot.tenants(), "tenant").generation()); + Map membershipGenerations = + Map.of(tenantId.toString(), pair.membershipAuthorityGeneration()); + Map membershipVersions = Map.of(tenantId.toString(), pair.membershipVersion()); + Map expectedTuple = new LinkedHashMap<>(); + expectedTuple.put("issuerAuthGeneration", snapshot.issuer().generation()); + expectedTuple.put("accountAuthorityGeneration", snapshot.account().generation()); + expectedTuple.put("tenantAuthorityGeneration", tenantGenerations); + expectedTuple.put("membershipAuthorityGeneration", membershipGenerations); + expectedTuple.put("privateRealmGrantVersions", List.of()); + source + .account() + .accountSecurityCutoff() + .ifPresent( + cutoff -> + expectedTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + Long.parseLong(cutoff.accountAuthorityGeneration()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + Long.parseLong(cutoff.outboxSequence())))); + if (tenantEvent.tenantBillingSequence() > 0L) { + expectedTuple.put( + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + tenantEvent.tenantAuthorityGeneration(), + "tenantBillingSequence", + tenantEvent.tenantBillingSequence(), + "outboxStreamKey", + tenantEvent.outboxStreamKey(), + "outboxSequence", + tenantEvent.outboxSequence()))); + } + Map scoped = object(claims.get("scopedRoles")); + if (!numericEquals(tuple.get("issuerAuthGeneration"), snapshot.issuer().generation()) + || !numericEquals(tuple.get("accountAuthorityGeneration"), snapshot.account().generation()) + || !canonicalMapEquals(tuple.get("tenantAuthorityGeneration"), tenantGenerations) + || !canonicalMapEquals(tuple.get("membershipAuthorityGeneration"), membershipGenerations) + || !canonicalMapEquals(tuple, expectedTuple) + || !canonicalMapEquals(claims.get("membershipVersion"), membershipVersions) + || !numericEquals(claims.get("issuanceFence"), snapshot.issuanceFence().value()) + || !canonicalMapEquals(scoped, Map.of(tenantId.toString(), roles.roles())) + || membership.getMembershipVersion() != pair.membershipVersion() + || !accountId.equals(membership.getAccount().getAccountUuid())) { + throw denied(); + } + } + + private static byte[] derivePendingRegistry(byte[] activeBytes) { + Map active = + parseCanonicalObject(activeBytes, AccountControlUiRegistryReader.MAX_RECORD_BYTES); + if (!"active".equals(active.get("state")) + || !Integer.valueOf(2).equals(number(active.get("registryVersion")))) { + throw denied(); + } + Map pending = new LinkedHashMap<>(active); + pending.put("state", "pending"); + pending.put("registryVersion", 1); + return canonicalBytes(pending); + } + + private static Map tokenIdentity(Map claims) { + Map identity = new LinkedHashMap<>(); + identity.put("jti", claims.get("jti")); + identity.put("tokenGeneration", claims.get("tokenGeneration")); + identity.put("iat", claims.get("iat")); + identity.put("nbf", claims.get("nbf")); + identity.put("exp", claims.get("exp")); + return identity; + } + + private static UUID selectedScopedTenant(Map claims, UUID selectedTenant) { + Map roles = object(claims.get("scopedRoles")); + if (!roles.keySet().equals(Set.of(selectedTenant.toString()))) { + throw denied(); + } + return selectedTenant; + } + + private static AccountAuthorityGenerationRepository.ScopeState only( + List states, String label) { + if (states == null || states.size() != 1) { + throw denied(); + } + return states.getFirst(); + } + + private static Map parseCanonicalObject(byte[] bytes, int maximum) { + if (bytes == null || bytes.length == 0 || bytes.length > maximum) { + throw denied(); + } + try { + String json = + StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString(); + if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw denied(); + } + Map fields = JSON.readValue(bytes, OBJECT); + if (fields == null) { + throw denied(); + } + return Map.copyOf(fields); + } catch (IOException | RuntimeException malformed) { + throw denied(); + } + } + + private static Map object(Object value) { + if (!(value instanceof Map map)) { + throw denied(); + } + Map result = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String text)) { + throw denied(); + } + result.put(text, item); + }); + return result; + } + + private static boolean canonicalMapEquals(Object first, Object second) { + return Arrays.equals(canonicalBytes(first), canonicalBytes(second)); + } + + private static byte[] canonicalBytes(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException | RuntimeException failure) { + throw denied(); + } + } + + private static boolean numericEquals(Object actual, long expected) { + return actual instanceof Number number && number.toString().equals(Long.toString(expected)); + } + + private static Number number(Object value) { + return value instanceof Number number ? number : null; + } + + private static long positiveLong(Object value) { + if (!(value instanceof Number number)) { + throw denied(); + } + try { + long parsed = Long.parseLong(number.toString()); + if (parsed <= 0L) { + throw denied(); + } + return parsed; + } catch (NumberFormatException malformed) { + throw denied(); + } + } + + private static boolean atLeastOne(Object value) { + return value instanceof Number number + && number.toString().matches("[1-9][0-9]{0,2}") + && number.longValue() >= 1L; + } + + private static UUID uuid(Object value) { + if (!(value instanceof String text)) { + throw denied(); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw denied(); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw denied(); + } + } + + private static String text(Object value) { + return value instanceof String text ? text : ""; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException unavailable) { + throw denied(); + } + } + + private static byte[] compactBytes(String compactJwt) { + if (compactJwt == null + || compactJwt.isBlank() + || compactJwt.length() > 16384 + || compactJwt.codePoints().anyMatch(codePoint -> codePoint > 0x7f)) { + throw denied(); + } + return compactJwt.getBytes(StandardCharsets.US_ASCII); + } + + private static void requireTenant(UUID tenant) { + if (tenant == null + || tenant.getMostSignificantBits() == 0L && tenant.getLeastSignificantBits() == 0L) { + throw denied(); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account JWT and Coordination reads must precede SQL ownership"); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Current Account control-ui actor evidence unavailable"); + } + + /** + * Identity and current source tuple only. It is not a route authorization or a reference grant. + */ + public record CurrentActor( + UUID accountId, + UUID tenantId, + UUID issuanceOperationId, + String tokenHash, + List currentTenantRoles, + long issuerGeneration, + long accountGeneration, + long tenantGeneration, + long membershipGeneration, + long membershipVersion, + long issuanceFence) { + public CurrentActor { + Objects.requireNonNull(accountId); + Objects.requireNonNull(tenantId); + Objects.requireNonNull(issuanceOperationId); + if (tokenHash == null || !DIGEST.matcher(tokenHash).matches()) { + throw new IllegalArgumentException("Control-ui actor token identity is invalid"); + } + currentTenantRoles = List.copyOf(currentTenantRoles); + if (issuerGeneration <= 0L + || accountGeneration <= 0L + || tenantGeneration <= 0L + || membershipGeneration <= 0L + || membershipVersion <= 0L + || issuanceFence <= 0L) { + throw new IllegalArgumentException("Control-ui current authority values must be positive"); + } + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java new file mode 100644 index 0000000000..ad87e06a8c --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java @@ -0,0 +1,617 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl.ControlUiPrimaryIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Genuine durable control-ui owner state. No caller-provided registry or evidence is accepted. */ +public final class AccountControlUiIssuanceRepository { + private static final String TABLE = "account_control_ui_issuance_operations"; + static final long MAX_REDIS_SAFE_INTEGER = 9_007_199_254_740_991L; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Pattern TRANSACTION_ID = Pattern.compile("[1-9][0-9]{0,19}"); + private final DSLContext dsl; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Account transaction collaborator.") + public AccountControlUiIssuanceRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + Stored findRequest(UUID requestId) { + requireTransaction(); + Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ?", requestId); + return row == null ? null : new Stored(row); + } + + Stored findToken(String tokenHash) { + requireTransaction(); + Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE token_hash = ?", tokenHash); + return row == null ? null : new Stored(row); + } + + Stored findTokenJti(UUID tokenJti) { + requireTransaction(); + Objects.requireNonNull(tokenJti, "control-ui token jti is required"); + Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE token_jti = ?", tokenJti); + return row == null ? null : new Stored(row); + } + + /** Account-owned linearization from the caller's existing current-source transaction. */ + public OwnerLinearization captureOwnerLinearization() { + requireTransaction(); + Record row = + dsl.fetchOne( + "SELECT pg_current_xact_id()::TEXT AS xid, " + + "nextval('account_control_ui_source_fence') AS fence"); + String transactionId = row == null ? null : row.get("xid", String.class); + Long sourceFence = row == null ? null : row.get("fence", Long.class); + if (transactionId == null + || !TRANSACTION_ID.matcher(transactionId).matches() + || sourceFence == null + || sourceFence <= 0L) { + throw denied(); + } + return new OwnerLinearization(transactionId, sourceFence); + } + + Stored prepare( + UUID requestId, + String caller, + UUID callerContextId, + String macKeyId, + String digest, + ControlUiPrimaryIdentity authenticated, + AccountControlUiAuthority.Snapshot source, + AccountControlUiSignerOwner.Capture signer, + Instant issuedAt, + long sessionSafetyMarginMillis) { + requireTransaction(); + if (!authenticated.accountId().equals(source.actor())) { + throw denied(); + } + UUID operationId = UUID.randomUUID(); + UUID jti = UUID.randomUUID(); + Instant expiry = issuedAt.plusSeconds(300); + long cleanupDeadlineMillis = + checkedCleanupDeadlineMillis(expiry.toEpochMilli(), sessionSafetyMarginMillis); + Instant recovery = issuedAt.plusSeconds(60); + var spec = + new AccountControlUiSigningSpec(operationId, requestId, jti, source, issuedAt, expiry); + OwnerLinearization linearization = captureOwnerLinearization(); + String xid = linearization.transactionId(); + long fence = linearization.sourceFence(); + Map ref = + Map.of( + "bundleVersion", + "1", + "sourceVersion", + xid, + "sourceFence", + Long.toString(fence), + "linearization", + xid); + Map operation = + Map.of( + "operationId", + operationId.toString(), + "requestId", + requestId.toString(), + "requestDigest", + digest, + "callerWorkload", + caller, + "callerContextId", + callerContextId.toString(), + "accountId", + source.actor().toString()); + var bundle = new LinkedHashMap(); + bundle.put("schema", "account-auth-evidence-bundle/v1"); + bundle.put("bundleRef", ref); + bundle.put("snapshotIdentity", hash(source.evidence())); + bundle.put( + "evaluationIdentity", + hash( + AccountControlUiAuthority.canonical( + Map.of( + "operation", + operation, + "claims", + spec.claims(), + "bundleRef", + ref, + "snapshotIdentity", + hash(source.evidence()))))); + bundle.put("issuer", "firemud-account-service"); + bundle.put("profile", "control-ui"); + bundle.put("audience", "control-ui"); + bundle.put( + "scope", + Map.of( + "kind", + "TENANT", + "accountId", + source.actor().toString(), + "tenantIds", + java.util.List.of(source.tenant().toString()))); + bundle.put("operation", operation); + bundle.put( + "tokenIdentity", + Map.of( + "jti", + jti.toString(), + "tokenGeneration", + 1, + "iat", + issuedAt.getEpochSecond(), + "nbf", + issuedAt.getEpochSecond(), + "exp", + expiry.getEpochSecond())); + bundle.put("authorityTuple", source.authorityTuple()); + bundle.put("membershipVersion", source.membershipVersion()); + bundle.put("issuanceFence", source.issuanceFence()); + Map versions = new LinkedHashMap<>(); + source.sources().forEach(value -> versions.put(value.key(), value.sourceVersion())); + bundle.put("authoritySourceVersions", Map.copyOf(versions)); + bundle.put("accountIdentitySource", source.accountIdentitySource()); + bundle.put("outboxCheckpoints", source.outboxCheckpoints()); + bundle.put( + "roleEvidence", + Map.of( + "scopedRoles", + spec.claims().get("scopedRoles"), + "freshnessSource", + hash(source.evidence()))); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload," + + " caller_context_id, request_mac_key_id, request_digest, claims_payload, source_payload," + + " bundle_payload, signer_receipt, issued_at_epoch_second, expires_at_epoch_second," + + " registry_cleanup_deadline_epoch_millis, recovery_expires_at, status)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')" + + " ON CONFLICT (request_id) DO NOTHING", + requestId, + operationId, + jti, + source.actor(), + source.tenant(), + caller, + callerContextId, + macKeyId, + digest, + AccountControlUiAuthority.canonical(spec.claims()), + source.evidence(), + AccountControlUiAuthority.canonical(bundle), + signer.receipt(), + issuedAt.getEpochSecond(), + expiry.getEpochSecond(), + cleanupDeadlineMillis, + OffsetDateTime.ofInstant(recovery, java.time.ZoneOffset.UTC)); + Stored stored = findRequest(requestId); + if (inserted != 1 || stored == null || !operationId.equals(stored.operationId)) { + throw denied(); + } + // The complete fixed-width digest field permits both final registry sizes to be checked now, + // before any private signing or Coordination mutation. No placeholder is retained as evidence. + registry(stored, signer, "0".repeat(64), false); + registry(stored, signer, "0".repeat(64), true); + return stored; + } + + Stored bindCandidate( + Stored original, + String tokenHash, + byte[] envelope, + byte[] binding, + AccountControlUiSignerOwner.Capture signer) { + requireTransaction(); + Stored current = lockExact(original); + if (!Arrays.equals(current.signerReceipt, signer.receipt()) + || !"PREPARED".equals(current.status)) { + throw denied(); + } + byte[] pending = registry(current, signer, tokenHash, false); + byte[] active = registry(current, signer, tokenHash, true); + dsl.execute( + "INSERT INTO account_control_ui_response_envelopes" + + " (operation_id, encrypted_response, owner_binding, recovery_expires_at) VALUES (?, ?, ?, ?::timestamptz)", + current.operationId, + envelope, + binding, + OffsetDateTime.ofInstant(current.recoveryExpiry, java.time.ZoneOffset.UTC)); + if (dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'CANDIDATE', token_hash = ?, pending_registry = ?, active_registry = ?" + + " WHERE operation_id = ? AND status = 'PREPARED'", + tokenHash, + pending, + active, + current.operationId) + != 1) { + throw denied(); + } + return findRequest(current.requestId); + } + + Committed commit(Stored original, AccountControlUiCoordination.Receipt pending) { + requireTransaction(); + Stored current = lockExact(original); + if (!Objects.equals(current.tokenHash, pending.tokenHash) + || !hash(current.pendingRegistry).equals(pending.recordDigest) + || current.expiryMillis() != pending.expiryMillis + || !"CANDIDATE".equals(current.status)) { + throw denied(); + } + byte[] receipt = + AccountControlUiAuthority.canonical( + Map.of( + "schema", + "account-control-ui-pending-readback/v1", + "tokenHash", + pending.tokenHash, + "recordDigest", + pending.recordDigest, + "expiryMillis", + pending.expiryMillis, + "aclIdentity", + "account_coord_app", + "localAofCount", + pending.localAof, + "replicaAofCount", + pending.replicas)); + if (dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'COMMITTED', pending_receipt = ?, committed_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND status = 'CANDIDATE'", + receipt, + current.operationId) + != 1) { + throw denied(); + } + return requireCommitted(findRequest(current.requestId)); + } + + Committed requireCommitted(Stored original) { + Stored current = lockExact(original); + if (!"COMMITTED".equals(current.status)) { + throw denied(); + } + return new Committed(current); + } + + /** Durable non-authorizing intent precedes any external revocation; no source recapture. */ + Stored beginRecoveryFailure(Stored original) { + Stored current = lockExact(original); + if (java.util.List.of("FAILED", "REVOKING", "REVOKED").contains(current.status)) { + return current; + } + String next = current.tokenHash == null ? "FAILED" : "REVOKING"; + if (dsl.execute( + "UPDATE " + + TABLE + + " SET status = ?, recovery_failed_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND status = ?", + next, + current.operationId, + current.status) + != 1) { + throw denied(); + } + return findRequest(current.requestId); + } + + void finishRecoveryFailure(Stored original, AccountControlUiCoordination.Receipt receipt) { + Stored current = lockExact(original); + if (!"REVOKING".equals(current.status) + || !Objects.equals(current.tokenHash, receipt.tokenHash) + || !hash(revokedRegistry(current)).equals(receipt.recordDigest) + || current.expiryMillis() != receipt.expiryMillis) { + throw denied(); + } + byte[] evidence = + AccountControlUiAuthority.canonical( + Map.of( + "schema", + "account-control-ui-revoked-readback/v1", + "tokenHash", + receipt.tokenHash, + "recordDigest", + receipt.recordDigest, + "expiryMillis", + receipt.expiryMillis, + "aclIdentity", + "account_coord_app", + "localAofCount", + receipt.localAof, + "replicaAofCount", + receipt.replicas)); + if (dsl.execute( + "UPDATE " + + TABLE + + " SET status = 'REVOKED', revocation_receipt = ?" + + " WHERE operation_id = ? AND status = 'REVOKING'", + evidence, + current.operationId) + != 1) { + throw denied(); + } + } + + static byte[] revokedRegistry(Stored original) { + if (!"REVOKING".equals(original.status)) { + throw denied(); + } + var record = new LinkedHashMap(object(original.pendingRegistry)); + record.put("state", "revoked"); + record.put("registryVersion", 3); + return AccountControlUiAuthority.canonical(record); + } + + Envelope envelope(Stored original) { + requireTransaction(); + Record value = + dsl.fetchOne( + "SELECT encrypted_response, owner_binding, recovery_expires_at" + + " FROM account_control_ui_response_envelopes WHERE operation_id = ?", + original.operationId); + if (value == null) { + return null; + } + if (!value + .get("recovery_expires_at", OffsetDateTime.class) + .toInstant() + .equals(original.recoveryExpiry)) { + return null; + } + return new Envelope( + value.get("encrypted_response", byte[].class), value.get("owner_binding", byte[].class)); + } + + private Stored lockExact(Stored original) { + requireTransaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE operation_id = ? FOR UPDATE", original.operationId); + if (row == null) { + throw denied(); + } + Stored current = new Stored(row); + if (!original.requestId.equals(current.requestId) + || !Arrays.equals(original.claims, current.claims) + || !Arrays.equals(original.sources, current.sources) + || !Arrays.equals(original.bundle, current.bundle) + || !Arrays.equals(original.signerReceipt, current.signerReceipt) + || !original.requestDigest.equals(current.requestDigest)) { + throw denied(); + } + return current; + } + + private static byte[] registry( + Stored value, AccountControlUiSignerOwner.Capture signer, String tokenHash, boolean active) { + var claims = object(value.claims); + var bundle = object(value.bundle); + var result = new LinkedHashMap(); + result.put("schemaVersion", 1); + result.put("registryVersion", active ? 2 : 1); + result.put("tokenHash", tokenHash); + result.put("kid", signer.kid()); + result.put("signerGeneration", signer.generation()); + result.put("issuer", "firemud-account-service"); + result.put("profile", "control-ui"); + result.put("type", "control-ui"); + result.put("audience", "control-ui"); + for (String field : + java.util.List.of( + "accountId", + "jti", + "iat", + "nbf", + "exp", + "tokenGeneration", + "authorityTuple", + "membershipVersion", + "issuanceFence")) { + result.put(field, claims.get(field)); + } + result.put("operationId", value.operationId.toString()); + result.put("requestId", value.requestId.toString()); + result.put("requestDigest", value.requestDigest); + result.put("state", active ? "active" : "pending"); + result.put("registryCleanupDeadlineEpochMillis", value.expiryMillis()); + result.put("authoritySourceVersions", bundle.get("authoritySourceVersions")); + var reference = new LinkedHashMap(); + @SuppressWarnings("unchecked") + var bundleRef = (Map) bundle.get("bundleRef"); + reference.putAll(bundleRef); + reference.put("canonicalSha256", hash(value.bundle)); + result.put("authEvidenceBundle", Map.copyOf(reference)); + result.put("originalSignerReceiptDigest", hash(value.signerReceipt)); + byte[] bytes = AccountControlUiAuthority.canonical(result); + if (bytes.length > 32768) { + throw denied(); + } + return bytes; + } + + static Map object(byte[] bytes) { + try { + return JSON.readValue(new String(bytes, StandardCharsets.UTF_8), new TypeReference<>() {}); + } catch (RuntimeException failure) { + throw denied(); + } + } + + static String hash(byte[] bytes) { + return AccountControlUiCoordination.digest("SHA-256", bytes); + } + + static long checkedCleanupDeadlineMillis(long tokenExpiryMillis, long marginMillis) { + if (tokenExpiryMillis <= 0L || marginMillis < 0L) { + throw denied(); + } + try { + long deadline = Math.addExact(tokenExpiryMillis, marginMillis); + if (deadline > MAX_REDIS_SAFE_INTEGER) { + throw denied(); + } + return deadline; + } catch (ArithmeticException malformed) { + throw denied(); + } + } + + private void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw denied(); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw denied(); + } + }); + } + + static final class Stored { + final UUID requestId, operationId, jti, accountId, tenantId, callerContextId; + final String caller, requestMacKeyId, requestDigest, status, tokenHash; + final byte[] claims, sources, bundle, signerReceipt, pendingRegistry, activeRegistry; + final Instant issuedAt, expiresAt, recoveryExpiry; + final Long registryCleanupDeadlineEpochMillis; + + Stored(Record row) { + requestId = row.get("request_id", UUID.class); + operationId = row.get("operation_id", UUID.class); + jti = row.get("token_jti", UUID.class); + accountId = row.get("account_uuid", UUID.class); + tenantId = row.get("tenant_uuid", UUID.class); + callerContextId = row.get("caller_context_id", UUID.class); + caller = row.get("caller_workload", String.class); + requestMacKeyId = row.get("request_mac_key_id", String.class); + requestDigest = row.get("request_digest", String.class); + status = row.get("status", String.class); + tokenHash = row.get("token_hash", String.class); + claims = row.get("claims_payload", byte[].class); + sources = row.get("source_payload", byte[].class); + bundle = row.get("bundle_payload", byte[].class); + signerReceipt = row.get("signer_receipt", byte[].class); + pendingRegistry = row.get("pending_registry", byte[].class); + activeRegistry = row.get("active_registry", byte[].class); + issuedAt = Instant.ofEpochSecond(row.get("issued_at_epoch_second", Long.class)); + expiresAt = Instant.ofEpochSecond(row.get("expires_at_epoch_second", Long.class)); + registryCleanupDeadlineEpochMillis = + row.get("registry_cleanup_deadline_epoch_millis", Long.class); + recoveryExpiry = row.get("recovery_expires_at", OffsetDateTime.class).toInstant(); + } + + long expiryMillis() { + Long deadline = registryCleanupDeadlineEpochMillis; + if (deadline == null || deadline > MAX_REDIS_SAFE_INTEGER) { + throw denied(); + } + try { + if (deadline < expiresAt.toEpochMilli()) { + throw denied(); + } + } catch (ArithmeticException malformed) { + throw denied(); + } + return deadline; + } + + @Override + public String toString() { + return "AccountControlUiIssuanceRepository.Stored[redacted]"; + } + } + + public record OwnerLinearization(String transactionId, long sourceFence) { + public OwnerLinearization { + if (transactionId == null + || !TRANSACTION_ID.matcher(transactionId).matches() + || sourceFence <= 0L) { + throw denied(); + } + } + } + + public static final class Committed { + final Stored stored; + + private Committed(Stored stored) { + this.stored = stored; + } + + public String tokenHash() { + return stored.tokenHash; + } + + public byte[] pendingRegistry() { + return stored.pendingRegistry.clone(); + } + + public byte[] activeRegistry() { + return stored.activeRegistry.clone(); + } + + public long expiryMillis() { + return stored.expiryMillis(); + } + + @Override + public String toString() { + return "AccountControlUiIssuanceRepository.Committed[redacted]"; + } + } + + record Envelope(byte[] encrypted, byte[] binding) { + Envelope { + encrypted = encrypted.clone(); + binding = binding.clone(); + } + + @Override + public byte[] encrypted() { + return encrypted.clone(); + } + + @Override + public byte[] binding() { + return binding.clone(); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Exact Account control-ui issuance owner evidence required"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java new file mode 100644 index 0000000000..9067ae24ef --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java @@ -0,0 +1,433 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.EmailCanonicalization; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Minimum genuine backend creator issuance/recovery, deliberately unregistered and unmounted. + * Primary credentials, existing owner sources and actual Coordination are all required. An + * independently protected exact peer binding supplies transport identity, never creator authority. + */ +public final class AccountControlUiIssuanceService { + private final AccountServiceImpl primaryAuthentication; + private final AccountControlUiIssuanceRepository operations; + private final AccountControlUiAuthority authority; + private final DraftAuthorizationFenceRepository fences; + private final AccountControlUiSignerOwner signers; + private final AccountControlUiResponseCryptography cryptography; + private final AccountControlUiCoordination registry; + private final AccountControlUiActorService actors; + private final TransactionTemplate transaction; + private final Clock clock; + private final long sessionSafetyMarginMillis; + private final String protectedCallerUri; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected primary authentication and Draft fence services remain internal Account owner collaborators.") + public AccountControlUiIssuanceService( + AccountServiceImpl primaryAuthentication, + AccountControlUiIssuanceRepository operations, + AccountControlUiAuthority authority, + DraftAuthorizationFenceRepository fences, + AccountControlUiSignerOwner signers, + AccountControlUiResponseCryptography cryptography, + AccountControlUiCoordination registry, + AccountControlUiActorService actors, + PlatformTransactionManager transactions, + Clock clock, + @Value("${firemud.auth.session-safety-margin-ms:300000}") long sessionSafetyMarginMillis, + String independentlyProtectedCallerUri) { + this.primaryAuthentication = Objects.requireNonNull(primaryAuthentication); + this.operations = Objects.requireNonNull(operations); + this.authority = Objects.requireNonNull(authority); + this.fences = Objects.requireNonNull(fences); + this.signers = Objects.requireNonNull(signers); + this.cryptography = Objects.requireNonNull(cryptography); + this.registry = Objects.requireNonNull(registry); + this.actors = Objects.requireNonNull(actors); + this.clock = Objects.requireNonNull(clock); + if (sessionSafetyMarginMillis < 0L) { + throw new IllegalArgumentException("Nonnegative Account session cleanup margin required"); + } + this.sessionSafetyMarginMillis = sessionSafetyMarginMillis; + protectedCallerUri = + GrpcPeerIdentity.parseUri(independentlyProtectedCallerUri) + .orElseThrow( + () -> new IllegalArgumentException("One protected exact issuer peer URI required")) + .uri(); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + public IssuedCredential issue(Request request, CapturedEnvironmentBoundary environment) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Control-ui workflow cannot inherit owner SQL locks"); + } + Objects.requireNonNull(request); + Objects.requireNonNull(environment); + var peer = GrpcPeerIdentity.current(); + if (peer == null || !protectedCallerUri.equals(peer.uri())) { + throw denied(); + } + String email = EmailCanonicalization.normalize(request.email); + byte[] exactRequest = + AccountControlUiAuthority.canonical( + Map.of( + "schema", + "account-control-ui-request/v1", + "requestId", + request.requestId.toString(), + "email", + email, + "secret", + request.secret, + "canonicalTenantId", + request.tenantId.toString(), + "callerWorkload", + peer.uri(), + "callerContextId", + request.callerContextId.toString())); + try { + InitialPreparation initial = + transaction.execute( + ignored -> { + var existing = operations.findRequest(request.requestId); + if (existing != null) { + requireRequest(existing, request, peer.uri(), exactRequest); + return new InitialPreparation(current(existing, environment), null); + } + // Preserve canonical tenant -> Account owner order before OTP/advisory + // authentication. + var source = authority.captureInitial(request.tenantId, environment); + fences.lockProducerSourcesNowait(source.sources()); + AccountServiceImpl.ControlUiPrimaryIdentity authenticated; + try { + authenticated = + primaryAuthentication.authenticateControlUiPrimaryIdentity( + email, request.secret); + } catch (AuthenticationException denial) { + // Only primary denial commits attempt accounting. No signer/issuance work + // follows. + return new InitialPreparation( + null, new PrimaryDenial(denial.getCode(), denial.getMessage())); + } + if (!source.actor().equals(authenticated.accountId())) { + throw denied(); + } + var signer = signers.captureCurrent(); + String macKey = cryptography.currentKeyId(); + String requestDigest = cryptography.requestDigest(macKey, exactRequest); + var stored = + operations.prepare( + request.requestId, + peer.uri(), + request.callerContextId, + macKey, + requestDigest, + authenticated, + source, + signer, + Instant.ofEpochSecond(clock.instant().getEpochSecond()), + sessionSafetyMarginMillis); + return new InitialPreparation(new Prepared(stored, source, signer), null); + }); + if (initial == null) { + throw denied(); + } + if (initial.denial != null) { + throw new AuthenticationException(initial.denial.code, initial.denial.message); + } + Prepared preparation = Objects.requireNonNull(initial.prepared); + var original = preparation.stored; + if ("PREPARED".equals(original.status)) { + var spec = + new AccountControlUiSigningSpec( + original.operationId, + original.requestId, + original.jti, + preparation.source, + original.issuedAt, + original.expiresAt); + if (!Arrays.equals(original.claims, AccountControlUiAuthority.canonical(spec.claims()))) { + throw denied(); + } + signers.sign( + preparation.signer, + spec, + (tokenHash, credential) -> { + String compact = new String(credential, StandardCharsets.US_ASCII); + var signed = actors.verifySigned(compact); + actors.requireSignerIdentity(original, signed); + if (!Arrays.equals( + original.claims, AccountControlUiAuthority.canonical(signed.claims.claims()))) { + throw denied(); + } + byte[] binding = envelopeBinding(original, tokenHash); + byte[] encrypted = cryptography.seal(credential, binding, original.recoveryExpiry); + transaction.execute( + ignored -> { + var stillCurrent = current(original, environment); + operations.bindCandidate( + stillCurrent.stored, tokenHash, encrypted, binding, stillCurrent.signer); + return null; + }); + }); + } + var candidate = transaction.execute(ignored -> current(original, environment).stored); + if (candidate == null) { + throw denied(); + } + AccountControlUiIssuanceRepository.Committed committed; + if ("CANDIDATE".equals(candidate.status)) { + var pending = + registry.registerPending( + candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); + committed = + transaction.execute( + ignored -> { + var observed = current(candidate, environment); + return operations.commit(observed.stored, pending); + }); + } else if ("COMMITTED".equals(candidate.status)) { + committed = + transaction.execute( + ignored -> { + current(candidate, environment); + return operations.requireCommitted(candidate); + }); + } else { + throw denied(); + } + if (committed == null) { + throw denied(); + } + registry.activate(committed); + var envelope = + transaction.execute( + ignored -> { + current(committed.stored, environment); + return operations.envelope(committed.stored); + }); + if (envelope == null + || !Arrays.equals( + envelope.binding(), envelopeBinding(committed.stored, committed.tokenHash()))) { + throw new RecoveryLost(committed.stored); + } + byte[] credential; + try { + credential = + cryptography.open( + envelope.encrypted(), envelope.binding(), committed.stored.recoveryExpiry); + } catch (AccountResponseEnvelopeCryptography.IntegrityException + | AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException permanent) { + throw new RecoveryLost(committed.stored); + } + try { + if (!committed.tokenHash().equals(AccountControlUiIssuanceRepository.hash(credential))) { + throw new RecoveryLost(committed.stored); + } + var actor = + actors.authenticate( + new String(credential, StandardCharsets.US_ASCII), request.tenantId, environment); + if (!actor.accountId().equals(committed.stored.accountId) + || !actor.issuanceOperationId().equals(committed.stored.operationId)) { + throw denied(); + } + return new IssuedCredential( + credential, committed.stored.expiresAt, committed.stored.recoveryExpiry); + } finally { + Arrays.fill(credential, (byte) 0); + } + } catch (RecoveryLost permanent) { + // Caller conflicts and unavailable SQL/custody/Coordination never enter this path. + // Persist denial first; ambiguous/missing Redis evidence leaves REVOKING, never success. + var failed = + transaction.execute(ignored -> operations.beginRecoveryFailure(permanent.original)); + if (failed != null && "REVOKING".equals(failed.status)) { + var receipt = registry.revoke(failed); + transaction.execute( + ignored -> { + operations.finishRecoveryFailure(failed, receipt); + return null; + }); + } + throw denied(); + } finally { + Arrays.fill(exactRequest, (byte) 0); + } + } + + private void requireRequest( + AccountControlUiIssuanceRepository.Stored stored, + Request request, + String caller, + byte[] exactRequest) { + if (!stored.requestId.equals(request.requestId) + || !stored.tenantId.equals(request.tenantId) + || !stored.caller.equals(caller) + || !stored.callerContextId.equals(request.callerContextId) + || !stored.requestDigest.equals( + cryptography.requestDigest(stored.requestMacKeyId, exactRequest))) { + throw new IllegalArgumentException("Control-ui issuance idempotency conflict"); + } + } + + private Prepared current( + AccountControlUiIssuanceRepository.Stored original, CapturedEnvironmentBoundary environment) { + // Missing cleanup evidence identifies a retained pre-margin row; never reinterpret or reissue + // it. + original.expiryMillis(); + if (!clock.instant().isBefore(original.recoveryExpiry) + || java.util.List.of("FAILED", "REVOKING", "REVOKED").contains(original.status)) { + throw new RecoveryLost(original); + } + var source = authority.capture(original.accountId, original.tenantId, environment); + fences.lockProducerSourcesNowait(source.sources()); + if (!Arrays.equals(source.evidence(), original.sources)) { + throw denied(); + } + var signer = signers.requireOriginal(original.signerReceipt); + var stored = operations.findRequest(original.requestId); + if (stored == null + || !stored.operationId.equals(original.operationId) + || !Arrays.equals(stored.sources, original.sources) + || !Arrays.equals(stored.claims, original.claims) + || !Arrays.equals(stored.signerReceipt, original.signerReceipt)) { + throw denied(); + } + return new Prepared(stored, source, signer); + } + + private static byte[] envelopeBinding( + AccountControlUiIssuanceRepository.Stored original, String tokenHash) { + return AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("purpose", "account-control-ui-original-credential/v1"), + Map.entry("operationId", original.operationId.toString()), + Map.entry("requestId", original.requestId.toString()), + Map.entry("accountId", original.accountId.toString()), + Map.entry("tenantId", original.tenantId.toString()), + Map.entry("callerWorkload", original.caller), + Map.entry("callerContextId", original.callerContextId.toString()), + Map.entry("requestMacKeyId", original.requestMacKeyId), + Map.entry("requestDigest", original.requestDigest), + Map.entry("tokenHash", tokenHash), + Map.entry("claimsDigest", AccountControlUiIssuanceRepository.hash(original.claims)), + Map.entry("bundleDigest", AccountControlUiIssuanceRepository.hash(original.bundle)), + Map.entry( + "signerReceiptDigest", + AccountControlUiIssuanceRepository.hash(original.signerReceipt)), + Map.entry("recoveryExpiresAt", original.recoveryExpiry.toString()))); + } + + private record PrimaryDenial(String code, String message) { + private PrimaryDenial { + Objects.requireNonNull(code); + Objects.requireNonNull(message); + } + } + + private record InitialPreparation(Prepared prepared, PrimaryDenial denial) { + private InitialPreparation { + if ((prepared == null) == (denial == null)) { + throw new IllegalArgumentException( + "Exactly one initial creator preparation outcome required"); + } + } + } + + private record Prepared( + AccountControlUiIssuanceRepository.Stored stored, + AccountControlUiAuthority.Snapshot source, + AccountControlUiSignerOwner.Capture signer) {} + + /** + * Only permanent loss established against the original owner record, never dependency failure. + */ + private static final class RecoveryLost extends RuntimeException { + private final AccountControlUiIssuanceRepository.Stored original; + + private RecoveryLost(AccountControlUiIssuanceRepository.Stored original) { + super("Original protected control-ui recovery permanently unavailable"); + this.original = original; + } + } + + public record Request( + UUID requestId, String email, String secret, UUID tenantId, UUID callerContextId) { + public Request { + if (requestId == null + || email == null + || email.isBlank() + || email.length() > 254 + || secret == null + || secret.isEmpty() + || secret.length() > 1024 + || tenantId == null + || callerContextId == null) { + throw new IllegalArgumentException("Exact bounded issuer request required"); + } + } + + @Override + public String toString() { + return "AccountControlUiIssuanceService.Request[redacted]"; + } + } + + public static final class IssuedCredential implements AutoCloseable { + private final byte[] bytes; + private final Instant expiresAt, recoveryExpiresAt; + + private IssuedCredential(byte[] bytes, Instant expiresAt, Instant recoveryExpiresAt) { + this.bytes = bytes.clone(); + this.expiresAt = expiresAt; + this.recoveryExpiresAt = recoveryExpiresAt; + } + + public byte[] compactBytes() { + return bytes.clone(); + } + + public Instant expiresAt() { + return expiresAt; + } + + public Instant recoveryExpiresAt() { + return recoveryExpiresAt; + } + + @Override + public void close() { + Arrays.fill(bytes, (byte) 0); + } + + @Override + public String toString() { + return "AccountControlUiIssuanceService.IssuedCredential[redacted]"; + } + } + + private static IllegalStateException denied() { + return new IllegalStateException("Control-ui original issuance/current recovery unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java new file mode 100644 index 0000000000..5c8f6d5621 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.file.Path; +import java.time.Instant; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +/** + * Separate unpublished control-ui custody using the existing bounded mounted-ring parser. + * encryption/ and request-mac/ each contain an independent existing-format keyring. Neither + * defaults to or reads the gameplay response-envelope mount. + */ +public final class AccountControlUiKeyring { + private final AccountResponseEnvelopeKeyring encryption; + private final AccountResponseEnvelopeKeyring requestMac; + + public AccountControlUiKeyring(Path dedicatedRoot) { + if (dedicatedRoot == null || !dedicatedRoot.isAbsolute()) { + throw new IllegalArgumentException("Separate absolute control-ui custody root required"); + } + encryption = new AccountResponseEnvelopeKeyring(dedicatedRoot.resolve("encryption").toString()); + requestMac = + new AccountResponseEnvelopeKeyring(dedicatedRoot.resolve("request-mac").toString()); + } + + AccountResponseEnvelopeKeyring encryption() { + return encryption; + } + + String requestKeyId() { + return requestMac.readCurrent().activeKeyId(); + } + + SecretKey requestKey(String id, Instant now) { + byte[] bytes = requestMac.readCurrent().decryptionKey(id, now).secretKey().getEncoded(); + byte[] encryptionBytes = encryption.readCurrent().activeKey().secretKey().getEncoded(); + try { + if (java.util.Arrays.equals(bytes, encryptionBytes)) { + throw new IllegalStateException("Control-ui encryption and request-MAC keys must differ"); + } + return new SecretKeySpec(bytes, "HmacSHA256"); + } finally { + java.util.Arrays.fill(bytes, (byte) 0); + java.util.Arrays.fill(encryptionBytes, (byte) 0); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java new file mode 100644 index 0000000000..c1b46b8aab --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java @@ -0,0 +1,45 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.*; + +/** Distinct owner descriptor; runtime catalog registration and ACL provisioning remain closed. */ +public final class AccountControlUiRegistryContract { + public static final String SCRIPT_ID = "account-control-ui-registry-cas.v1"; + public static final String RESOURCE = "redis/lua/account-control-ui-registry-cas.lua"; + + private AccountControlUiRegistryContract() {} + + public static RedisScriptDescriptor descriptor() { + return new RedisScriptDescriptor( + SCRIPT_ID, + RESOURCE, + "48c909de4aa5868772662972bf1ce449a2c83fd72cb06e5e2f43fea66e253a1b", + "account-service", + "account_coord_app", + RedisRole.COORDINATION, + List.of(new KeySpec("tokenRecord", "session:auth:token:", HashTagDeclaration.NOT_REQUIRED)), + List.of( + new ArgumentSpec("expectedOriginalRecord"), + new ArgumentSpec("exactReplacementRecord"), + new ArgumentSpec("absoluteCleanupDeadlineEpochMillis")), + ScriptCategory.SESSION_CAS, + List.of( + new OutcomeSpec("APPLIED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), + new OutcomeSpec("EXACT_REASSERTED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING), + new OutcomeSpec( + "INVALID_ARGUMENTS", + OutcomeCategory.VALIDATION_FAILURE, + MutationEffect.NON_MUTATING), + new OutcomeSpec("EXPIRED", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), + new OutcomeSpec("EXPIRY_MISMATCH", OutcomeCategory.STALE, MutationEffect.NON_MUTATING), + new OutcomeSpec("CONFLICT", OutcomeCategory.STALE, MutationEffect.NON_MUTATING)), + ResetSensitivity.CLUSTER, + LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, + "Missing or changed control-ui record denies; only original durable Account issuance may reconcile.", + CompatibilityLevel.REQUIRES_CLUSTER_RESET, + List.of(new SupportedCoexistence("v1", "v1")), + null); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java new file mode 100644 index 0000000000..917d03ba67 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java @@ -0,0 +1,219 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.api.sync.RedisCommands; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Read-only Account Coordination view of one committed control-ui token record. + * + *

This class is deliberately not a Spring bean and contains no Redis mutation path. A caller + * must supply Account's protected pinned connection provider; each read proves the live ACL user + * and exact physical cleanup deadline on that same non-reconnecting connection. Registry presence + * is only one input to Account's committed issuance/current-authority verification. + */ +public final class AccountControlUiRegistryReader { + public static final String TOKEN_KEY_PREFIX = "session:auth:token:"; + public static final String REQUIRED_ACL_IDENTITY = "account_coord_app"; + public static final int MAX_RECORD_BYTES = 32 * 1024; + + private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final long MAX_REDIS_SAFE_INTEGER = 9_007_199_254_740_991L; + private static final Set FIELDS = + Set.of( + "schemaVersion", + "registryVersion", + "tokenHash", + "kid", + "signerGeneration", + "issuer", + "profile", + "type", + "audience", + "accountId", + "jti", + "iat", + "nbf", + "exp", + "tokenGeneration", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "operationId", + "requestId", + "requestDigest", + "registryCleanupDeadlineEpochMillis", + "state", + "authoritySourceVersions", + "authEvidenceBundle", + "originalSignerReceiptDigest"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> OBJECT = new TypeReference<>() {}; + + private final AccountCoordinationPinnedConnectionProvider connections; + + public AccountControlUiRegistryReader(AccountCoordinationPinnedConnectionProvider connections) { + this.connections = + Objects.requireNonNull(connections, "private Account Coordination is required"); + } + + /** Reads and validates one active registry value without holding an Account SQL transaction. */ + public byte[] readActive(String tokenHash) { + outsideSql(); + if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) { + throw denied(); + } + try (var connection = connections.openPinnedConnection()) { + if (connection == null + || !connection.isOpen() + || connection.getOptions() == null + || connection.getOptions().isAutoReconnect()) { + throw denied(); + } + RedisCommands commands = connection.sync(); + if (!REQUIRED_ACL_IDENTITY.equals(commands.aclWhoami())) { + throw denied(); + } + byte[] key = (TOKEN_KEY_PREFIX + tokenHash).getBytes(StandardCharsets.US_ASCII); + byte[] exact = commands.get(key); + Map record = parseActiveRecord(exact, tokenHash); + long expiresAtMillis = + checkedCleanupDeadlineMillis( + record.get("exp"), record.get("registryCleanupDeadlineEpochMillis")); + Long physicalExpiry = commands.pexpiretime(key); + if (physicalExpiry == null || physicalExpiry.longValue() != expiresAtMillis) { + throw denied(); + } + return exact.clone(); + } catch (RuntimeException unavailable) { + throw denied(); + } + } + + static Map parseActiveRecord(byte[] exact, String tokenHash) { + if (exact == null || exact.length == 0 || exact.length > MAX_RECORD_BYTES) { + throw denied(); + } + try { + String json = + StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(exact)).toString(); + if (!Arrays.equals(exact, Rfc8785CanonicalJson.canonicalizeUtf8(json))) { + throw denied(); + } + Map fields = JSON.readValue(exact, OBJECT); + if (fields == null + || !fields.keySet().equals(FIELDS) + || !Integer.valueOf(1).equals(number(fields.get("schemaVersion"))) + || !Integer.valueOf(2).equals(number(fields.get("registryVersion"))) + || !tokenHash.equals(text(fields.get("tokenHash"))) + || !"firemud-account-service".equals(text(fields.get("issuer"))) + || !"control-ui".equals(text(fields.get("profile"))) + || !"control-ui".equals(text(fields.get("type"))) + || !"control-ui".equals(text(fields.get("audience"))) + || !"active".equals(text(fields.get("state"))) + || !KID.matcher(text(fields.get("kid"))).matches() + || !DECIMAL.matcher(text(fields.get("signerGeneration"))).matches() + || !DIGEST.matcher(text(fields.get("requestDigest"))).matches() + || !DIGEST.matcher(text(fields.get("originalSignerReceiptDigest"))).matches() + || !(fields.get("authorityTuple") instanceof Map) + || !(fields.get("membershipVersion") instanceof Map) + || !(fields.get("authoritySourceVersions") instanceof Map) + || !(fields.get("authEvidenceBundle") instanceof Map)) { + throw denied(); + } + requireUuid(fields.get("accountId")); + requireUuid(fields.get("jti")); + requireUuid(fields.get("operationId")); + requireUuid(fields.get("requestId")); + requirePositiveNumber(fields.get("iat")); + requirePositiveNumber(fields.get("nbf")); + requirePositiveNumber(fields.get("exp")); + requirePositiveNumber(fields.get("tokenGeneration")); + requirePositiveNumber(fields.get("issuanceFence")); + return Map.copyOf(fields); + } catch (IOException | RuntimeException malformed) { + throw denied(); + } + } + + static long checkedCleanupDeadlineMillis(Object encodedExpiry, Object encodedDeadline) { + try { + long expMillis = Math.multiplyExact(requirePositiveNumber(encodedExpiry), 1000L); + long deadline = requirePositiveNumber(encodedDeadline); + if (deadline < expMillis || deadline > MAX_REDIS_SAFE_INTEGER) { + throw denied(); + } + return deadline; + } catch (ArithmeticException | IllegalArgumentException malformed) { + throw denied(); + } + } + + private static Number number(Object value) { + return value instanceof Number number ? number : null; + } + + private static String text(Object value) { + return value instanceof String text ? text : ""; + } + + private static long requirePositiveNumber(Object value) { + if (!(value instanceof Number number)) { + throw denied(); + } + String encoded = number.toString(); + if (!DECIMAL.matcher(encoded).matches()) { + throw denied(); + } + try { + return Long.parseLong(encoded); + } catch (NumberFormatException malformed) { + throw denied(); + } + } + + private static void requireUuid(Object value) { + if (!(value instanceof String text)) { + throw denied(); + } + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) + || parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) { + throw denied(); + } + } catch (IllegalArgumentException malformed) { + throw denied(); + } + } + + private static void outsideSql() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account Coordination reads cannot retain Account SQL locks"); + } + } + + private static IllegalStateException denied() { + return new IllegalStateException( + "Exact Account active control-ui registry evidence unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java new file mode 100644 index 0000000000..a3de42db00 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java @@ -0,0 +1,76 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import javax.crypto.Mac; + +/** Distinct control-ui custody and purpose over the existing tested envelope primitive. */ +public final class AccountControlUiResponseCryptography { + private final AccountControlUiKeyring keys; + private final AccountResponseEnvelopeCryptography envelopes; + private final Clock clock; + + public AccountControlUiResponseCryptography(AccountControlUiKeyring keys, Clock clock) { + this.keys = Objects.requireNonNull(keys); + this.clock = Objects.requireNonNull(clock); + envelopes = + new AccountResponseEnvelopeCryptography( + keys.encryption(), clock, new java.security.SecureRandom()); + } + + String currentKeyId() { + return keys.requestKeyId(); + } + + String requestDigest(String keyId, byte[] exactRequest) { + if (exactRequest == null || exactRequest.length == 0 || exactRequest.length > 16384) { + throw new IllegalArgumentException("Bounded control-ui credential request required"); + } + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(keys.requestKey(keyId, clock.instant())); + mac.update("firemud/control-ui/credential-request/v1\0".getBytes(StandardCharsets.US_ASCII)); + return HexFormat.of().formatHex(mac.doFinal(exactRequest)); + } catch (java.security.GeneralSecurityException | RuntimeException exception) { + throw new IllegalStateException("Control-ui request MAC unavailable"); + } + } + + byte[] seal(byte[] credential, byte[] binding, Instant recoveryExpiry) { + return envelopes.encrypt(binding(binding), credential, recoveryExpiry).bytes(); + } + + byte[] open(byte[] envelope, byte[] binding, Instant recoveryExpiry) { + return envelopes.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope(envelope), + binding(binding), + recoveryExpiry); + } + + private static AccountResponseEnvelopeCryptography.Binding binding(byte[] exactOwnerBinding) { + try { + byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(exactOwnerBinding); + String identity = HexFormat.of().formatHex(digest); + // Labels identify cryptographic purpose, not a workload or authenticated actor. + return new AccountResponseEnvelopeCryptography.Binding( + "control-ui-issuance/v1", + identity, + digest, + "account-control-ui-custody", + identity, + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1, + "{}".getBytes(StandardCharsets.US_ASCII), + "{}".getBytes(StandardCharsets.US_ASCII), + exactOwnerBinding); + } catch (java.security.NoSuchAlgorithmException impossible) { + throw new IllegalStateException(impossible); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java new file mode 100644 index 0000000000..c982a8210a --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java @@ -0,0 +1,201 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.Objects; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; + +/** Unregistered genuine committed-signer owner, separate from non-authorizing readiness probes. */ +public final class AccountControlUiSignerOwner { + private final AccountJwtSignerDesiredStateRepository repository; + private final AccountJwtSignerMaterializerTrustBinding trust; + private final AccountJwtJwksApiBinding api; + private final Path privateRoot; + private final Path publicRoot; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected signer repository is an internal Account owner transaction collaborator.") + public AccountControlUiSignerOwner( + AccountJwtSignerDesiredStateRepository repository, + AccountJwtSignerMaterializerTrustBinding trust, + AccountJwtJwksApiBinding api, + Path privateRoot, + Path publicRoot) { + this.repository = Objects.requireNonNull(repository); + this.trust = Objects.requireNonNull(trust); + this.api = Objects.requireNonNull(api); + this.privateRoot = Objects.requireNonNull(privateRoot); + this.publicRoot = Objects.requireNonNull(publicRoot); + if (!privateRoot.isAbsolute() || !publicRoot.isAbsolute()) { + throw new IllegalArgumentException("Protected Account signer roots required"); + } + } + + /** Reads existing real lifecycle receipts under their existing Account owner transaction. */ + public Capture captureCurrent() { + return capture(null); + } + + /** Original retained owner receipt, independently re-read rather than treated as caller proof. */ + public Capture requireOriginal(byte[] originalReceipt) { + var observed = capture(Objects.requireNonNull(originalReceipt)); + if (!java.util.Arrays.equals(originalReceipt, observed.receipt())) { + throw unavailable(); + } + return observed; + } + + private Capture capture(byte[] originalReceipt) { + var materializer = trust.current().orElseThrow(AccountControlUiSignerOwner::unavailable); + var publicApi = api.current(); + if (!materializer.environmentId().equals(publicApi.environmentId()) + || !materializer.clusterId().equals(publicApi.clusterId()) + || !materializer.namespace().equals(publicApi.namespace()) + || !materializer + .expectedClusterIncarnationUid() + .equals(publicApi.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(publicApi.expectedNamespaceUid())) { + throw unavailable(); + } + var binding = + new AccountJwtSignerDesiredStateRepository.Binding( + materializer.environmentId(), + materializer.clusterId(), + materializer.namespace(), + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + var fence = + new TrustFence( + materializer.expectedClusterIncarnationUid(), + materializer.expectedNamespaceUid(), + materializer.bindingDigest(), + materializer.configRevision()); + AccountJwtSignerDesiredStateRepository.GenerationResult generation; + AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence promotion; + AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt privateReceipt; + AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt publicReceipt; + if (originalReceipt == null) { + var evidence = + repository + .readCurrentCommittedSigner( + binding, fence, publicApi.bindingDigest(), publicApi.configRevision()) + .orElseThrow(AccountControlUiSignerOwner::unavailable); + generation = evidence.generationResult(); + promotion = evidence.promotion(); + privateReceipt = evidence.privateReceipt(); + publicReceipt = evidence.publicReceipt(); + } else { + var original = AccountControlUiIssuanceRepository.object(originalReceipt); + var evidence = + repository + .readOriginalCommittedSigner( + binding, + fence, + publicApi.bindingDigest(), + publicApi.configRevision(), + java.util.UUID.fromString((String) original.get("promotionOperationId")), + java.util.UUID.fromString((String) original.get("generationOperationId"))) + .orElseThrow(AccountControlUiSignerOwner::unavailable); + generation = evidence.generationResult(); + promotion = evidence.promotion(); + privateReceipt = evidence.privateReceipt(); + publicReceipt = evidence.publicReceipt(); + } + if (!binding.equals(promotion.binding()) + || !binding.equals(generation.binding()) + || !fence.equals(promotion.trustFence()) + || !fence.equals(generation.trustFence()) + || !promotion.targetGeneration().equals(generation.targetGeneration()) + || !promotion.targetKid().equals(generation.targetKid()) + || !"RS256".equals(promotion.targetAlgorithm()) + || !"RS256".equals(generation.targetAlgorithm()) + || !promotion.targetPublicKeyFingerprint().equals(generation.publicKeyFingerprint())) { + throw unavailable(); + } + var expected = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + generation.operationId().toString(), + generation.targetGeneration(), + generation.targetKid(), + generation.publicKeyFingerprint()); + var receipt = new LinkedHashMap(); + receipt.put("schema", "account-control-ui-committed-signer/v1"); + receipt.put("environmentId", binding.environmentId()); + receipt.put("clusterId", binding.clusterId()); + receipt.put("namespace", binding.namespace()); + receipt.put("clusterIncarnationUid", materializer.expectedClusterIncarnationUid()); + receipt.put("namespaceUid", materializer.expectedNamespaceUid()); + receipt.put("trustBindingDigest", materializer.bindingDigest()); + receipt.put("trustConfigRevision", materializer.configRevision()); + receipt.put("apiBindingDigest", publicApi.bindingDigest()); + receipt.put("apiConfigRevision", publicApi.configRevision()); + receipt.put("promotionOperationId", promotion.operationId().toString()); + receipt.put("promotionRequestDigest", promotion.requestDigest()); + receipt.put("generationOperationId", generation.operationId().toString()); + receipt.put("signerGeneration", generation.targetGeneration()); + receipt.put("kid", generation.targetKid()); + receipt.put("algorithm", generation.targetAlgorithm()); + receipt.put("publicKeyFingerprint", generation.publicKeyFingerprint()); + receipt.put("privateReceiptDigest", privateReceipt.receiptDigest()); + receipt.put("privateResourceVersion", privateReceipt.observedResourceVersion()); + receipt.put("publicReceiptDigest", publicReceipt.receiptDigest()); + receipt.put("publicResourceVersion", publicReceipt.observedResourceVersion()); + receipt.put("publicConfigMapUid", publicReceipt.configMapUid()); + receipt.put("publicDataDigest", publicReceipt.publicDataDigest()); + return new Capture(expected, AccountControlUiAuthority.canonical(receipt)); + } + + String sign( + Capture original, + AccountControlUiSigningSpec spec, + java.util.function.BiConsumer candidateConsumer) { + return AccountMountedJwtSignerBundle.signCommittedControlUiDigest( + privateRoot, + Path.of("current.key"), + publicRoot, + Path.of("jwks.json"), + original.expected, + spec, + candidateConsumer); + } + + public static final class Capture { + private final AccountMountedJwtSignerBundle.ExpectedIdentity expected; + private final byte[] receipt; + + private Capture(AccountMountedJwtSignerBundle.ExpectedIdentity expected, byte[] receipt) { + this.expected = expected; + this.receipt = receipt.clone(); + } + + public byte[] receipt() { + return receipt.clone(); + } + + public String kid() { + return expected.kid(); + } + + public String generation() { + return expected.generation(); + } + + @Override + public String toString() { + return "AccountControlUiSignerOwner.Capture[redacted]"; + } + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Existing committed control-ui signer unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java new file mode 100644 index 0000000000..33b0c3650e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.lettuce.core.api.StatefulRedisConnection; + +/** Opens one private, dedicated, non-clustered Coordination connection for one Account read. */ +@FunctionalInterface +public interface AccountCoordinationPinnedConnectionProvider { + /** + * The provider must not return an ambient Spring connection, must disable automatic reconnect, + * and must retain one pinned physical Redis connection for the invocation. The caller checks the + * open/no-auto-reconnect contract and authenticates its ACL identity before reading data. + */ + StatefulRedisConnection openPinnedConnection(); + + /** Bounded durability acknowledgement requirements for one owner Coordination operation. */ + record AcknowledgementRequirements( + int requiredLocalAofCount, int requiredReplicaAofCount, int timeoutMillis) { + public AcknowledgementRequirements { + if (requiredLocalAofCount != 1 + || requiredReplicaAofCount < 1 + || requiredReplicaAofCount > 16 + || timeoutMillis < 1 + || timeoutMillis > 60_000) { + throw new IllegalArgumentException("WAITAOF requirements are outside the supported bound"); + } + } + } +} 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 new file mode 100644 index 0000000000..3f2077f190 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java @@ -0,0 +1,704 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.Supplier; +import java.util.regex.Pattern; +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 tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * The Account-only Kubernetes adapter for the pre-created public {@code jwt-jwks} ConfigMap. Every + * write is a fixed-name, resourceVersion-guarded merge patch followed by exact readback. This class + * is intentionally not a lifecycle, readiness, or signer-promotion authority. + */ +public final class AccountJwtJwksConfigMapClient { + public static final String CONFIG_MAP_NAME = "jwt-jwks"; + public static final String JWKS_DATA_KEY = "jwks.json"; + public static final String GENERATION_DATA_KEY = "jwt-generation.json"; + public static final int MAX_DESIRED_VALUE_BYTES = 768 * 1024; + private static final int MAX_CONFIG_MAP_DATA_KEYS = 128; + private static final int MAX_CONFIG_MAP_DATA_BYTES = 1024 * 1024; + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern UID = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Set ACCOUNT_DATA_KEYS = Set.of(JWKS_DATA_KEY, GENERATION_DATA_KEY); + private static final Set PRIVATE_JWK_FIELDS = + Set.of("d", "p", "q", "dp", "dq", "qi", "oth", "k"); + private static final byte[] SELF_SUBJECT_REVIEW_REQUEST = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}" + .getBytes(StandardCharsets.UTF_8); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final Supplier operationSupplier; + + /** Production constructor; API TLS and bearer handling remain inside the protected binding. */ + public AccountJwtJwksConfigMapClient(AccountJwtJwksApiBinding binding) { + AccountJwtJwksApiBinding requiredBinding = + Objects.requireNonNull(binding, "Account JWT JWKS API binding is required"); + this.operationSupplier = + () -> { + AccountJwtJwksApiBinding.ApiOperation operation = requiredBinding.beginOperation(); + return new ApiSession() { + @Override + public ParsedBinding binding() { + return operation.binding(); + } + + @Override + public ApiResponse send(ApiCall call, byte[] body) { + return operation.send(call, body); + } + + @Override + public void close() { + operation.close(); + } + }; + }; + } + + /** Deterministic bounded transport seam for focused tests. */ + AccountJwtJwksConfigMapClient(Supplier operationSupplier) { + this.operationSupplier = + Objects.requireNonNull(operationSupplier, "API operation supplier is required"); + } + + /** + * Returns only the independently protected non-secret API/destination pins. Callers can compare + * these with Account's materializer binding before creating durable publication intent. + */ + public BindingIdentity identity() { + try (ApiSession operation = beginOperation()) { + return toIdentity(operation.binding()); + } + } + + /** + * Reads only the fixed pre-created public ConfigMap after checking Account API identity and both + * namespace incarnation pins. No list, create, delete, or Secret endpoint is available. + */ + public ConfigMapSnapshot observe() { + try (ApiSession operation = beginOperation()) { + verifyEnvironment(operation); + return readConfigMap(operation); + } + } + + /** + * Applies an exact owner-authored public data map using Kubernetes resourceVersion CAS. Only + * {@code jwks.json} and {@code jwt-generation.json} are accepted; unrelated data is preserved. An + * ambiguous write is successful only after a fresh exact-content readback on the same UID. + */ + public CasObservation publish(ConfigMapSnapshot expected, Map desiredPublicData) { + Objects.requireNonNull(expected, "expected ConfigMap snapshot is required"); + Map desired = validateDesiredPublicData(desiredPublicData); + requireSnapshotIdentity(expected); + + try (ApiSession operation = beginOperation()) { + return publish(operation, expected, desired); + } + } + + /** + * Reconciles Account's exact active-marker transition from its durable prepublication RV. The + * freshly observed full snapshot preserves unrelated entries on a first write; an exact replay is + * accepted only when the live Account-owned data already matches and its RV advanced beyond the + * original prepublication fence. + */ + public CasObservation publishActiveProjection( + ConfigMapSnapshot observed, + String expectedPriorResourceVersion, + Map desiredPublicData) { + Objects.requireNonNull(observed, "fresh ConfigMap observation is required"); + Map desired = validateDesiredPublicData(desiredPublicData); + requireSnapshotIdentity(observed); + if (expectedPriorResourceVersion == null + || !RESOURCE_VERSION.matcher(expectedPriorResourceVersion).matches()) { + throw new IllegalArgumentException("Active ConfigMap prior resourceVersion is malformed"); + } + + try (ApiSession operation = beginOperation()) { + verifyEnvironment(operation); + ConfigMapSnapshot before = readConfigMap(operation); + if (!before.uid().equals(observed.uid()) + || !before.resourceVersion().equals(observed.resourceVersion()) + || !before.data().equals(observed.data())) { + throw conflict(before); + } + if (sameAccountData(before.data(), desired)) { + if (before.resourceVersion().equals(expectedPriorResourceVersion)) { + throw conflict(before); + } + return observationWithPrior( + expectedPriorResourceVersion, before, desired, Outcome.EXACT_REPLAY); + } + if (!before.resourceVersion().equals(expectedPriorResourceVersion)) { + throw conflict(before); + } + + byte[] patch = createMergePatch(before, desired); + verifyEnvironment(operation); + ApiResponse response; + try { + response = operation.send(ApiCall.PATCH_JWKS_CONFIG_MAP, patch); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + return reconcileUnknownWrite(operation, before, before, desired); + } + if (response.statusCode() == 409) { + verifyEnvironment(operation); + throw conflict(readConfigMap(operation)); + } + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (response.statusCode() >= 500 || response.statusCode() == 408) { + return reconcileUnknownWrite(operation, before, before, desired); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + ConfigMapSnapshot readback; + try { + verifyEnvironment(operation); + readback = readConfigMap(operation); + } catch (RuntimeException ex) { + throw new UncertainOutcomeException(); + } + requireExactPostcondition(before, before, readback, desired); + return observationWithPrior(expectedPriorResourceVersion, readback, desired, Outcome.APPLIED); + } + } + + private CasObservation publish( + ApiSession operation, ConfigMapSnapshot expected, Map desired) { + verifyEnvironment(operation); + ConfigMapSnapshot before = readConfigMap(operation); + if (!before.uid().equals(expected.uid())) { + throw conflict(before); + } + if (sameAccountData(before.data(), desired)) { + if (before.resourceVersion().equals(expected.resourceVersion())) { + throw conflict(before); + } + return observation(expected, before, desired, Outcome.EXACT_REPLAY); + } + if (!before.resourceVersion().equals(expected.resourceVersion())) { + throw conflict(before); + } + + byte[] patch = createMergePatch(expected, desired); + // Identity checks are repeated immediately before the only write call. + verifyEnvironment(operation); + ApiResponse response; + try { + response = operation.send(ApiCall.PATCH_JWKS_CONFIG_MAP, patch); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + return reconcileUnknownWrite(operation, expected, before, desired); + } + if (response.statusCode() == 409) { + verifyEnvironment(operation); + throw conflict(readConfigMap(operation)); + } + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (response.statusCode() >= 500 || response.statusCode() == 408) { + return reconcileUnknownWrite(operation, expected, before, desired); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + + ConfigMapSnapshot readback; + try { + verifyEnvironment(operation); + readback = readConfigMap(operation); + } catch (RuntimeException ex) { + throw new UncertainOutcomeException(); + } + requireExactPostcondition(expected, before, readback, desired); + return observation(expected, readback, desired, Outcome.APPLIED); + } + + private CasObservation reconcileUnknownWrite( + ApiSession operation, + ConfigMapSnapshot expected, + ConfigMapSnapshot before, + Map desired) { + try { + verifyEnvironment(operation); + ConfigMapSnapshot observed = readConfigMap(operation); + if (observed.uid().equals(expected.uid()) && sameAccountData(observed.data(), desired)) { + requirePreservedUnrelatedData(before, observed); + if (observed.resourceVersion().equals(expected.resourceVersion())) { + throw new UncertainOutcomeException(); + } + return observation(expected, observed, desired, Outcome.EXACT_REPLAY); + } + } catch (UncertainOutcomeException ex) { + throw ex; + } catch (RuntimeException ex) { + // The write outcome remains unknown when reconciliation itself is unavailable. + } + throw new UncertainOutcomeException(); + } + + private void requireExactPostcondition( + ConfigMapSnapshot expected, + ConfigMapSnapshot before, + ConfigMapSnapshot readback, + Map desired) { + if (!readback.uid().equals(expected.uid()) + || readback.resourceVersion().equals(expected.resourceVersion()) + || !sameAccountData(readback.data(), desired)) { + throw new UncertainOutcomeException(); + } + requirePreservedUnrelatedData(before, readback); + } + + private static void requirePreservedUnrelatedData( + ConfigMapSnapshot before, ConfigMapSnapshot after) { + Map previous = unrelatedData(before.data()); + Map current = unrelatedData(after.data()); + if (!previous.equals(current)) { + throw new UncertainOutcomeException(); + } + } + + private static Map unrelatedData(Map data) { + Map unrelated = new LinkedHashMap<>(); + data.forEach( + (key, value) -> { + if (!ACCOUNT_DATA_KEYS.contains(key)) { + unrelated.put(key, value); + } + }); + return Map.copyOf(unrelated); + } + + private ConfigMapSnapshot readConfigMap(ApiSession operation) { + ApiResponse response = send(operation, ApiCall.READ_JWKS_CONFIG_MAP, null); + if (response.statusCode() == 404) { + throw new ResourceMissingException(); + } + if (!isSuccess(response.statusCode())) { + throw new ApiFailureException(response.statusCode()); + } + return parseConfigMap(response.body(), operation.binding()); + } + + private void verifyEnvironment(ApiSession operation) { + ParsedBinding binding = operation.binding(); + ApiResponse selfReview = + send(operation, ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, SELF_SUBJECT_REVIEW_REQUEST); + if ((selfReview.statusCode() != 200 && selfReview.statusCode() != 201) + || !binding.expectedApiUsername().equals(parseAuthenticatedUsername(selfReview.body()))) { + throw new BindingRejectedException(); + } + verifyNamespace( + send(operation, ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null), + "kube-system", + binding.expectedClusterIncarnationUid()); + verifyNamespace( + send(operation, ApiCall.READ_TARGET_NAMESPACE, null), + binding.namespace(), + binding.expectedNamespaceUid()); + } + + private void verifyNamespace(ApiResponse response, String name, String expectedUid) { + if (!isSuccess(response.statusCode())) { + if (response.statusCode() == 404) { + throw new BindingRejectedException(); + } + throw new ApiFailureException(response.statusCode()); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode status = root.get("status"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"Namespace".equals(text(root.get("kind"))) + || metadata == null + || !name.equals(text(metadata.get("name"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || status == null + || !"Active".equals(text(status.get("phase")))) { + throw new BindingRejectedException(); + } + } + + private static String parseAuthenticatedUsername(byte[] bytes) { + JsonNode root = parseJson(bytes); + JsonNode status = root.get("status"); + JsonNode userInfo = status == null ? null : status.get("userInfo"); + String username = userInfo == null ? null : text(userInfo.get("username")); + JsonNode evaluationError = status == null ? null : status.get("evaluationError"); + if (!"authentication.k8s.io/v1".equals(text(root.get("apiVersion"))) + || !"SelfSubjectReview".equals(text(root.get("kind"))) + || username == null + || (evaluationError != null + && !evaluationError.isNull() + && (!evaluationError.isTextual() || !evaluationError.asText().isEmpty()))) { + throw new BindingRejectedException(); + } + return username; + } + + private static ConfigMapSnapshot parseConfigMap(byte[] bytes, ParsedBinding binding) { + JsonNode root = parseJson(bytes); + JsonNode metadata = root.get("metadata"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"ConfigMap".equals(text(root.get("kind"))) + || metadata == null + || !CONFIG_MAP_NAME.equals(text(metadata.get("name"))) + || !binding.namespace().equals(text(metadata.get("namespace"))) + || metadata.hasNonNull("deletionTimestamp") + || Boolean.TRUE.equals(booleanValue(root.get("immutable"))) + || (root.has("binaryData") && !root.get("binaryData").isNull())) { + throw new ApiFailureException(0); + } + String uid = canonicalUid(text(metadata.get("uid"))); + String resourceVersion = text(metadata.get("resourceVersion")); + if (resourceVersion == null || !RESOURCE_VERSION.matcher(resourceVersion).matches()) { + throw new ApiFailureException(0); + } + Map data = parseData(root.get("data")); + return new ConfigMapSnapshot(uid, resourceVersion, data); + } + + private static Map parseData(JsonNode dataNode) { + if (dataNode == null || dataNode.isNull()) { + return Map.of(); + } + if (!dataNode.isObject() || dataNode.size() > MAX_CONFIG_MAP_DATA_KEYS) { + throw new ApiFailureException(0); + } + Map data = new LinkedHashMap<>(); + int totalBytes = 0; + for (Map.Entry entry : dataNode.properties()) { + JsonNode value = entry.getValue(); + if (!value.isTextual()) { + throw new ApiFailureException(0); + } + String text = value.asText(); + totalBytes += text.getBytes(StandardCharsets.UTF_8).length; + if (totalBytes > MAX_CONFIG_MAP_DATA_BYTES) { + throw new ApiFailureException(0); + } + data.put(entry.getKey(), text); + } + return Map.copyOf(data); + } + + private ApiSession beginOperation() { + try { + return Objects.requireNonNull(operationSupplier.get(), "API operation is unavailable"); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (RuntimeException ex) { + throw new BindingRejectedException(); + } + } + + private ApiResponse send(ApiSession operation, ApiCall call, byte[] body) { + try { + return operation.send(call, body); + } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) { + throw new BindingRejectedException(); + } catch (AccountJwtJwksApiBinding.ApiTransportException ex) { + throw new ApiFailureException(0); + } + } + + private static BindingIdentity toIdentity(ParsedBinding binding) { + return new BindingIdentity( + binding.bindingDigest(), + binding.configRevision(), + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.apiServer().toString(), + binding.tlsServerName(), + binding.servingCaSha256(), + binding.expectedApiUsername()); + } + + private static Map validateDesiredPublicData(Map desired) { + if (desired == null || !desired.keySet().equals(ACCOUNT_DATA_KEYS)) { + throw new IllegalArgumentException("Account public JWKS data keys are invalid"); + } + Map copy = new LinkedHashMap<>(); + int total = 0; + for (String key : ACCOUNT_DATA_KEYS) { + String value = desired.get(key); + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Account public JWKS data is incomplete"); + } + int length = value.getBytes(StandardCharsets.UTF_8).length; + if (length > MAX_DESIRED_VALUE_BYTES) { + throw new IllegalArgumentException("Account public JWKS data exceeds its bound"); + } + total += length; + copy.put(key, value); + } + if (total > MAX_CONFIG_MAP_DATA_BYTES) { + throw new IllegalArgumentException("Account public JWKS data exceeds its bound"); + } + validatePublicJwks(copy.get(JWKS_DATA_KEY)); + return Map.copyOf(copy); + } + + private static void validatePublicJwks(String jwks) { + JsonNode root = parseJson(jwks.getBytes(StandardCharsets.UTF_8)); + JsonNode keys = root.get("keys"); + if (!root.isObject() || root.size() != 1 || keys == null || !keys.isArray() || keys.isEmpty()) { + throw new IllegalArgumentException("Account public JWKS is malformed"); + } + for (JsonNode key : keys) { + if (!key.isObject()) { + throw new IllegalArgumentException("Account public JWKS is malformed"); + } + for (String privateField : PRIVATE_JWK_FIELDS) { + if (key.has(privateField)) { + throw new IllegalArgumentException("Account public JWKS contains private material"); + } + } + } + } + + private static byte[] createMergePatch(ConfigMapSnapshot expected, Map desired) { + Map metadata = new LinkedHashMap<>(); + metadata.put("uid", expected.uid()); + metadata.put("resourceVersion", expected.resourceVersion()); + Map patch = new LinkedHashMap<>(); + patch.put("metadata", metadata); + patch.put("data", desired); + try { + return STRICT_JSON.writeValueAsBytes(patch); + } catch (Exception ex) { + throw new IllegalStateException("Account public JWKS patch could not be encoded"); + } + } + + private static boolean sameAccountData(Map current, Map desired) { + return desired.get(JWKS_DATA_KEY).equals(current.get(JWKS_DATA_KEY)) + && desired.get(GENERATION_DATA_KEY).equals(current.get(GENERATION_DATA_KEY)); + } + + private static CasObservation observation( + ConfigMapSnapshot expected, + ConfigMapSnapshot observed, + Map desired, + Outcome outcome) { + Map exactOutput = new LinkedHashMap<>(); + exactOutput.put(JWKS_DATA_KEY, desired.get(JWKS_DATA_KEY)); + exactOutput.put(GENERATION_DATA_KEY, desired.get(GENERATION_DATA_KEY)); + return new CasObservation( + observed.uid(), + expected.resourceVersion(), + observed.resourceVersion(), + exactOutput, + observed.data(), + outcome); + } + + private static CasObservation observationWithPrior( + String priorResourceVersion, + ConfigMapSnapshot observed, + Map desired, + Outcome outcome) { + Map exactOutput = new LinkedHashMap<>(); + exactOutput.put(JWKS_DATA_KEY, desired.get(JWKS_DATA_KEY)); + exactOutput.put(GENERATION_DATA_KEY, desired.get(GENERATION_DATA_KEY)); + return new CasObservation( + observed.uid(), + priorResourceVersion, + observed.resourceVersion(), + exactOutput, + observed.data(), + outcome); + } + + private static CasConflictException conflict(ConfigMapSnapshot observed) { + return new CasConflictException(observed.uid(), observed.resourceVersion()); + } + + private static void requireSnapshotIdentity(ConfigMapSnapshot snapshot) { + if (!validUid(snapshot.uid()) + || snapshot.resourceVersion() == null + || !RESOURCE_VERSION.matcher(snapshot.resourceVersion()).matches()) { + throw new IllegalArgumentException("Expected ConfigMap snapshot identity is malformed"); + } + } + + private static boolean isSuccess(int statusCode) { + return statusCode >= 200 && statusCode < 300; + } + + private static JsonNode parseJson(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_CONFIG_MAP_DATA_BYTES) { + throw new ApiFailureException(0); + } + try { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || !root.isObject()) { + throw new ApiFailureException(0); + } + return root; + } catch (CharacterCodingException | RuntimeException ex) { + throw new ApiFailureException(0); + } + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + @SuppressFBWarnings( + value = "NP_BOOLEAN_RETURN_NULL", + justification = + "The parser intentionally preserves absent or malformed booleans as unknown; callers require explicit true.") + private static Boolean booleanValue(JsonNode node) { + return node != null && node.isBoolean() ? node.booleanValue() : null; + } + + private static String canonicalUid(String value) { + if (!validUid(value)) { + throw new ApiFailureException(0); + } + return value; + } + + private static boolean validUid(String value) { + return value != null + && UID.matcher(value).matches() + && !"00000000-0000-0000-0000-000000000000".equals(value); + } + + interface ApiSession extends AutoCloseable { + ParsedBinding binding(); + + ApiResponse send(ApiCall call, byte[] body); + + @Override + void close(); + } + + public record BindingIdentity( + String bindingDigest, + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String apiServerUrl, + String tlsServerName, + String servingCaSha256, + String expectedApiUsername) {} + + public record ConfigMapSnapshot(String uid, String resourceVersion, Map data) { + public ConfigMapSnapshot { + data = data == null ? Map.of() : Map.copyOf(data); + } + } + + public record CasObservation( + String uid, + String priorResourceVersion, + String resourceVersion, + Map publishedData, + Map readbackData, + Outcome outcome) { + public CasObservation { + publishedData = Map.copyOf(publishedData); + readbackData = Map.copyOf(readbackData); + } + } + + public enum Outcome { + APPLIED, + EXACT_REPLAY + } + + public static class ResourceMissingException extends RuntimeException { + public ResourceMissingException() { + super("Pre-created Account public JWKS ConfigMap is unavailable"); + } + } + + public static class CasConflictException extends RuntimeException { + private final String observedUid; + private final String observedResourceVersion; + + public CasConflictException(String observedUid, String observedResourceVersion) { + super("Account public JWKS ConfigMap compare-and-set conflict"); + this.observedUid = observedUid; + this.observedResourceVersion = observedResourceVersion; + } + + public String observedUid() { + return observedUid; + } + + public String observedResourceVersion() { + return observedResourceVersion; + } + } + + public static class UncertainOutcomeException extends RuntimeException { + public UncertainOutcomeException() { + super("Account public JWKS ConfigMap write outcome is uncertain"); + } + } + + public static class ApiFailureException extends RuntimeException { + private final int statusCode; + + public ApiFailureException(int statusCode) { + super("Account public JWKS Kubernetes API request failed"); + this.statusCode = statusCode; + } + + public int statusCode() { + return statusCode; + } + } + + public static class BindingRejectedException extends RuntimeException { + public BindingRejectedException() { + super("Account public JWKS API binding or identity was rejected"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java new file mode 100644 index 0000000000..17de38c401 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java @@ -0,0 +1,935 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +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.security.KeyFactory; +import java.security.spec.RSAPublicKeySpec; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +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.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +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.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned producer for the public JWKS prepublication phase and local mounted correspondence + * observation. + * + *

It accepts no caller-selected operation, key identity, ConfigMap name, or public bytes. The + * only source key is the exact current Account generation receipt. Remote CAS is outside SQL + * transactions and is preceded by a durable immutable intent. Neither publication nor local + * correspondence establishes PREPARED, COMMITTED, issuance, cache convergence, probes, or + * readiness. + */ +public final class AccountJwtJwksPrepublicationService { + public static final int MAX_MOUNTED_MARKER_BYTES = 16 * 1024; + private static final String PRIVATE_MOUNT = "/var/run/secrets/firemud/jwt"; + private static final String PRIVATE_PENDING_BUNDLE = "pending.key"; + private static final String PRIVATE_ACTIVE_BUNDLE = "current.key"; + private static final String PUBLIC_MOUNT = "/var/run/secrets/firemud/jwks"; + private static final String PUBLIC_JWKS = "jwks.json"; + private static final String PUBLIC_MARKER = "jwt-generation.json"; + private static final int MAX_KEYS = 64; + private static final int MIN_RSA_BITS = 3_072; + private static final int MAX_RSA_BITS = 16_384; + private static final Set JWKS_ROOT_FIELDS = Set.of("keys"); + private static final Set JWK_FIELDS = + Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPublicationRepository publicationRepository; + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtJwksConfigMapClient configMapClient; + private final TransactionTemplate accountTransaction; + private final MountedProjection mountedProjection; + + /** Production instance uses only the fixed Account signer/JWKS mount paths. */ + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The production constructor intentionally fixes Account's protected private-signer and read-only public-JWKS mount roots.") + public AccountJwtJwksPrepublicationService( + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksConfigMapClient configMapClient, + PlatformTransactionManager transactionManager) { + this( + desiredStateRepository, + publicationRepository, + materializerTrustBinding, + configMapClient, + transactionManager, + new MountedProjection( + Path.of(PRIVATE_MOUNT), + Path.of(PRIVATE_PENDING_BUNDLE), + Path.of(PUBLIC_MOUNT), + Path.of(PUBLIC_JWKS), + Path.of(PUBLIC_MARKER))); + } + + AccountJwtJwksPrepublicationService( + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksConfigMapClient configMapClient, + PlatformTransactionManager transactionManager, + MountedProjection mountedProjection) { + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required"); + this.publicationRepository = + Objects.requireNonNull(publicationRepository, "JWKS publication repository is required"); + this.materializerTrustBinding = + Objects.requireNonNull( + materializerTrustBinding, "Protected materializer trust is required"); + this.configMapClient = + Objects.requireNonNull(configMapClient, "Protected ConfigMap client is required"); + this.accountTransaction = new TransactionTemplate(transactionManager); + this.accountTransaction.setReadOnly(false); + this.mountedProjection = Objects.requireNonNull(mountedProjection); + } + + /** + * Publishes exactly Account's current pending public JWK alongside all retained public keys. + * Exact retries reconcile a previously persisted intent; changed/stale ConfigMap data fail before + * another write. + */ + public PublicationReceipt prepublishCurrentGeneration() { + Binding binding = requireCurrentMaterializerBinding(); + BindingIdentity apiIdentity = requireMatchingApiIdentity(binding, configMapClient.identity()); + CurrentGeneration current = loadCurrentGeneration(binding, apiIdentity); + if (current.publication().isPresent()) { + PublicationEvidence evidence = current.publication().orElseThrow(); + PrepublicationIntent intent = evidence.intent(); + requireIntentApiIdentity(intent, apiIdentity); + ConfigMapSnapshot snapshot = configMapClient.observe(); + if (evidence.receipt().isPresent()) { + requirePublishedProjection(intent, snapshot); + requireUnchangedBindings(binding, apiIdentity); + return evidence.receipt().orElseThrow(); + } + requireRetrySnapshot(intent, snapshot); + return publishAndRecord(binding, apiIdentity, intent, snapshot); + } + + ConfigMapSnapshot snapshot = configMapClient.observe(); + String sourceJwks = snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY); + if (sourceJwks == null || sourceJwks.isBlank()) { + throw new PublicationRejectedException( + "Pre-created Account public JWKS ConfigMap has no bounded jwks.json value"); + } + String desiredJwks = appendPendingPublicKey(sourceJwks, current.result()); + String marker = generationMarker(current.result(), current.request(), apiIdentity); + PrepublicationIntent intent = + accountTransaction.execute( + status -> { + PrepublicationIntent persisted = + publicationRepository.recordPrepublicationIntent( + binding.accountBinding(), + trustFence(binding), + current.result(), + current.request(), + apiIdentity.bindingDigest(), + apiIdentity.configRevision(), + snapshot.uid(), + snapshot.resourceVersion(), + AccountJwtJwksPublicationRepository.snapshotDigest(snapshot.data()), + desiredJwks, + marker); + requireUnchangedBindings(binding, apiIdentity); + return persisted; + }); + if (intent == null) { + throw new PublicationRejectedException("Account JWT JWKS intent was not persisted"); + } + requireIntentApiIdentity(intent, apiIdentity); + requireRetrySnapshot(intent, snapshot); + return publishAndRecord(binding, apiIdentity, intent, snapshot); + } + + /** + * Observes exact mounted {@code pending.key}, {@code jwks.json}, and publication marker files. + * The operation must already have an exact persisted Account API readback receipt. + */ + public MountObservation observeCurrentMountedCorrespondence() { + Binding binding = requireCurrentMaterializerBinding(); + BindingIdentity apiIdentity = requireMatchingApiIdentity(binding, configMapClient.identity()); + CurrentGeneration current = loadCurrentGeneration(binding, apiIdentity); + PublicationEvidence evidence = + current + .publication() + .orElseThrow( + () -> + new PublicationRejectedException( + "Account JWT JWKS publication evidence is not available")); + PrepublicationIntent intent = evidence.intent(); + evidence + .receipt() + .orElseThrow( + () -> + new PublicationRejectedException("Account JWT JWKS API readback is not available")); + requireIntentApiIdentity(intent, apiIdentity); + + byte[] markerBytes = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.markerPath(), + MAX_MOUNTED_MARKER_BYTES); + byte[] jwksBytes = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES); + String marker = strictUtf8(markerBytes); + String mountedJwks = strictUtf8(jwksBytes); + if (!intent.generationMarkerJson().equals(marker) + || !intent.jwksJson().equals(mountedJwks) + || !intent + .publicDataDigest() + .equals(AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, marker))) { + throw new PublicationRejectedException( + "Mounted Account public JWT projection does not match Account's exact publication"); + } + + AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + current.result().operationId().toString(), + current.result().targetGeneration(), + current.result().targetKid(), + current.result().publicKeyFingerprint()); + AccountMountedJwtSignerBundle.LocalObservation localObservation = + AccountMountedJwtSignerBundle.observeMounted( + mountedProjection.privateMountRoot(), + mountedProjection.pendingBundlePath(), + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + expectedIdentity); + + byte[] markerAfter = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.markerPath(), + MAX_MOUNTED_MARKER_BYTES); + byte[] jwksAfter = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES); + if (!Arrays.equals(markerBytes, markerAfter) || !Arrays.equals(jwksBytes, jwksAfter)) { + throw new PublicationRejectedException( + "Mounted Account public JWT projection changed during correspondence observation"); + } + MountObservation observation = + accountTransaction.execute( + status -> { + MountObservation persisted = + publicationRepository.recordMountedCorrespondence( + binding.accountBinding(), + trustFence(binding), + current.result().operationId(), + sha256(markerBytes), + AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, marker), + localObservation.publicKeyFingerprint()); + requireUnchangedBindings(binding, apiIdentity); + return persisted; + }); + if (observation == null) { + throw new PublicationRejectedException( + "Mounted Account JWT correspondence was not persisted"); + } + Arrays.fill(markerBytes, (byte) 0); + Arrays.fill(jwksBytes, (byte) 0); + Arrays.fill(markerAfter, (byte) 0); + Arrays.fill(jwksAfter, (byte) 0); + return observation; + } + + /** + * Observes the exact Account PREPARED operation's current private key and public projection + * without mutating either resource. The protected fixed Secret may already have been promoted + * while the public ConfigMap remains PREPUBLISHED; after an ambiguous Account-owned CAS, the + * exact ACTIVE projection is also accepted for forward reconciliation. + */ + public ConfigMapSnapshot observePreparedCurrentKeyCorrespondence( + PromotionOperationEvidence promotion) { + Objects.requireNonNull(promotion, "Account PREPARED promotion is required"); + Binding binding = requireCurrentMaterializerBinding(); + BindingIdentity apiIdentity = requireMatchingApiIdentity(binding, configMapClient.identity()); + TrustFence trust = trustFence(binding); + if (!promotion.binding().equals(binding.accountBinding()) + || !promotion.trustFence().equals(trust) + || !promotion.apiBindingDigest().equals(apiIdentity.bindingDigest()) + || !promotion.apiConfigRevision().equals(apiIdentity.configRevision()) + || !"PREPARED".equals(promotion.status()) + || !promotion.privatePromotionDispatched() + || promotion.privatePromotionReceiptDigest().isEmpty() + || !promotion.expectedPreviousActive().equals(promotion.expectedPublishedActive())) { + throw new PublicationRejectedException( + "Prepared Account JWT operation no longer matches protected bindings"); + } + + var publication = + accountTransaction.execute( + status -> + publicationRepository.readPreparedPublicationForRecovery( + binding.accountBinding(), trust)); + if (publication == null + || !publication.intent().operationId().equals(promotion.generationOperationId()) + || !publication.intent().intentDigest().equals(promotion.prepublicationIntentDigest()) + || !publication.receipt().receiptDigest().equals(promotion.prepublicationReceiptDigest()) + || !publication.intent().configMapUid().equals(promotion.publicConfigMapUid()) + || !publication + .receipt() + .observedResourceVersion() + .equals(promotion.expectedPublicResourceVersion()) + || !publication.intent().jwksJson().equals(promotion.expectedPublicJwksJson())) { + throw new PublicationRejectedException( + "Prepared Account JWT operation has no exact public publication evidence"); + } + + ConfigMapSnapshot snapshot = configMapClient.observe(); + String mountedJwks = snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY); + String apiMarker = + snapshot.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY); + boolean prepublished = publication.intent().generationMarkerJson().equals(apiMarker); + boolean active = promotion.expectedActiveMarkerJson().equals(apiMarker); + if (!promotion.publicConfigMapUid().equals(snapshot.uid()) + || !promotion.expectedPublicJwksJson().equals(mountedJwks) + || (!prepublished && !active) + || (prepublished + && !promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion())) + || (active + && promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion()))) { + throw new PublicationRejectedException( + "Live Account public JWT projection is not the exact PREPARED or ACTIVE value"); + } + if (promotion.activeJwksReceiptDigest().isPresent()) { + if (!active + || !promotion + .activeJwksObservedResourceVersion() + .filter(snapshot.resourceVersion()::equals) + .isPresent() + || !promotion + .activeJwksPublicDataDigest() + .filter( + AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, apiMarker) + ::equals) + .isPresent()) { + throw new PublicationRejectedException( + "Live Account ACTIVE JWT projection differs from its durable receipt"); + } + } + + byte[] markerBefore = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.markerPath(), + MAX_MOUNTED_MARKER_BYTES); + byte[] jwksBefore = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES); + byte[] markerAfter = null; + byte[] jwksAfter = null; + try { + if (!apiMarker.equals(strictUtf8(markerBefore)) + || !mountedJwks.equals(strictUtf8(jwksBefore))) { + throw new PublicationRejectedException( + "Mounted Account public JWT projection has not caught up to its exact API value"); + } + AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + promotion.generationOperationId().toString(), + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()); + AccountMountedJwtSignerBundle.LocalObservation local = + AccountMountedJwtSignerBundle.observeMounted( + mountedProjection.privateMountRoot(), + Path.of(PRIVATE_ACTIVE_BUNDLE), + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + expectedIdentity); + if (!local.expectedIdentity().equals(expectedIdentity)) { + throw new PublicationRejectedException( + "Mounted Account current JWT key does not match the PREPARED operation"); + } + markerAfter = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.markerPath(), + MAX_MOUNTED_MARKER_BYTES); + jwksAfter = + readMountedFile( + mountedProjection.publicMountRoot(), + mountedProjection.jwksPath(), + AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES); + if (!Arrays.equals(markerBefore, markerAfter) || !Arrays.equals(jwksBefore, jwksAfter)) { + throw new PublicationRejectedException( + "Mounted Account public JWT projection changed during current-key correspondence"); + } + requireUnchangedBindings(binding, apiIdentity); + return snapshot; + } finally { + Arrays.fill(markerBefore, (byte) 0); + Arrays.fill(jwksBefore, (byte) 0); + if (markerAfter != null) { + Arrays.fill(markerAfter, (byte) 0); + } + if (jwksAfter != null) { + Arrays.fill(jwksAfter, (byte) 0); + } + } + } + + private PublicationReceipt publishAndRecord( + Binding binding, + BindingIdentity apiIdentity, + PrepublicationIntent intent, + ConfigMapSnapshot expectedSnapshot) { + requireUnchangedBindings(binding, apiIdentity); + Map desiredData = desiredData(intent); + ConfigMapSnapshot intentCasSnapshot = + new ConfigMapSnapshot( + intent.configMapUid(), intent.expectedResourceVersion(), expectedSnapshot.data()); + CasObservation observation = configMapClient.publish(intentCasSnapshot, desiredData); + if (!intent.configMapUid().equals(observation.uid()) + || !intent.expectedResourceVersion().equals(observation.priorResourceVersion()) + || !observation.publishedData().equals(desiredData) + || !desiredData.entrySet().stream() + .allMatch( + entry -> entry.getValue().equals(observation.readbackData().get(entry.getKey()))) + || intent.expectedResourceVersion().equals(observation.resourceVersion())) { + throw new PublicationRejectedException( + "Protected Account public JWKS client returned a non-exact readback"); + } + requireUnchangedBindings(binding, apiIdentity); + PublicationReceipt persisted = + accountTransaction.execute( + status -> { + PublicationReceipt receipt = + publicationRepository.recordPublicationReceipt( + binding.accountBinding(), + trustFence(binding), + intent.operationId(), + apiIdentity.bindingDigest(), + apiIdentity.configRevision(), + observation.uid(), + observation.resourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson()); + requireUnchangedBindings(binding, apiIdentity); + return receipt; + }); + if (persisted == null) { + throw new PublicationRejectedException("Account JWT JWKS API receipt was not persisted"); + } + return persisted; + } + + private CurrentGeneration loadCurrentGeneration(Binding binding, BindingIdentity apiIdentity) { + CurrentGeneration current = + accountTransaction.execute( + status -> { + GenerationResult result = + desiredStateRepository.readCurrentGenerationResult( + binding.accountBinding(), trustFence(binding)); + GenerationRequest request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + Optional publication = + publicationRepository.readCurrentPublication( + binding.accountBinding(), trustFence(binding)); + if (!result.binding().equals(binding.accountBinding()) + || !result.trustFence().equals(trustFence(binding)) + || !request.operationId().equals(result.operationId()) + || !request.generationReceiptDigest().equals(result.receiptDigest())) { + throw new PublicationRejectedException( + "Account JWT generation receipt does not match the current protected binding"); + } + requireUnchangedBindings(binding, apiIdentity); + return new CurrentGeneration(result, request, publication); + }); + if (current == null) { + throw new PublicationRejectedException("Current Account JWT generation is unavailable"); + } + return current; + } + + private Binding requireCurrentMaterializerBinding() { + Binding current = materializerTrustBinding.current().orElse(null); + if (current == null) { + throw new PublicationRejectedException( + "Protected Account JWT materializer binding is unavailable"); + } + return current; + } + + private static BindingIdentity requireMatchingApiIdentity( + Binding materializerBinding, BindingIdentity apiIdentity) { + if (apiIdentity == null + || !materializerBinding.environmentId().equals(apiIdentity.environmentId()) + || !materializerBinding.clusterId().equals(apiIdentity.clusterId()) + || !materializerBinding.namespace().equals(apiIdentity.namespace()) + || !materializerBinding + .expectedClusterIncarnationUid() + .equals(apiIdentity.expectedClusterIncarnationUid()) + || !materializerBinding.expectedNamespaceUid().equals(apiIdentity.expectedNamespaceUid()) + || apiIdentity.bindingDigest() == null + || apiIdentity.configRevision() == null) { + throw new PublicationRejectedException( + "Protected Account materializer and ConfigMap API bindings disagree"); + } + return apiIdentity; + } + + private void requireUnchangedBindings(Binding expected, BindingIdentity expectedApiIdentity) { + if (materializerTrustBinding.current().filter(expected::equals).isEmpty() + || !expectedApiIdentity.equals(configMapClient.identity())) { + throw new PublicationRejectedException( + "Protected Account JWT publication trust changed during the operation"); + } + } + + private static void requireIntentApiIdentity( + PrepublicationIntent intent, BindingIdentity apiIdentity) { + if (!intent.apiBindingDigest().equals(apiIdentity.bindingDigest()) + || !intent.apiConfigRevision().equals(apiIdentity.configRevision())) { + throw new PublicationRejectedException( + "Protected Account ConfigMap API trust changed for the current JWT operation"); + } + } + + private static void requirePublishedProjection( + PrepublicationIntent intent, ConfigMapSnapshot snapshot) { + if (!intent.configMapUid().equals(snapshot.uid()) + || !intent + .jwksJson() + .equals(snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY)) + || !intent + .generationMarkerJson() + .equals( + snapshot + .data() + .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY))) { + throw new PublicationRejectedException( + "Current public JWT ConfigMap no longer matches Account's immutable receipt"); + } + } + + private static void requireRetrySnapshot( + PrepublicationIntent intent, ConfigMapSnapshot snapshot) { + if (!intent.configMapUid().equals(snapshot.uid())) { + throw new PublicationRejectedException( + "Account public JWKS ConfigMap UID changed after intent creation"); + } + if (intent + .jwksJson() + .equals(snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY)) + && intent + .generationMarkerJson() + .equals( + snapshot + .data() + .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY))) { + return; + } + if (!intent.expectedResourceVersion().equals(snapshot.resourceVersion()) + || !intent + .expectedSnapshotDigest() + .equals(AccountJwtJwksPublicationRepository.snapshotDigest(snapshot.data()))) { + throw new PublicationRejectedException( + "Account public JWKS ConfigMap changed after immutable intent creation"); + } + } + + private static Map desiredData(PrepublicationIntent intent) { + Map data = new LinkedHashMap<>(); + data.put(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, intent.jwksJson()); + data.put( + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + intent.generationMarkerJson()); + return Map.copyOf(data); + } + + private static String appendPendingPublicKey(String sourceJwks, GenerationResult result) { + JsonNode root = parseStrictJson(sourceJwks, AccountJwtJwksPublicationRepository.MAX_JWKS_BYTES); + boolean supportedRoot = root.size() == JWKS_ROOT_FIELDS.size(); + for (Map.Entry field : root.properties()) { + supportedRoot &= JWKS_ROOT_FIELDS.contains(field.getKey()); + } + if (!supportedRoot) { + throw new PublicationRejectedException("Existing Account JWKS has an unsupported shape"); + } + JsonNode keys = root.get("keys"); + if (keys == null || !keys.isArray() || keys.size() >= MAX_KEYS) { + throw new PublicationRejectedException( + "Existing Account JWKS is missing or at its key limit"); + } + Set kids = new HashSet<>(); + List canonicalKeys = new ArrayList<>(keys.size() + 1); + for (JsonNode jwk : keys) { + validateRetainedJwk(jwk); + String kid = jwk.get("kid").textValue(); + if (!kids.add(kid) || kid.equals(result.targetKid())) { + throw new PublicationRejectedException( + "Existing Account JWKS has a duplicate or conflicting key identifier"); + } + canonicalKeys.add(canonicalJson(jwk.toString())); + } + JsonNode pending = parseStrictJson(result.publicJwkJson(), 8 * 1024); + validateRetainedJwk(pending); + if (!result.targetKid().equals(pending.get("kid").textValue()) + || !kids.add(result.targetKid())) { + throw new PublicationRejectedException( + "Account generation receipt has a conflicting public key identifier"); + } + canonicalKeys.add(canonicalJson(result.publicJwkJson())); + String jwks = "{\"keys\":[" + String.join(",", canonicalKeys) + "]}"; + if (jwks.getBytes(StandardCharsets.UTF_8).length + > AccountJwtJwksPublicationRepository.MAX_JWKS_BYTES) { + throw new PublicationRejectedException("Account public JWKS exceeds its storage bound"); + } + return jwks; + } + + private static void validateRetainedJwk(JsonNode jwk) { + if (jwk == null || !jwk.isObject() || jwk.size() < 6 || jwk.size() > 7) { + throw new PublicationRejectedException("Existing Account JWKS contains a malformed key"); + } + for (Map.Entry field : jwk.properties()) { + if (!JWK_FIELDS.contains(field.getKey())) { + throw new PublicationRejectedException( + "Existing Account JWKS contains an unsupported or private key field"); + } + } + String kty = requiredText(jwk, "kty", 8); + String use = requiredText(jwk, "use", 8); + String alg = requiredText(jwk, "alg", 8); + String kid = requiredText(jwk, "kid", 64); + String n = requiredText(jwk, "n", 4096); + String e = requiredText(jwk, "e", 16); + if (!"RSA".equals(kty) + || !"sig".equals(use) + || !"RS256".equals(alg) + || !KID.matcher(kid).matches()) { + throw new PublicationRejectedException("Existing Account JWKS contains an unsupported key"); + } + JsonNode keyOps = jwk.get("key_ops"); + if (keyOps != null + && (!keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue()))) { + throw new PublicationRejectedException("Existing Account JWKS key operations are malformed"); + } + byte[] modulus = decodeBase64Url(n, 2048); + byte[] exponent = decodeBase64Url(e, 8); + try { + if (modulus.length == 0 || modulus[0] == 0 || exponent.length == 0 || exponent[0] == 0) { + throw new PublicationRejectedException( + "Existing Account JWKS RSA parameters are malformed"); + } + BigInteger modulusValue = new BigInteger(1, modulus); + BigInteger exponentValue = new BigInteger(1, exponent); + if (modulusValue.bitLength() < MIN_RSA_BITS + || modulusValue.bitLength() > MAX_RSA_BITS + || !modulusValue.testBit(0) + || !BigInteger.valueOf(65_537).equals(exponentValue)) { + throw new PublicationRejectedException( + "Existing Account JWKS RSA parameters are unsupported"); + } + KeyFactory.getInstance("RSA") + .generatePublic(new RSAPublicKeySpec(modulusValue, exponentValue)); + } catch (Exception ex) { + if (ex instanceof PublicationRejectedException rejected) { + throw rejected; + } + throw new PublicationRejectedException("Existing Account JWKS RSA parameters are invalid"); + } finally { + Arrays.fill(modulus, (byte) 0); + Arrays.fill(exponent, (byte) 0); + } + } + + private static String generationMarker( + GenerationResult result, GenerationRequest request, BindingIdentity apiIdentity) { + Map marker = new LinkedHashMap<>(); + marker.put("schemaVersion", 1); + marker.put("phase", "PREPUBLISHED"); + marker.put("operationId", result.operationId().toString()); + marker.put("operationDigest", result.operationDigest()); + marker.put("generationRequestDigest", result.generationRequestDigest()); + marker.put("generationReceiptDigest", result.receiptDigest()); + Map binding = new LinkedHashMap<>(); + binding.put("environmentId", result.binding().environmentId()); + binding.put("clusterId", result.binding().clusterId()); + binding.put("namespace", result.binding().namespace()); + binding.put( + "expectedClusterIncarnationUid", result.trustFence().expectedClusterIncarnationUid()); + binding.put("expectedNamespaceUid", result.trustFence().expectedNamespaceUid()); + binding.put("trustBindingDigest", result.trustFence().bindingDigest()); + binding.put("trustConfigRevision", result.trustFence().configRevision()); + binding.put("apiBindingDigest", apiIdentity.bindingDigest()); + binding.put("apiConfigRevision", apiIdentity.configRevision()); + marker.put("binding", binding); + marker.put("publicConfigMap", Map.of("name", "jwt-jwks")); + marker.put("expectedDurableActive", activeMarker(request.expectedActive())); + marker.put("expectedPublishedActive", activeMarker(request.expectedPublishedActive())); + Map pending = new LinkedHashMap<>(); + pending.put("generation", result.targetGeneration()); + pending.put("kid", result.targetKid()); + pending.put("algorithm", result.targetAlgorithm()); + pending.put("publicKeyFingerprint", result.publicKeyFingerprint()); + marker.put("pending", pending); + return canonicalJson(marker); + } + + private static Map activeMarker( + Optional active) { + Map marker = new LinkedHashMap<>(); + marker.put("present", active.isPresent()); + active.ifPresent( + signer -> { + marker.put("generation", signer.generation()); + marker.put("kid", signer.kid()); + }); + return marker; + } + + private static JsonNode parseStrictJson(String json, int maxBytes) { + if (json == null || json.isBlank() || json.getBytes(StandardCharsets.UTF_8).length > maxBytes) { + throw new PublicationRejectedException("Account public JWT JSON is missing or oversized"); + } + try { + JsonNode node = STRICT_JSON.readTree(json); + if (node == null || !node.isObject()) { + throw new PublicationRejectedException("Account public JWT JSON has an unsupported shape"); + } + return node; + } catch (PublicationRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new PublicationRejectedException("Account public JWT JSON is malformed"); + } + } + + private static String requiredText(JsonNode object, String field, int maxLength) { + JsonNode value = object.get(field); + if (value == null + || !value.isTextual() + || value.textValue().isEmpty() + || value.textValue().length() > maxLength) { + throw new PublicationRejectedException("Existing Account JWKS key is malformed"); + } + return value.textValue(); + } + + private static byte[] decodeBase64Url(String value, int maxBytes) { + if (value == null + || value.isEmpty() + || value.contains("=") + || !value.matches("[A-Za-z0-9_-]+")) { + throw new PublicationRejectedException("Existing Account JWKS RSA parameters are malformed"); + } + try { + byte[] decoded = Base64.getUrlDecoder().decode(value); + if (decoded.length > maxBytes + || !Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(value)) { + Arrays.fill(decoded, (byte) 0); + throw new PublicationRejectedException( + "Existing Account JWKS RSA parameters are malformed"); + } + return decoded; + } catch (IllegalArgumentException ex) { + throw new PublicationRejectedException("Existing Account JWKS RSA parameters are malformed"); + } + } + + private static String canonicalJson(String json) { + try { + return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new PublicationRejectedException("Account public JWT JSON canonicalization failed"); + } + } + + private static String canonicalJson(Object value) { + try { + return canonicalJson(STRICT_JSON.writeValueAsString(value)); + } catch (Exception ex) { + throw new PublicationRejectedException("Account public JWT marker encoding failed"); + } + } + + private static byte[] readMountedFile(Path configuredRoot, Path relativePath, int maxBytes) { + try { + if (configuredRoot == null + || relativePath == null + || relativePath.isAbsolute() + || relativePath.normalize().startsWith("..")) { + throw new IOException("Mounted file path is invalid"); + } + Path root = configuredRoot.toRealPath(); + if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Mounted root is unavailable"); + } + Path unresolved = root.resolve(relativePath).normalize(); + if (!unresolved.startsWith(root)) { + throw new IOException("Mounted file escapes its projection"); + } + Path file = unresolved.toRealPath(); + if (!file.startsWith(root) || !Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Mounted file is unavailable"); + } + BasicFileAttributes before = + Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (before.size() <= 0 || before.size() > maxBytes) { + throw new IOException("Mounted file size is invalid"); + } + 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 new IOException("Mounted file changed while being read"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Mounted file changed while being read"); + } + } + BasicFileAttributes after = + Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || !Objects.equals(before.fileKey(), after.fileKey()) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime())) { + Arrays.fill(bytes, (byte) 0); + throw new IOException("Mounted file changed while being read"); + } + return bytes; + } catch (IOException | RuntimeException ex) { + throw new PublicationRejectedException( + "Mounted Account JWT public projection is unavailable or invalid"); + } + } + + private static String strictUtf8(byte[] bytes) { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException ex) { + throw new PublicationRejectedException("Mounted Account JWT public projection is not UTF-8"); + } + } + + private static String sha256(byte[] value) { + try { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value)); + } catch (java.security.NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private record CurrentGeneration( + GenerationResult result, + GenerationRequest request, + Optional publication) {} + + /** Fixed filesystem projections; production paths are not request inputs. */ + record MountedProjection( + Path privateMountRoot, + Path pendingBundlePath, + Path publicMountRoot, + Path jwksPath, + Path markerPath) { + MountedProjection { + Objects.requireNonNull(privateMountRoot); + Objects.requireNonNull(pendingBundlePath); + Objects.requireNonNull(publicMountRoot); + Objects.requireNonNull(jwksPath); + Objects.requireNonNull(markerPath); + if (pendingBundlePath.isAbsolute() + || jwksPath.isAbsolute() + || markerPath.isAbsolute() + || pendingBundlePath.normalize().startsWith("..") + || jwksPath.normalize().startsWith("..") + || markerPath.normalize().startsWith("..")) { + throw new IllegalArgumentException("JWT mounted projection paths must be relative"); + } + } + } + + /** Safe generic failure; never includes a key, ConfigMap response body, or mounted path. */ + public static final class PublicationRejectedException extends IllegalStateException { + public PublicationRejectedException(String message) { + super(message); + } + } +} 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 new file mode 100644 index 0000000000..03f9b957c7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java @@ -0,0 +1,784 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.IOException; +import java.math.BigInteger; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +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.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +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 org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned authenticated read adapter for the current public JWKS publication. + * + *

The cache pin is derived from Account's root-protected Kubernetes API binding and exact + * Account-owned publication evidence. The first receipt-backed PREPUBLISHED key can be served to + * readiness probes before a signer is committed, but is never represented as active authority. + * During ordinary prepublication of a next key, the prior committed key remains the only active + * signer while the exact new public set may be served for validation overlap. PREPARED and + * unexplained resource changes deny. This adapter exposes only public JWKS bytes and grants no + * signing, registry, readiness, or admission authority. + */ +public final class AccountJwtJwksTrustedSource + implements AccountPublicJwksCache.TrustedPublicJwksSource { + private static final int MAX_JWKS_BYTES = 256 * 1024; + private static final int MAX_MARKER_BYTES = 16 * 1024; + 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 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"); + private static final java.util.Set OPTIONAL_JWK_FIELDS = java.util.Set.of("key_ops"); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountJwtJwksConfigMapClient configMapClient; + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPublicationRepository publicationRepository; + private final TransactionTemplate accountTransaction; + private final Object pinMonitor = new Object(); + + private volatile TrustedPin trustedPin; + + /** Constructs an inactive adapter over Account's real protected API and owner-recorded state. */ + public AccountJwtJwksTrustedSource( + AccountJwtJwksConfigMapClient configMapClient, + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + PlatformTransactionManager transactionManager) { + this.configMapClient = + Objects.requireNonNull(configMapClient, "Account ConfigMap client is required"); + this.materializerTrustBinding = + Objects.requireNonNull(materializerTrustBinding, "Protected Account trust is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Account signer repository is required"); + this.publicationRepository = + Objects.requireNonNull(publicationRepository, "Account publication repository is required"); + this.accountTransaction = + new TransactionTemplate( + Objects.requireNonNull(transactionManager, "Account transaction manager is required")); + this.accountTransaction.setReadOnly(false); + } + + /** + * Establishes the immutable cache pin from a coherent, protected Account read. A cache owner + * obtains its expected source identity here; it is not accepted as caller-supplied evidence. + */ + public SourceIdentity sourceIdentity() { + TrustedPin current = trustedPin; + if (current != null) { + return current.sourceIdentity(); + } + synchronized (pinMonitor) { + current = trustedPin; + if (current == null) { + VerifiedSource verified = readVerifiedSource(); + current = verified.pin(); + trustedPin = current; + } + } + return current.sourceIdentity(); + } + + /** + * Derives one key's RFC 7638 fingerprint from a snapshot already loaded through this trusted + * source. It compares the immutable pin and grants no signer, registry, or token authority. + */ + static Optional publicKeyFingerprint( + PublicJwksSnapshot snapshot, SourceIdentity expectedSourceIdentity, String kid) { + if (snapshot == null + || expectedSourceIdentity == null + || !expectedSourceIdentity.equals(snapshot.sourceIdentity()) + || kid == null + || !kid.matches("[A-Za-z0-9_-]{1,64}")) { + throw rejected(); + } + Map fingerprints = + publicKeyFingerprints(new String(snapshot.jwksBytes(), StandardCharsets.UTF_8)); + return Optional.ofNullable(fingerprints.get(kid)); + } + + /** + * Loads one exact public JWKS snapshot after checking Account trust and receipt readback twice. + */ + @Override + public PublicJwksSnapshot load() { + TrustedPin expected = trustedPin; + if (expected == null) { + throw rejected(); + } + VerifiedSource verified = readVerifiedSource(); + if (!expected.equals(verified.pin())) { + throw rejected(); + } + 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(); + } + + OwnerProjection ownerBefore = currentOwnerProjection(materializerBefore, apiBefore); + SourceIdentity pinnedIdentity = + sourceIdentity(materializerBefore, apiBefore, ownerBefore.projection().configMapUid()); + if (alreadyPinned != null && !alreadyPinned.sourceIdentity().equals(pinnedIdentity)) { + throw rejected(); + } + + 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(); + } + + Binding materializerAfter = currentMaterializerBinding(); + BindingIdentity apiAfter = currentApiIdentity(); + if (!materializerBefore.equals(materializerAfter) || !apiBefore.equals(apiAfter)) { + throw rejected(); + } + + OwnerProjection ownerAfter = currentOwnerProjection(materializerAfter, apiAfter); + if (!ownerBefore.equals(ownerAfter)) { + // A concurrent Account lifecycle/publication change is not a coherent source snapshot. + throw unavailable(); + } + 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(); + } + TrustedPin pin = new TrustedPin(materializerBefore, apiBefore, pinnedIdentity); + return new VerifiedSource(pin, jwks); + } + + private Binding currentMaterializerBinding() { + return materializerTrustBinding.current().orElseThrow(AccountJwtJwksTrustedSource::rejected); + } + + private BindingIdentity currentApiIdentity() { + try { + return Objects.requireNonNull(configMapClient.identity()); + } catch (RuntimeException rejectedBinding) { + throw rejected(); + } + } + + private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity api) { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw rejected(); + } + try { + OwnerProjection result = + accountTransaction.execute( + status -> { + DesiredState enrolled = + desiredStateRepository + .readEnrollmentState(binding.accountBinding()) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + if (enrolled.durableActive().isEmpty() && enrolled.publishedActive().isEmpty()) { + return initialPrepublicationProjection(enrolled, binding, api); + } + CommittedSignerEvidence committed = + desiredStateRepository + .readCurrentCommittedSigner( + binding.accountBinding(), + trustFence(binding), + api.bindingDigest(), + api.configRevision()) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + ActiveSigner currentActive = + new ActiveSigner( + committed.promotion().targetGeneration(), + committed.promotion().targetKid()); + PublishedProjection projection = committedProjection(committed); + if (committed.desiredState().generationOperationId().isEmpty()) { + return new OwnerProjection(committed, projection); + } + + var request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED) { + return new OwnerProjection(committed, projection); + } + Optional currentPublication = + publicationRepository.readCurrentPublication( + binding.accountBinding(), trustFence(binding)); + if (currentPublication.isEmpty()) { + return new OwnerProjection(committed, projection); + } + PublicationEvidence evidence = currentPublication.orElseThrow(); + requirePublicationBinding(evidence, binding, api); + PrepublicationIntent intent = evidence.intent(); + var receipt = + evidence.receipt().orElseThrow(AccountJwtJwksTrustedSource::unavailable); + if (!intent.operationId().equals(request.operationId()) + || !intent.operationDigest().equals(request.operationDigest()) + || !intent.generationRequestDigest().equals(request.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(request.generationReceiptDigest()) + || !intent.targetGeneration().equals(request.targetGeneration()) + || !intent.targetKid().equals(request.targetKid()) + || !intent.publicKeyFingerprint().equals(request.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(Optional.of(currentActive)) + || !intent.expectedPublishedActive().equals(Optional.of(currentActive)) + || !intent.configMapUid().equals(committed.promotion().publicConfigMapUid()) + || !receipt.configMapUid().equals(committed.promotion().publicConfigMapUid()) + || !intent.apiBindingDigest().equals(api.bindingDigest()) + || !intent.apiConfigRevision().equals(api.configRevision())) { + throw rejected(); + } + requireRetainedPublicKeySet(committed, intent); + return new OwnerProjection( + committed, + new PublishedProjection( + intent.configMapUid(), + receipt.observedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + receipt.publicDataDigest())); + }); + if (result == null) { + throw unavailable(); + } + return result; + } catch (RuntimeException ownerStateUnavailable) { + if (ownerStateUnavailable instanceof SourceUnavailableException unavailable) { + throw unavailable; + } + if (ownerStateUnavailable instanceof SourceRejectedException) { + throw ownerStateUnavailable; + } + throw rejected(); + } + } + + /** + * 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) { + if (!enrolled.binding().equals(binding.accountBinding()) + || enrolled.preparedOperationId().isPresent() + || enrolled.generationOperationId().isEmpty() + || enrolled.enrollmentIdentity().isEmpty()) { + throw rejected(); + } + EnrollmentIdentity enrollment = enrolled.enrollmentIdentity().orElseThrow(); + if (!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())) { + throw rejected(); + } + + GenerationRequest request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + GenerationResult result = + desiredStateRepository.readCurrentGenerationResult( + binding.accountBinding(), trustFence(binding)); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED + || !request.expectedActive().isEmpty() + || !request.expectedPublishedActive().isEmpty() + || !enrolled.generationOperationId().equals(Optional.of(request.operationId())) + || !request.binding().equals(binding.accountBinding()) + || !request.trustFence().equals(trustFence(binding)) + || !result.binding().equals(binding.accountBinding()) + || !result.trustFence().equals(trustFence(binding)) + || request.desiredStateVersion() != result.desiredStateVersion() + || !request.operationId().equals(result.operationId()) + || !request.operationDigest().equals(result.operationDigest()) + || !request.generationRequestDigest().equals(result.generationRequestDigest()) + || !request.targetGeneration().equals(result.targetGeneration()) + || !request.targetKid().equals(result.targetKid()) + || !request.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !request.publicJwkJson().equals(result.publicJwkJson()) + || !"RS256".equals(result.targetAlgorithm())) { + throw rejected(); + } + + PublicationEvidence evidence = + publicationRepository + .readCurrentPublication(binding.accountBinding(), trustFence(binding)) + .orElseThrow(AccountJwtJwksTrustedSource::unavailable); + requirePublicationBinding(evidence, binding, api); + PrepublicationIntent intent = evidence.intent(); + var receipt = evidence.receipt().orElseThrow(AccountJwtJwksTrustedSource::unavailable); + if (!intent.operationId().equals(result.operationId()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.expectedDurableActive().isEmpty() + || !intent.expectedPublishedActive().isEmpty() + || !intent.configMapUid().equals(enrollment.publicConfigMapUid()) + || !receipt.configMapUid().equals(enrollment.publicConfigMapUid()) + || !intent.apiBindingDigest().equals(enrollment.apiBindingDigest()) + || !intent.apiConfigRevision().equals(enrollment.apiConfigRevision()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw rejected(); + } + Map publicKeys = publicKeyFingerprints(intent.jwksJson()); + if (publicKeys.size() != 1 + || !result.publicKeyFingerprint().equals(publicKeys.get(result.targetKid()))) { + throw rejected(); + } + requireInitialPrepublicationMarker(intent, result, binding, api); + return new OwnerProjection( + null, + new PublishedProjection( + intent.configMapUid(), + receipt.observedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + receipt.publicDataDigest())); + } + + private static void requireInitialPrepublicationMarker( + PrepublicationIntent intent, GenerationResult result, Binding binding, BindingIdentity api) { + try { + JsonNode marker = STRICT_JSON.readTree(intent.generationMarkerJson()); + JsonNode markerBinding = marker == null ? null : marker.get("binding"); + JsonNode publicConfigMap = marker == null ? null : marker.get("publicConfigMap"); + JsonNode pending = marker == null ? null : marker.get("pending"); + JsonNode durable = marker == null ? null : marker.get("expectedDurableActive"); + JsonNode published = marker == null ? null : marker.get("expectedPublishedActive"); + if (marker == null + || !marker.isObject() + || !hasExactFields( + marker, + java.util.Set.of( + "schemaVersion", + "phase", + "operationId", + "operationDigest", + "generationRequestDigest", + "generationReceiptDigest", + "binding", + "publicConfigMap", + "expectedDurableActive", + "expectedPublishedActive", + "pending")) + || !marker.get("schemaVersion").isIntegralNumber() + || marker.get("schemaVersion").intValue() != 1 + || !"PREPUBLISHED".equals(requiredText(marker, "phase")) + || !intent.operationId().toString().equals(requiredText(marker, "operationId")) + || !intent.operationDigest().equals(requiredText(marker, "operationDigest")) + || !intent + .generationRequestDigest() + .equals(requiredText(marker, "generationRequestDigest")) + || !intent + .generationReceiptDigest() + .equals(requiredText(marker, "generationReceiptDigest")) + || !hasExactFields( + markerBinding, + java.util.Set.of( + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "trustBindingDigest", + "trustConfigRevision", + "apiBindingDigest", + "apiConfigRevision")) + || !binding.environmentId().equals(requiredText(markerBinding, "environmentId")) + || !binding.clusterId().equals(requiredText(markerBinding, "clusterId")) + || !binding.namespace().equals(requiredText(markerBinding, "namespace")) + || !binding + .expectedClusterIncarnationUid() + .equals(requiredText(markerBinding, "expectedClusterIncarnationUid")) + || !binding + .expectedNamespaceUid() + .equals(requiredText(markerBinding, "expectedNamespaceUid")) + || !binding.bindingDigest().equals(requiredText(markerBinding, "trustBindingDigest")) + || !binding.configRevision().equals(requiredText(markerBinding, "trustConfigRevision")) + || !api.bindingDigest().equals(requiredText(markerBinding, "apiBindingDigest")) + || !api.configRevision().equals(requiredText(markerBinding, "apiConfigRevision")) + || !hasExactFields(publicConfigMap, java.util.Set.of("name")) + || !AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME.equals( + 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")) + || !"RS256".equals(requiredText(pending, "algorithm")) + || !result.publicKeyFingerprint().equals(requiredText(pending, "publicKeyFingerprint")) + || !inactiveMarker(durable) + || !inactiveMarker(published)) { + throw rejected(); + } + } catch (RuntimeException malformed) { + throw rejected(); + } + } + + private static boolean inactiveMarker(JsonNode marker) { + return hasExactFields(marker, java.util.Set.of("present")) + && marker.get("present").isBoolean() + && !marker.get("present").booleanValue(); + } + + private static void requireBindingsAgree(Binding materializer, BindingIdentity api) { + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid()) + || api.bindingDigest() == null + || api.configRevision() == null + || api.expectedApiUsername() == null + || !api.expectedApiUsername() + .equals( + ACCOUNT_SERVICE_USERNAME_PREFIX + + materializer.namespace() + + ":" + + ACCOUNT_SERVICE_NAME)) { + throw rejected(); + } + URI endpoint; + try { + endpoint = URI.create(api.apiServerUrl()); + } catch (RuntimeException malformedEndpoint) { + throw rejected(); + } + if (!"https".equalsIgnoreCase(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() <= 0 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null + && !endpoint.getRawPath().isEmpty() + && !"/".equals(endpoint.getRawPath())) + || api.tlsServerName() == null + || !endpoint.getHost().equalsIgnoreCase(api.tlsServerName()) + || api.servingCaSha256() == null) { + throw rejected(); + } + } + + private static void requirePublicationBinding( + PublicationEvidence evidence, Binding materializer, BindingIdentity api) { + PrepublicationIntent intent = evidence.intent(); + if (!intent.binding().equals(materializer.accountBinding()) + || !intent.trustFence().equals(trustFence(materializer)) + || !AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME.equals(intent.configMapName()) + || !intent.apiBindingDigest().equals(api.bindingDigest()) + || !intent.apiConfigRevision().equals(api.configRevision()) + || !AccountJwtJwksPublicationRepository.publicDataDigest( + intent.jwksJson(), intent.generationMarkerJson()) + .equals(intent.publicDataDigest())) { + throw rejected(); + } + PublicationReceipt receipt = evidence.receipt().orElse(null); + if (receipt != null + && (!receipt.operationId().equals(intent.operationId()) + || !receipt.binding().equals(materializer.accountBinding()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !receipt.configMapUid().equals(intent.configMapUid()) + || !receipt.publicDataDigest().equals(intent.publicDataDigest()) + || !receipt.expectedResourceVersion().equals(intent.expectedResourceVersion()))) { + throw rejected(); + } + } + + private static PublishedProjection committedProjection(CommittedSignerEvidence committed) { + PromotionOperationEvidence promotion = committed.promotion(); + var receipt = committed.publicReceipt(); + String dataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson()); + if (!promotion.publicConfigMapUid().equals(receipt.configMapUid()) + || !promotion + .activeJwksObservedResourceVersion() + .orElseThrow() + .equals(receipt.observedResourceVersion()) + || !promotion.activeJwksPublicDataDigest().orElseThrow().equals(dataDigest) + || !receipt.publicDataDigest().equals(dataDigest)) { + throw rejected(); + } + return new PublishedProjection( + receipt.configMapUid(), + receipt.observedResourceVersion(), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson(), + dataDigest); + } + + private static void requireRetainedPublicKeySet( + CommittedSignerEvidence committed, PrepublicationIntent intent) { + Map previousKeys = + publicKeyFingerprints(committed.promotion().expectedPublicJwksJson()); + Map currentKeys = publicKeyFingerprints(intent.jwksJson()); + if (previousKeys.isEmpty() || currentKeys.size() < previousKeys.size()) { + throw rejected(); + } + if (new BigInteger(intent.targetGeneration()) + .compareTo(new BigInteger(committed.promotion().targetGeneration())) + <= 0) { + throw rejected(); + } + for (Map.Entry previous : previousKeys.entrySet()) { + if (!previous.getValue().equals(currentKeys.get(previous.getKey()))) { + throw rejected(); + } + } + if (!intent.publicKeyFingerprint().equals(currentKeys.get(intent.targetKid())) + || !committed + .promotion() + .targetPublicKeyFingerprint() + .equals(currentKeys.get(committed.promotion().targetKid()))) { + throw rejected(); + } + } + + private static Map publicKeyFingerprints(String jwksJson) { + try { + if (jwksJson == null + || jwksJson.isBlank() + || jwksJson.getBytes(StandardCharsets.UTF_8).length > MAX_JWKS_BYTES) { + throw new IllegalArgumentException(); + } + JsonNode root = STRICT_JSON.readTree(jwksJson); + if (root == null || !root.isObject() || !hasExactFields(root, JWKS_FIELDS)) { + throw new IllegalArgumentException(); + } + JsonNode keys = root.get("keys"); + if (keys == null || !keys.isArray() || keys.isEmpty() || keys.size() > MAX_KEYS) { + throw new IllegalArgumentException(); + } + Map fingerprints = new LinkedHashMap<>(); + for (JsonNode key : keys) { + if (!hasRequiredAndAllowedFields(key, REQUIRED_JWK_FIELDS, OPTIONAL_JWK_FIELDS)) { + throw new IllegalArgumentException(); + } + String kty = requiredText(key, "kty"); + String use = requiredText(key, "use"); + String alg = requiredText(key, "alg"); + String kid = requiredText(key, "kid"); + String modulus = requiredText(key, "n"); + String exponent = requiredText(key, "e"); + JsonNode keyOps = key.get("key_ops"); + if (!"RSA".equals(kty) + || !"sig".equals(use) + || !"RS256".equals(alg) + || !kid.matches("[A-Za-z0-9_-]{1,64}") + || (keyOps != null + && (!keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())))) { + throw new IllegalArgumentException(); + } + String preimage = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + STRICT_JSON.writeValueAsString( + Map.of("e", exponent, "kty", kty, "n", modulus))), + StandardCharsets.UTF_8); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.getBytes(StandardCharsets.UTF_8))); + if (fingerprints.putIfAbsent(kid, fingerprint) != null) { + throw new IllegalArgumentException(); + } + } + return Map.copyOf(fingerprints); + } catch (IOException | NoSuchAlgorithmException | RuntimeException malformed) { + throw rejected(); + } + } + + private static String requiredText(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) { + throw new IllegalArgumentException(); + } + return value.textValue(); + } + + private static boolean hasExactFields(JsonNode object, java.util.Set expected) { + if (object == null || !object.isObject() || object.size() != expected.size()) { + return false; + } + for (Map.Entry property : object.properties()) { + if (!expected.contains(property.getKey())) { + return false; + } + } + return true; + } + + private static boolean hasRequiredAndAllowedFields( + JsonNode object, java.util.Set required, java.util.Set optional) { + if (object == null || !object.isObject() || object.size() < required.size()) { + return false; + } + for (String field : required) { + if (!object.has(field)) { + return false; + } + } + for (Map.Entry property : object.properties()) { + if (!required.contains(property.getKey()) && !optional.contains(property.getKey())) { + return false; + } + } + return true; + } + + private static void requireExactReadback(PublishedProjection projection, ConfigMapSnapshot live) { + 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 + || marker.getBytes(StandardCharsets.UTF_8).length > MAX_MARKER_BYTES + || !AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker) + .equals(projection.publicDataDigest())) { + throw rejected(); + } + } + + private static SourceIdentity sourceIdentity( + Binding materializer, BindingIdentity api, String configMapUid) { + try { + return new SourceIdentity( + materializer.environmentId(), + materializer.clusterId(), + materializer.expectedClusterIncarnationUid(), + materializer.namespace(), + materializer.expectedNamespaceUid(), + configMapUid, + api.configRevision(), + api.apiServerUrl(), + api.servingCaSha256()); + } catch (RuntimeException invalidIdentity) { + throw rejected(); + } + } + + private void requireUnchangedProtectedTrust(Binding expected, BindingIdentity expectedApi) { + Binding currentMaterializer = currentMaterializerBinding(); + BindingIdentity currentApi = currentApiIdentity(); + if (!expected.equals(currentMaterializer) || !expectedApi.equals(currentApi)) { + throw rejected(); + } + } + + private static boolean isTemporaryApiFailure(int statusCode) { + return statusCode == 0 || statusCode == 408 || statusCode == 429 || statusCode >= 500; + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static SourceUnavailableException unavailable() { + return new SourceUnavailableException(); + } + + private static SourceRejectedException rejected() { + return new SourceRejectedException(); + } + + private static final class SourceRejectedException extends IllegalStateException { + private SourceRejectedException() { + super("Account trusted public JWKS source was rejected"); + } + } + + private record TrustedPin( + Binding materializerBinding, BindingIdentity apiIdentity, SourceIdentity sourceIdentity) {} + + private record OwnerProjection( + CommittedSignerEvidence committedSigner, PublishedProjection projection) {} + + private record PublishedProjection( + String configMapUid, + String resourceVersion, + String jwksJson, + String markerJson, + String publicDataDigest) {} + + private record VerifiedSource(TrustedPin pin, byte[] jwksBytes) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java new file mode 100644 index 0000000000..c001802deb --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java @@ -0,0 +1,554 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.HexFormat; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.DeliveryClaim; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ExpectedPod; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.OwnerProbeEvidence; +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.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ExpectedIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.SignedProbeDigest; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Dormant, owner-internal producer for durable Account readiness-probe plans and constrained + * pending-key signatures. + * + *

This class is intentionally not a Spring component. Its per-invocation callback receives the + * exact compact probe only for the duration of the call; this producer persists only its hash. The + * caller must supply the already-persisted one-shot delivery claim. The separate readiness route + * may record an authenticated non-authorizing observation, but neither path can promote a signer. + */ +public final class AccountJwtReadinessProbeService { + private static final Path PRIVATE_MOUNT = privateSignerMount(); + + private static final Path PRIVATE_PENDING_BUNDLE = Path.of("pending.key"); + + private static final Path PUBLIC_MOUNT = publicJwksMount(); + + private static final Path PUBLIC_JWKS = Path.of("jwks.json"); + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The interim private signer projection is intentionally fixed to Account's protected read-only mount.") + private static Path privateSignerMount() { + return Path.of("/var/run/secrets/firemud/jwt"); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "The public JWKS projection is intentionally fixed to Account's read-only validator-consumed mount.") + private static Path publicJwksMount() { + return Path.of("/var/run/secrets/firemud/jwks"); + } + + private final AccountJwtReadinessProbeRepository repository; + private final TransactionTemplate accountTransaction; + private final Clock clock; + private final AccountJwtValidatorInventorySource inventorySource; + private final Path privateMount; + private final Path privateBundle; + private final Path publicMount; + private final Path publicJwks; + + public AccountJwtReadinessProbeService( + AccountJwtReadinessProbeRepository repository, + TransactionTemplate accountTransaction, + Clock clock) { + this( + repository, + accountTransaction, + clock, + PRIVATE_MOUNT, + PRIVATE_PENDING_BUNDLE, + PUBLIC_MOUNT, + PUBLIC_JWKS); + } + + AccountJwtReadinessProbeService( + AccountJwtReadinessProbeRepository repository, + TransactionTemplate accountTransaction, + Clock clock, + Path privateMount, + Path privateBundle, + Path publicMount, + Path publicJwks) { + this( + repository, + accountTransaction, + clock, + privateMount, + privateBundle, + publicMount, + publicJwks, + null); + } + + public AccountJwtReadinessProbeService( + AccountJwtReadinessProbeRepository repository, + TransactionTemplate accountTransaction, + Clock clock, + AccountJwtValidatorInventorySource inventorySource) { + this( + repository, + accountTransaction, + clock, + PRIVATE_MOUNT, + PRIVATE_PENDING_BUNDLE, + PUBLIC_MOUNT, + PUBLIC_JWKS, + Objects.requireNonNull(inventorySource)); + } + + private AccountJwtReadinessProbeService( + AccountJwtReadinessProbeRepository repository, + TransactionTemplate accountTransaction, + Clock clock, + Path privateMount, + Path privateBundle, + Path publicMount, + Path publicJwks, + AccountJwtValidatorInventorySource inventorySource) { + this.repository = Objects.requireNonNull(repository); + this.accountTransaction = Objects.requireNonNull(accountTransaction); + this.clock = Objects.requireNonNull(clock); + this.privateMount = Objects.requireNonNull(privateMount); + this.privateBundle = Objects.requireNonNull(privateBundle); + this.publicMount = Objects.requireNonNull(publicMount); + this.publicJwks = Objects.requireNonNull(publicJwks); + this.inventorySource = inventorySource; + } + + /** Plans the current Account-selected generation operation; no signing occurs in this method. */ + public ReadinessProbePlan planCurrent(Binding binding, TrustFence trust) { + if (inventorySource == null) { + return inTransaction( + () -> repository.planCurrent(binding, trust, Instant.ofEpochSecond(nowEpochSecond()))); + } + ObservationContext observationContext = + inTransaction(() -> repository.readCurrentInventoryObservationContext(binding, trust)); + AccountJwtValidatorInventorySource.InventorySnapshot snapshot = + inventorySource.observe(observationContext); + return inTransaction( + () -> + repository.planCurrent( + binding, trust, Instant.ofEpochSecond(nowEpochSecond()), snapshot)); + } + + /** Rereads protected live inventory before opening the exact receiver target-read transaction. */ + public List readCurrentExpectedPods( + Binding binding, TrustFence trust, ProbeEntry entry) { + AccountJwtValidatorInventorySource.InventorySnapshot snapshot = + observeCurrentInventory(binding, trust, entry.rotationOperationId()); + return inTransaction(() -> repository.readCurrentExpectedPods(binding, trust, entry, snapshot)); + } + + /** + * Reads one exact V2 receiver owner row after observing protected Kubernetes inventory outside + * the short SQL transaction. + */ + public OwnerProbeEvidence readCurrentProbeOwner( + Binding binding, + TrustFence trust, + AccountJwtReadinessProbeOwnerSelector selector, + String authenticatedWorkloadNamespace) { + AccountJwtValidatorInventorySource.InventorySnapshot snapshot = + observeCurrentInventory(binding, trust, selector.rotationOperationId()); + if (!snapshot.namespace().equals(authenticatedWorkloadNamespace)) { + throw new AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException(); + } + return inTransaction( + () -> + repository.readCurrentProbeOwner( + binding, trust, selector, snapshot, authenticatedWorkloadNamespace)); + } + + /** Rereads protected live inventory before committing one immutable per-Pod receipt. */ + public ProbeEntry recordPodAcceptance( + Binding binding, + TrustFence trust, + ProbeEntry entry, + ExpectedPod expectedPod, + AuthenticatedAcceptance acceptance) { + AccountJwtValidatorInventorySource.InventorySnapshot snapshot = + observeCurrentInventory(binding, trust, entry.rotationOperationId()); + return inTransaction( + () -> + repository.recordPodAcceptance( + binding, trust, entry, expectedPod, acceptance, snapshot)); + } + + /** + * Fresh owner observation for promotion callers; never performs I/O while SQL rows are locked. + */ + public AccountJwtValidatorInventorySource.InventorySnapshot observeCurrentInventory() { + if (inventorySource == null) { + throw new AccountJwtValidatorInventorySource.InventoryUnavailableException(); + } + return inventorySource.observe(); + } + + /** Reads only an owner-derived current V2 operation context for the Pod-local receiver proof. */ + ObservationContext readCurrentInventoryObservationContext(Binding binding, TrustFence trust) { + return inTransaction(() -> repository.readCurrentInventoryObservationContext(binding, trust)); + } + + /** Reads only an owner-derived current V2 operation context for the Pod-local receiver proof. */ + ObservationContext readCurrentInventoryObservationContext( + Binding binding, TrustFence trust, UUID operationId) { + return inTransaction( + () -> repository.readCurrentInventoryObservationContext(binding, trust, operationId)); + } + + private AccountJwtValidatorInventorySource.InventorySnapshot observeCurrentInventory( + Binding binding, TrustFence trust, UUID operationId) { + if (inventorySource == null) { + throw new AccountJwtValidatorInventorySource.InventoryUnavailableException(); + } + ObservationContext observationContext = + readCurrentInventoryObservationContext(binding, trust, operationId); + return inventorySource.observe(observationContext); + } + + /** Reads the exact durable operation and latest receipt state without creating evidence. */ + ReadinessProbePlan readCurrentPlan(Binding binding, TrustFence trust, UUID operationId) { + return inTransaction(() -> repository.readCurrentPlan(binding, trust, operationId)); + } + + /** + * Delivers each exact current planned probe once. The compact-token hash and ISSUED transition + * are durably read back before transient delivery, so an authenticated validator can consume the + * current entry synchronously. A persisted signing-attempt hash without ISSUED is ambiguous and + * causes same-operation quarantine rather than token remint or replay. + */ + List issueCurrentPlan( + Binding binding, + TrustFence trust, + UUID operationId, + DeliveryClaim claim, + OwnerInternalProbeDelivery delivery) { + ReadinessProbePlan plan = + inTransaction(() -> repository.readCurrentPlan(binding, trust, operationId)); + if (nowEpochSecond() < plan.notBeforeEpochSecond()) { + throw new AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException(); + } + if (nowEpochSecond() >= plan.expiresAtEpochSecond()) { + return expireAndClean(binding, trust, operationId); + } + Objects.requireNonNull(claim, "Persisted one-shot delivery claim is required"); + Objects.requireNonNull(delivery, "Per-invocation internal delivery is required"); + DeliveryClaim persistedClaim = + inTransaction( + () -> + repository.requireCurrentDeliveryClaim( + binding, trust, plan, claim, Instant.ofEpochSecond(nowEpochSecond()))); + if (persistedClaim == null || !persistedClaim.equals(claim)) { + throw new AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException(); + } + List output = new ArrayList<>(); + for (ProbeEntry planned : plan.entries()) { + ProbeEntry current = currentEntry(binding, trust, operationId, planned); + if (current.state() == ProbeState.ISSUED) { + output.add(current); + continue; + } + if (current.state() == ProbeState.PLANNED && current.compactTokenSha256().isPresent()) { + output.addAll(quarantineCurrent(binding, trust, operationId)); + break; + } + if (current.state() != ProbeState.PLANNED) { + output.add(current); + continue; + } + + long now = nowEpochSecond(); + if (now < current.plannedIssuedAtEpochSecond()) { + throw new AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException(); + } + if (now >= current.expiresAtEpochSecond()) { + output.addAll(expireAndClean(binding, trust, operationId)); + break; + } + + ExpectedIdentity identity = + new ExpectedIdentity( + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + operationId.toString(), + current.targetGeneration(), + current.targetKid(), + plan.targetPublicKeyFingerprint()); + ReadinessProbeSigningSpec spec = + new ReadinessProbeSigningSpec( + current.validatorId(), + current.probeKind(), + current.tokenProfile(), + current.audience(), + current.jti(), + current.targetGeneration(), + current.targetKid(), + current.plannedIssuedAtEpochSecond(), + current.expiresAtEpochSecond()); + + SignedProbeDigest signed; + try { + signed = + AccountMountedJwtSignerBundle.signReadinessProbeDigest( + privateMount, + privateBundle, + publicMount, + publicJwks, + identity, + spec, + (digest, exactCompactJwt) -> { + try { + pinBeforeDelivery(binding, trust, digest); + ProbeEntry issued = + inTransaction( + () -> + repository.recordIssued( + binding, + trust, + digest, + Instant.ofEpochSecond(nowEpochSecond()))); + DeliveryMetadata metadata = DeliveryMetadata.from(plan, issued, digest); + delivery.deliver(metadata, exactCompactJwt); + if (!sha256(exactCompactJwt).equals(metadata.compactTokenSha256())) { + throw new IllegalStateException( + "Transient readiness probe bytes changed in delivery"); + } + } catch (RuntimeException ignored) { + abortAfterDeliveryFailure(binding, trust, operationId); + throw new DeliveryQuarantinedException(); + } + }); + } catch (DeliveryQuarantinedException ex) { + throw ex; + } + try { + ProbeEntry delivered = currentEntry(binding, trust, operationId, current); + if (!exactSignedReadback(plan, current, delivered, signed) + || (delivered.state() != ProbeState.ISSUED + && delivered.state() != ProbeState.VERIFIED)) { + throw new IllegalStateException("Readiness delivery result did not read back exactly"); + } + output.add(delivered); + } catch (RuntimeException ignored) { + abortAfterDeliveryFailure(binding, trust, operationId); + throw new DeliveryQuarantinedException(); + } + } + return List.copyOf(output); + } + + /** Aborts only the named current operation and retains hashes/evidence. */ + public List abortCurrentPlan(Binding binding, TrustFence trust, UUID operationId) { + return quarantineCurrent(binding, trust, operationId); + } + + /** Expires due entries and performs bounded cleanup for only the named operation. */ + public List expireAndClean(Binding binding, TrustFence trust, UUID operationId) { + return inTransaction( + () -> { + repository.expireCurrent( + binding, trust, operationId, Instant.ofEpochSecond(nowEpochSecond())); + return repository.cleanTerminalEntries( + operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION); + }); + } + + /** Bounded terminal cleanup never scans outside this explicit operation ID. */ + public List cleanTerminalEntries(UUID operationId) { + return inTransaction( + () -> + repository.cleanTerminalEntries( + operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION)); + } + + private void pinBeforeDelivery(Binding binding, TrustFence trust, SignedProbeDigest digest) { + try { + inTransaction( + () -> + repository.recordSigningAttempt( + binding, trust, digest, Instant.ofEpochSecond(nowEpochSecond()))); + } catch (RuntimeException failure) { + throw new SigningAttemptConflict(); + } + } + + private void abortAfterDeliveryFailure(Binding binding, TrustFence trust, UUID operationId) { + try { + quarantineCurrent(binding, trust, operationId); + } catch (RuntimeException ignored) { + // The durable pre-delivery hash remains a quarantine marker for same-operation recovery. + } + } + + private static boolean exactSignedReadback( + ReadinessProbePlan plan, ProbeEntry expected, ProbeEntry readback, SignedProbeDigest signed) { + long issuedEntryVersion = expected.entryVersion() + 2L; + long resultEntryVersion = + readback.state() == ProbeState.VERIFIED ? issuedEntryVersion + 1L : issuedEntryVersion; + return readback.rotationOperationId().equals(plan.operationId()) + && readback.planDigest().equals(plan.planDigest()) + && expected.planDigest().equals(plan.planDigest()) + && signed.operationId().equals(plan.operationId().toString()) + && readback.jti().equals(expected.jti()) + && signed.jti().equals(expected.jti()) + && readback.validatorId().equals(expected.validatorId()) + && signed.validatorId().equals(expected.validatorId()) + && readback.tokenProfile().equals(expected.tokenProfile()) + && signed.tokenProfile().equals(expected.tokenProfile()) + && readback.audience().equals(expected.audience()) + && signed.audience().equals(expected.audience()) + && readback.probeKind() == expected.probeKind() + && signed.probeKind() == expected.probeKind() + && readback.targetGeneration().equals(plan.targetGeneration()) + && signed.targetGeneration().equals(plan.targetGeneration()) + && readback.targetKid().equals(plan.targetKid()) + && signed.targetKid().equals(plan.targetKid()) + && signed.publicKeyFingerprint().equals(plan.targetPublicKeyFingerprint()) + && readback.plannedIssuedAtEpochSecond() == signed.issuedAtEpochSecond() + && readback.expiresAtEpochSecond() == signed.expiresAtEpochSecond() + && readback.signingAttemptedAtEpochSecond().isPresent() + && readback.entryVersion() == resultEntryVersion + && (readback.state() != ProbeState.VERIFIED + || readback + .verificationReceipt() + .filter( + receipt -> + receipt.sourceEntryVersion() == issuedEntryVersion + && receipt.resultEntryVersion() == resultEntryVersion) + .isPresent()) + && readback.compactTokenSha256().equals(java.util.Optional.of(signed.compactTokenSha256())); + } + + private List quarantineCurrent(Binding binding, TrustFence trust, UUID operationId) { + return inTransaction( + () -> { + repository.abortCurrent( + binding, trust, operationId, Instant.ofEpochSecond(nowEpochSecond())); + return repository.cleanTerminalEntries( + operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION); + }); + } + + private ProbeEntry currentEntry( + Binding binding, TrustFence trust, UUID operationId, ProbeEntry expected) { + ReadinessProbePlan plan = + inTransaction(() -> repository.readCurrentPlan(binding, trust, operationId)); + return plan.entries().stream() + .filter(entry -> entry.jti().equals(expected.jti())) + .findFirst() + .orElseThrow( + () -> + new AccountJwtReadinessProbeRepository.QuarantinedStateException( + "Readiness probe entry disappeared from its immutable plan")); + } + + private long nowEpochSecond() { + long value = clock.instant().getEpochSecond(); + if (value <= 0L) { + throw new IllegalStateException("Readiness producer clock is invalid"); + } + return value; + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable"); + } + } + + private T inTransaction(java.util.function.Supplier operation) { + return accountTransaction.execute(status -> operation.get()); + } + + /** + * Per-invocation owner-internal sink. This is not a Spring component contract or an authority + * input; callback success is not validation evidence. Only an exact owner readback of a receipt + * independently recorded by the authenticated validator is. + */ + @FunctionalInterface + interface OwnerInternalProbeDelivery { + void deliver(DeliveryMetadata metadata, byte[] exactCompactJwt); + } + + /** Non-secret operation identity passed alongside the transient probe bytes. */ + public record DeliveryMetadata( + UUID operationId, + String planDigest, + int planVersion, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + String targetGeneration, + String targetKid, + Optional expectedActiveGeneration, + Optional expectedActiveKid, + int registryVersion, + long entryVersion, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256) { + private static DeliveryMetadata from( + ReadinessProbePlan plan, ProbeEntry entry, SignedProbeDigest digest) { + return new DeliveryMetadata( + plan.operationId(), + plan.planDigest(), + plan.planVersion(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + entry.jti(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive().map(value -> value.generation()), + entry.expectedActive().map(value -> value.kid()), + entry.registryVersion(), + entry.entryVersion(), + entry.plannedIssuedAtEpochSecond(), + entry.expiresAtEpochSecond(), + digest.compactTokenSha256()); + } + } + + private static final class SigningAttemptConflict extends IllegalStateException { + private SigningAttemptConflict() { + super("Readiness signing attempt could not be durably pinned"); + } + } + + private static final class DeliveryQuarantinedException extends IllegalStateException { + private DeliveryQuarantinedException() { + super("Readiness probe delivery was ambiguous; the operation was quarantined"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java new file mode 100644 index 0000000000..4e5ab7a257 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java @@ -0,0 +1,1122 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedPromotion; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +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.ObservationPurpose; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Explicit Account-owned enrollment and durable-generation reconciliation for interim JWT signer + * materialization. + * + *

This coordinator is not scheduled or run at application startup. Enrollment derives only from + * Account's protected materializer binding, protected JWKS API binding, and a live observation of + * the fixed public ConfigMap. Enrollment initializes the short Account state row without selecting + * a generation request. Durable-generation reconciliation reads only an already selected request. + * Those two bootstrap paths do not commit signer promotion or treat mounted correspondence as + * validator readiness; the separate prepared-promotion path below requires the private receipt and + * complete current readiness evidence before it owns the public ACTIVE CAS and durable commit. + */ +public final class AccountJwtSignerBootstrapCoordinator { + private static final String JWKS_DATA_KEY = AccountJwtJwksPublicationRepository.JWKS_DATA_KEY; + + private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding; + private final AccountJwtJwksConfigMapClient configMapClient; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPrepublicationService prepublicationService; + private final AccountJwtReadinessProbeRepository readinessRepository; + private final ObjectProvider inventorySourceProvider; + private final TransactionTemplate accountTransaction; + + public AccountJwtSignerBootstrapCoordinator( + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksConfigMapClient configMapClient, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPrepublicationService prepublicationService, + TransactionTemplate accountTransaction) { + this( + materializerTrustBinding, + configMapClient, + desiredStateRepository, + prepublicationService, + null, + null, + accountTransaction); + } + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The Account readiness repository is a live Spring owner used for transactional proof reads.") + public AccountJwtSignerBootstrapCoordinator( + AccountJwtSignerMaterializerTrustBinding materializerTrustBinding, + AccountJwtJwksConfigMapClient configMapClient, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPrepublicationService prepublicationService, + AccountJwtReadinessProbeRepository readinessRepository, + ObjectProvider inventorySourceProvider, + TransactionTemplate accountTransaction) { + this.materializerTrustBinding = + Objects.requireNonNull( + materializerTrustBinding, "Protected materializer trust is required"); + this.configMapClient = + Objects.requireNonNull(configMapClient, "Protected JWKS client is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Account signer repository is required"); + this.prepublicationService = + Objects.requireNonNull(prepublicationService, "Account prepublication owner is required"); + this.readinessRepository = readinessRepository; + this.inventorySourceProvider = inventorySourceProvider; + this.accountTransaction = + Objects.requireNonNull(accountTransaction, "Account transaction template is required"); + this.accountTransaction.setReadOnly(false); + } + + /** + * Performs only the authenticated, finite enrollment step. It does not select a generation + * request, advance a signer phase, publish JWKS, or inspect mounted private material. + */ + public EnrollmentAcknowledgement enrollOnce() { + EnrollmentSources sources = captureEnrollmentSources(); + DesiredState initialized = initializeEnrollment(sources); + EnrollmentIdentity enrolled = + initialized + .enrollmentIdentity() + .orElseThrow( + () -> new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS)); + return acknowledgement(sources.materializerBinding(), sources.apiIdentity(), enrolled); + } + + /** + * Reconciles publication and mounted correspondence for the exact current generated receipt. The + * authenticated RPC owner calls this only after its short generation-read transaction has + * returned {@code GENERATION_RECORDED}; this method never creates a new operation. + */ + public BootstrapProgress reconcileCurrentGenerationOnce(UUID expectedOperationId) { + Objects.requireNonNull(expectedOperationId, "Expected generation operation is required"); + EnrollmentSources sources = captureEnrollmentSources(); + GenerationRequest request = readCurrentGenerationRequest(sources); + if (!expectedOperationId.equals(request.operationId()) + || request.phase() != GenerationPhase.GENERATION_RECORDED) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH); + } + return reconcileSelectedGeneration(sources, request); + } + + /** + * Enters PREPARED only for the exact current durable generation after refreshed publication, + * mounted correspondence, and owner-verified live validator closure. The materializer's + * authenticated promotion-request RPC is the only production caller. All API, filesystem, and + * Kubernetes reads finish before the short Account transaction that obtains the private proof and + * performs the owner CAS. + */ + public Optional prepareCurrentPromotionOnce() { + if (readinessRepository == null || inventorySourceProvider == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + EnrollmentSources sources = captureEnrollmentSources(); + DesiredState enrolled = readEnrollmentState(sources); + if (enrolled.generationOperationId().isEmpty()) { + requireUnselectedInitialEnrollment(enrolled, sources); + requireUnchangedProtectedBindings(sources); + return Optional.empty(); + } + GenerationRequest request = readCurrentGenerationRequest(sources); + if (request.phase() != GenerationPhase.GENERATION_RECORDED) { + if (request.phase() == GenerationPhase.OBSERVE_PRIVATE_SECRET + || request.phase() == GenerationPhase.GENERATE_PENDING) { + requireUnchangedProtectedBindings(sources); + return Optional.empty(); + } + throw new BootstrapOperationException(FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH); + } + + BootstrapProgress refreshed = reconcileSelectedGeneration(sources, request); + if (refreshed.stage() != Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE + || !refreshed.publicKeyPrepublished() + || !refreshed.mountedKeyCorrespondence()) { + return Optional.empty(); + } + + InventorySnapshot liveInventory = observeCurrentValidatorInventory(sources, request); + requireUnchangedProtectedBindings(sources); + PreparedPromotion prepared = + accountTransaction.execute( + status -> { + requireUnchangedProtectedBindings(sources); + var proof = + readinessRepository.readCurrentPromotionPrerequisites( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding()), + request.operationId(), + liveInventory); + if (proof.isEmpty()) { + return null; + } + ReadinessPromotionProof verifiedProof = proof.orElseThrow(); + DesiredState state = + desiredStateRepository.read(sources.materializerBinding().accountBinding()); + EnrollmentIdentity enrollment = + state + .enrollmentIdentity() + .orElseThrow( + () -> + new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS)); + var publication = verifiedProof.publication(); + PromotionPreparation preparation = + new PromotionPreparation( + verifiedProof.generationResult().operationId(), + verifiedProof.generationResult(), + enrollment, + publication.intent().apiBindingDigest(), + publication.intent().apiConfigRevision(), + publication.intent().configMapUid(), + publication.receipt().observedResourceVersion(), + publication.intent().intentDigest(), + publication.receipt().receiptDigest(), + publication.mountedCorrespondence().observationDigest(), + verifiedProof.plan().planDigest(), + verifiedProof.readinessEvidenceDigest(), + publication.intent().jwksJson()); + PreparedPromotion persisted = + desiredStateRepository.prepareCurrentGeneration( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding()), + preparation, + verifiedProof); + PreparedGenerationEvidence readback = + desiredStateRepository.readPreparedGenerationForRecovery( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding())); + if (!readback.promotion().operationId().equals(persisted.operationId()) + || !readback.promotion().requestDigest().equals(persisted.requestDigest()) + || !readback.promotion().generationOperationId().equals(request.operationId()) + || !readback.generationResult().equals(verifiedProof.generationResult()) + || !"PREPARED".equals(persisted.status())) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + requireUnchangedProtectedBindings(sources); + return persisted; + }); + if (prepared == null) { + return Optional.empty(); + } + requireUnchangedProtectedBindings(sources); + return Optional.of(prepared); + } + + /** + * Completes only the exact Account PREPARED operation whose authenticated private-slot receipt + * has already been recorded. Account owns the public ConfigMap ACTIVE CAS and terminal durable + * commit; this finite call is never started at boot or by a scheduler. + */ + public void reconcilePreparedPromotionOnce( + PrivatePromotionObservation observation, PrivatePromotionReceipt expectedReceipt) { + Objects.requireNonNull(observation, "Exact private promotion observation is required"); + Objects.requireNonNull(expectedReceipt, "Durable private promotion receipt is required"); + Binding binding = currentMaterializerBinding(); + BindingIdentity apiIdentity = currentApiIdentity(); + requireMatchingProtectedPins(binding, apiIdentity); + requireReceiptIdentity(observation, expectedReceipt); + + PromotionOwnerSnapshot start = + readPromotionOwnerSnapshot(binding, apiIdentity, observation, expectedReceipt); + requireUnchangedProtectedBindings(binding, apiIdentity); + if (!expectedReceipt.equals(start.privateReceipt())) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account private promotion receipt changed during reconciliation"); + } + if (start.committedEvidence() != null) { + return; + } + if (readinessRepository == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + + PreparedGenerationEvidence prepared = start.preparedEvidence(); + PromotionOperationEvidence promotion = prepared.promotion(); + ObservationContext context = observationContext(promotion); + InventorySnapshot beforeInventory = observePreparedInventory(context); + requireUnchangedProtectedBindings(binding, apiIdentity); + + ConfigMapSnapshot observedConfigMap = + prepublicationService.observePreparedCurrentKeyCorrespondence(promotion); + requireUnchangedProtectedBindings(binding, apiIdentity); + + readPreparedPromotionProof( + binding, apiIdentity, observation, expectedReceipt, promotion, beforeInventory); + requireUnchangedProtectedBindings(binding, apiIdentity); + requireExpectedPublicSnapshot(promotion, observedConfigMap); + requireUnchangedProtectedBindings(binding, apiIdentity); + + CasObservation activeReadback = + configMapClient.publishActiveProjection( + observedConfigMap, + promotion.expectedPublicResourceVersion(), + java.util.Map.of( + JWKS_DATA_KEY, + promotion.expectedPublicJwksJson(), + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + promotion.expectedActiveMarkerJson())); + requireExactActiveReadback(promotion, activeReadback); + requireUnchangedProtectedBindings(binding, apiIdentity); + + ActiveJwksPromotionObservation activeObservation = + new ActiveJwksPromotionObservation( + activeReadback.uid(), + activeReadback.priorResourceVersion(), + activeReadback.resourceVersion(), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson()); + ActiveJwksPromotionReceipt activeReceipt = + accountTransaction.execute( + status -> { + PrivatePromotionReceipt currentPrivateReceipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trustFence(binding), observation); + if (!expectedReceipt.equals(currentPrivateReceipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Original private promotion receipt changed before ACTIVE readback recording"); + } + return desiredStateRepository.recordActiveJwksPromotionResult( + binding.accountBinding(), trustFence(binding), activeObservation); + }); + if (activeReceipt == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account ACTIVE JWKS receipt is unavailable"); + } + requireUnchangedProtectedBindings(binding, apiIdentity); + if (!activeReceipt.promotionOperationId().equals(promotion.operationId()) + || !activeReceipt.configMapUid().equals(promotion.publicConfigMapUid()) + || !activeReceipt.priorResourceVersion().equals(promotion.expectedPublicResourceVersion()) + || !activeReceipt.observedResourceVersion().equals(activeReadback.resourceVersion()) + || !activeReceipt + .publicDataDigest() + .equals( + AccountJwtJwksPublicationRepository.publicDataDigest( + promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson()))) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account ACTIVE JWKS receipt did not match its exact CAS readback"); + } + + PreparedGenerationEvidence afterActiveReceipt = + accountTransaction.execute( + status -> + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding))); + if (afterActiveReceipt == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Prepared Account promotion evidence is unavailable after ACTIVE readback"); + } + PromotionOperationEvidence promotionWithActiveReceipt = afterActiveReceipt.promotion(); + requirePromotionIdentity(promotion, promotionWithActiveReceipt, observation, expectedReceipt); + if (!promotionWithActiveReceipt + .activeJwksReceiptDigest() + .equals(Optional.of(activeReceipt.receiptDigest())) + || !promotionWithActiveReceipt + .activeJwksPublicDataDigest() + .equals(Optional.of(activeReceipt.publicDataDigest())) + || !promotionWithActiveReceipt + .activeJwksObservedResourceVersion() + .equals(Optional.of(activeReceipt.observedResourceVersion()))) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account ACTIVE JWKS receipt is not bound to the current PREPARED operation"); + } + requireUnchangedProtectedBindings(binding, apiIdentity); + + InventorySnapshot beforeCommitInventory = observePreparedInventory(context); + requireUnchangedProtectedBindings(binding, apiIdentity); + prepublicationService.observePreparedCurrentKeyCorrespondence(promotionWithActiveReceipt); + requireUnchangedProtectedBindings(binding, apiIdentity); + CommittedSignerEvidence committed = + commitPreparedPromotion( + binding, + apiIdentity, + observation, + expectedReceipt, + promotionWithActiveReceipt, + beforeCommitInventory); + requireUnchangedProtectedBindings(binding, apiIdentity); + if (committed == null + || !promotion.operationId().equals(committed.promotion().operationId()) + || !"COMMITTED".equals(committed.promotion().status())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account ACTIVE signer commit did not read back exactly"); + } + // The final commit obtains a separate readiness proof from the independent post-CAS inventory + // observation. + } + + private PromotionOwnerSnapshot readPromotionOwnerSnapshot( + Binding binding, + BindingIdentity apiIdentity, + PrivatePromotionObservation observation, + PrivatePromotionReceipt expectedReceipt) { + TrustFence trust = trustFence(binding); + PromotionOwnerSnapshot snapshot = + accountTransaction.execute( + status -> { + PrivatePromotionReceipt receipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trust, observation); + if (!expectedReceipt.equals(receipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Private promotion receipt changed before Account reconciliation"); + } + try { + PreparedGenerationEvidence prepared = + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trust); + requirePreparedReceipt(prepared, observation, receipt); + return new PromotionOwnerSnapshot(prepared, null, receipt); + } catch (AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException done) { + CommittedSignerEvidence committed = + desiredStateRepository + .readCurrentCommittedSigner( + binding.accountBinding(), + trust, + apiIdentity.bindingDigest(), + apiIdentity.configRevision()) + .orElseThrow( + () -> + new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Private promotion is neither PREPARED nor currently committed")); + if (!committed.privateReceipt().equals(receipt) + || !committed + .promotion() + .operationId() + .equals(observation.promotionOperationId())) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Committed private promotion retry differs from Account evidence"); + } + return new PromotionOwnerSnapshot(null, committed, receipt); + } + }); + if (snapshot == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account signer promotion evidence is unavailable"); + } + return snapshot; + } + + private ReadinessPromotionProof readPreparedPromotionProof( + Binding binding, + BindingIdentity apiIdentity, + PrivatePromotionObservation observation, + PrivatePromotionReceipt expectedReceipt, + PromotionOperationEvidence expectedPromotion, + InventorySnapshot liveInventory) { + TrustFence trust = trustFence(binding); + ReadinessPromotionProof proof = + accountTransaction.execute( + status -> { + PrivatePromotionReceipt receipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trust, observation); + if (!expectedReceipt.equals(receipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Private promotion receipt changed before ACTIVE publication"); + } + PreparedGenerationEvidence current = + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trust); + requireSamePreparedPromotion(current, expectedPromotion, observation, receipt); + return readinessRepository + .readPromotionProof( + binding.accountBinding(), + trust, + expectedPromotion.generationOperationId(), + liveInventory) + .orElseThrow( + () -> + new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Fresh complete Account readiness proof is unavailable")); + }); + if (proof == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account readiness proof is unavailable"); + } + requireUnchangedProtectedBindings(binding, apiIdentity); + return proof; + } + + private CommittedSignerEvidence commitPreparedPromotion( + Binding binding, + BindingIdentity apiIdentity, + PrivatePromotionObservation observation, + PrivatePromotionReceipt expectedReceipt, + PromotionOperationEvidence expectedPromotion, + InventorySnapshot liveInventory) { + TrustFence trust = trustFence(binding); + CommittedSignerEvidence committed = + accountTransaction.execute( + status -> { + PrivatePromotionReceipt receipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trust, observation); + if (!expectedReceipt.equals(receipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Original private promotion observation no longer matches Account evidence"); + } + PreparedGenerationEvidence current = + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trust); + requireSamePreparedPromotion(current, expectedPromotion, observation, receipt); + ReadinessPromotionProof proof = + readinessRepository + .readPromotionProof( + binding.accountBinding(), + trust, + expectedPromotion.generationOperationId(), + liveInventory) + .orElseThrow( + () -> + new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Post-CAS complete Account readiness proof is unavailable")); + return desiredStateRepository.commitPreparedPromotion( + binding.accountBinding(), trust, expectedPromotion.operationId(), proof); + }); + if (committed == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account signer promotion commit is unavailable"); + } + requireUnchangedProtectedBindings(binding, apiIdentity); + return committed; + } + + private InventorySnapshot observePreparedInventory(ObservationContext context) { + if (inventorySourceProvider == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + AccountJwtValidatorInventorySource source = inventorySourceProvider.getIfAvailable(); + if (source == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + try { + return source.observe(context); + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + } + + private static ObservationContext observationContext(PromotionOperationEvidence promotion) { + if (!promotion.expectedPreviousActive().equals(promotion.expectedPublishedActive())) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared Account active signer fence is inconsistent"); + } + return new ObservationContext( + promotion.expectedPreviousActive().isEmpty() + ? ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES + : ObservationPurpose.STRICT_READY, + promotion.generationOperationId(), + promotion.generationOperationDigest()); + } + + private static void requireReceiptIdentity( + PrivatePromotionObservation observation, PrivatePromotionReceipt receipt) { + if (!observation.promotionOperationId().equals(receipt.promotionOperationId()) + || !observation.generationOperationId().equals(receipt.generationOperationId()) + || !observation.observedResourceVersion().equals(receipt.observedResourceVersion())) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Private promotion result does not match the exact Account receipt"); + } + } + + private static void requirePreparedReceipt( + PreparedGenerationEvidence prepared, + PrivatePromotionObservation observation, + PrivatePromotionReceipt receipt) { + requireSamePreparedPromotion(prepared, prepared.promotion(), observation, receipt); + } + + private static void requireSamePreparedPromotion( + PreparedGenerationEvidence prepared, + PromotionOperationEvidence expected, + PrivatePromotionObservation observation, + PrivatePromotionReceipt receipt) { + PromotionOperationEvidence current = prepared.promotion(); + if (!current.equals(expected) + || !current.operationId().equals(observation.promotionOperationId()) + || !current.generationOperationId().equals(observation.generationOperationId()) + || !current.generationOperationDigest().equals(observation.generationOperationDigest()) + || !current.requestDigest().equals(observation.promotionRequestDigest()) + || !current.privatePromotionDispatched() + || !current.privatePromotionReceiptDigest().equals(Optional.of(receipt.receiptDigest()))) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Private promotion receipt does not match the exact current PREPARED operation"); + } + } + + private static void requirePromotionIdentity( + PromotionOperationEvidence expected, + PromotionOperationEvidence current, + PrivatePromotionObservation observation, + PrivatePromotionReceipt receipt) { + if (!current.operationId().equals(expected.operationId()) + || !current.requestDigest().equals(expected.requestDigest()) + || current.expectedRecordVersion() != expected.expectedRecordVersion() + || !current.binding().equals(expected.binding()) + || !current.expectedPreviousActive().equals(expected.expectedPreviousActive()) + || !current + .expectedPreviousPublicKeyFingerprint() + .equals(expected.expectedPreviousPublicKeyFingerprint()) + || !current.expectedPublishedActive().equals(expected.expectedPublishedActive()) + || !current.targetAlgorithm().equals(expected.targetAlgorithm()) + || !current.trustFence().equals(expected.trustFence()) + || !current.generationOperationId().equals(expected.generationOperationId()) + || !current.generationOperationDigest().equals(expected.generationOperationDigest()) + || !current.generationReceiptDigest().equals(expected.generationReceiptDigest()) + || !current.targetGeneration().equals(expected.targetGeneration()) + || !current.targetKid().equals(expected.targetKid()) + || !current.targetPublicKeyFingerprint().equals(expected.targetPublicKeyFingerprint()) + || !current.secretUid().equals(expected.secretUid()) + || !current + .expectedPrivateResourceVersion() + .equals(expected.expectedPrivateResourceVersion()) + || !current.apiBindingDigest().equals(expected.apiBindingDigest()) + || !current.apiConfigRevision().equals(expected.apiConfigRevision()) + || !current.publicConfigMapUid().equals(expected.publicConfigMapUid()) + || !current.expectedPublicResourceVersion().equals(expected.expectedPublicResourceVersion()) + || !current.prepublicationIntentDigest().equals(expected.prepublicationIntentDigest()) + || !current.prepublicationReceiptDigest().equals(expected.prepublicationReceiptDigest()) + || !current.mountedObservationDigest().equals(expected.mountedObservationDigest()) + || !current.readinessPlanDigest().equals(expected.readinessPlanDigest()) + || !current.readinessEvidenceDigest().equals(expected.readinessEvidenceDigest()) + || !current.expectedPublicJwksJson().equals(expected.expectedPublicJwksJson()) + || !current.expectedActiveMarkerJson().equals(expected.expectedActiveMarkerJson()) + || !"PREPARED".equals(current.status()) + || !current.operationId().equals(observation.promotionOperationId()) + || !current.generationOperationId().equals(observation.generationOperationId()) + || !current.privatePromotionDispatched() + || !current.privatePromotionReceiptDigest().equals(Optional.of(receipt.receiptDigest()))) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account PREPARED operation changed during ACTIVE publication"); + } + } + + private static void requireExpectedPublicSnapshot( + PromotionOperationEvidence promotion, ConfigMapSnapshot snapshot) { + String marker = + snapshot.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY); + boolean active = promotion.expectedActiveMarkerJson().equals(marker); + if (!promotion.publicConfigMapUid().equals(snapshot.uid()) + || !promotion.expectedPublicJwksJson().equals(snapshot.data().get(JWKS_DATA_KEY)) + || (!promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion()) + && !active) + || (promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion()) + && active)) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Account public ConfigMap changed before its exact ACTIVE CAS"); + } + } + + private static void requireExactActiveReadback( + PromotionOperationEvidence promotion, CasObservation observation) { + if (!promotion.publicConfigMapUid().equals(observation.uid()) + || !promotion.expectedPublicResourceVersion().equals(observation.priorResourceVersion()) + || !promotion + .expectedPublicJwksJson() + .equals(observation.publishedData().get(JWKS_DATA_KEY)) + || !promotion + .expectedActiveMarkerJson() + .equals( + observation + .publishedData() + .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY)) + || !promotion.expectedPublicJwksJson().equals(observation.readbackData().get(JWKS_DATA_KEY)) + || !promotion + .expectedActiveMarkerJson() + .equals( + observation + .readbackData() + .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY)) + || promotion.expectedPublicResourceVersion().equals(observation.resourceVersion())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account ACTIVE ConfigMap CAS did not return its exact immutable readback"); + } + } + + private InventorySnapshot observeCurrentValidatorInventory( + EnrollmentSources sources, GenerationRequest request) { + try { + AccountJwtValidatorInventorySource source = inventorySourceProvider.getIfAvailable(); + if (source == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + ObservationContext context = + accountTransaction.execute( + status -> { + requireUnchangedProtectedBindings(sources); + ObservationContext selected = + readinessRepository.readCurrentInventoryObservationContext( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding()), + request.operationId()); + requireUnchangedProtectedBindings(sources); + return selected; + }); + if (context == null) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + return source.observe(context); + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); + } + } + + private BootstrapProgress reconcileSelectedGeneration( + EnrollmentSources sources, GenerationRequest request) { + try { + AccountJwtJwksPublicationRepository.PublicationReceipt publication = + prepublicationService.prepublishCurrentGeneration(); + requireUnchangedProtectedBindings(sources); + if (!request.operationId().equals(publication.operationId())) { + return progress( + Stage.PREPUBLICATION_BLOCKED, + request, + false, + false, + FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH); + } + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException ambiguousOrRejected) { + return progress( + Stage.PREPUBLICATION_BLOCKED, + request, + false, + false, + FailureCode.ACCOUNT_PREPUBLICATION_UNAVAILABLE); + } + + try { + AccountJwtJwksPublicationRepository.MountObservation mount = + prepublicationService.observeCurrentMountedCorrespondence(); + requireUnchangedProtectedBindings(sources); + if (!request.operationId().equals(mount.operationId())) { + return progress( + Stage.MOUNT_CORRESPONDENCE_BLOCKED, + request, + true, + false, + FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH); + } + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailableOrRejected) { + return progress( + Stage.MOUNT_CORRESPONDENCE_BLOCKED, + request, + true, + false, + FailureCode.ACCOUNT_MOUNT_CORRESPONDENCE_UNAVAILABLE); + } + + return progress( + Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE, + request, + true, + true, + FailureCode.VALIDATOR_ACCEPTANCE_INCOMPLETE); + } + + private DesiredState initializeEnrollment(EnrollmentSources sources) { + AccountJwtSignerDesiredStateRepository.Binding accountBinding = + sources.materializerBinding().accountBinding(); + try { + DesiredState initialized = + accountTransaction.execute( + status -> { + requireUnchangedProtectedBindings(sources); + DesiredState persisted = + desiredStateRepository.initialize(accountBinding, sources.enrollmentIdentity()); + requireUnchangedProtectedBindings(sources); + return persisted; + }); + if (initialized == null) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + requireUnchangedProtectedBindings(sources); + return initialized; + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + } + + private DesiredState readEnrollmentState(EnrollmentSources sources) { + AccountJwtSignerDesiredStateRepository.Binding accountBinding = + sources.materializerBinding().accountBinding(); + try { + Optional state = + accountTransaction.execute( + status -> { + requireUnchangedProtectedBindings(sources); + Optional current = + desiredStateRepository.readEnrollmentState(accountBinding); + requireUnchangedProtectedBindings(sources); + return current; + }); + if (state == null || state.isEmpty()) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + DesiredState current = state.orElseThrow(); + EnrollmentIdentity enrollment = + current + .enrollmentIdentity() + .orElseThrow( + () -> new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS)); + if (!enrollment.sameStablePins(sources.enrollmentIdentity())) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_MISMATCH); + } + requireUnchangedProtectedBindings(sources); + return current; + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + } + + private static void requireUnselectedInitialEnrollment( + DesiredState state, EnrollmentSources sources) { + if (state.recordVersion() != 1 + || state.durableActive().isPresent() + || state.publishedActive().isPresent() + || state.preparedOperationId().isPresent() + || state.generationOperationId().isPresent() + || state.enrollmentIdentity().isEmpty() + || !state.enrollmentIdentity().orElseThrow().sameStablePins(sources.enrollmentIdentity())) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + } + + private GenerationRequest readCurrentGenerationRequest(EnrollmentSources sources) { + AccountJwtSignerDesiredStateRepository.Binding accountBinding = + sources.materializerBinding().accountBinding(); + TrustFence trustFence = trustFence(sources.materializerBinding()); + try { + GenerationRequest request = + accountTransaction.execute( + status -> { + requireUnchangedProtectedBindings(sources); + GenerationRequest current = + desiredStateRepository.readCurrentGenerationRequest(accountBinding, trustFence); + requireUnchangedProtectedBindings(sources); + return current; + }); + if (request == null) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + requireUnchangedProtectedBindings(sources); + return request; + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + } + + private static EnrollmentAcknowledgement acknowledgement( + Binding materializer, + AccountJwtJwksConfigMapClient.BindingIdentity api, + EnrollmentIdentity enrollment) { + return new EnrollmentAcknowledgement( + materializer.environmentId(), + materializer.clusterId(), + materializer.namespace(), + enrollment.expectedClusterIncarnationUid(), + enrollment.expectedNamespaceUid(), + enrollment.materializerTrustBindingDigest(), + enrollment.materializerTrustConfigRevision(), + enrollment.apiBindingDigest(), + enrollment.apiConfigRevision(), + api.apiServerUrl(), + api.tlsServerName(), + api.servingCaSha256(), + api.expectedApiUsername(), + AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME, + AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME, + enrollment.publicConfigMapUid(), + enrollment.publicConfigMapResourceVersion(), + enrollment.publicConfigMapSnapshotDigest()); + } + + private EnrollmentSources captureEnrollmentSources() { + Binding materializerBefore = currentMaterializerBinding(); + AccountJwtJwksConfigMapClient.BindingIdentity apiBefore = currentApiIdentity(); + requireMatchingProtectedPins(materializerBefore, apiBefore); + + AccountJwtJwksConfigMapClient.ConfigMapSnapshot publicConfigMap; + try { + publicConfigMap = Objects.requireNonNull(configMapClient.observe()); + } catch (RuntimeException unavailableOrAmbiguous) { + throw new BootstrapOperationException(FailureCode.PUBLIC_CONFIG_MAP_UNAVAILABLE); + } + + Binding materializerAfter = currentMaterializerBinding(); + AccountJwtJwksConfigMapClient.BindingIdentity apiAfter = currentApiIdentity(); + if (!materializerBefore.equals(materializerAfter) || !apiBefore.equals(apiAfter)) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_CHANGED); + } + requireMatchingProtectedPins(materializerAfter, apiAfter); + String initialJwks = publicConfigMap.data().get(JWKS_DATA_KEY); + if (initialJwks == null || initialJwks.isBlank()) { + throw new BootstrapOperationException(FailureCode.PUBLIC_CONFIG_MAP_INCOMPLETE); + } + + try { + EnrollmentIdentity enrollment = + new EnrollmentIdentity( + materializerAfter.expectedClusterIncarnationUid(), + materializerAfter.expectedNamespaceUid(), + materializerAfter.bindingDigest(), + materializerAfter.configRevision(), + apiAfter.bindingDigest(), + apiAfter.configRevision(), + publicConfigMap.uid(), + publicConfigMap.resourceVersion(), + AccountJwtJwksPublicationRepository.snapshotDigest(publicConfigMap.data())); + return new EnrollmentSources(materializerAfter, apiAfter, enrollment); + } catch (RuntimeException malformedSource) { + throw new BootstrapOperationException(FailureCode.PUBLIC_CONFIG_MAP_INCOMPLETE); + } + } + + private Binding currentMaterializerBinding() { + try { + return materializerTrustBinding + .current() + .orElseThrow( + () -> new BootstrapOperationException(FailureCode.PROTECTED_BINDING_UNAVAILABLE)); + } catch (BootstrapOperationException failure) { + throw failure; + } catch (RuntimeException unavailable) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_UNAVAILABLE); + } + } + + private AccountJwtJwksConfigMapClient.BindingIdentity currentApiIdentity() { + try { + return Objects.requireNonNull(configMapClient.identity()); + } catch (RuntimeException unavailable) { + throw new BootstrapOperationException(FailureCode.PROTECTED_API_BINDING_UNAVAILABLE); + } + } + + private void requireUnchangedProtectedBindings(EnrollmentSources sources) { + Binding currentMaterializer = currentMaterializerBinding(); + AccountJwtJwksConfigMapClient.BindingIdentity currentApi = currentApiIdentity(); + if (!sources.materializerBinding().equals(currentMaterializer) + || !sources.apiIdentity().equals(currentApi)) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_CHANGED); + } + requireMatchingProtectedPins(currentMaterializer, currentApi); + } + + private void requireUnchangedProtectedBindings( + Binding expectedMaterializer, BindingIdentity expectedApiIdentity) { + Binding currentMaterializer = currentMaterializerBinding(); + BindingIdentity currentApi = currentApiIdentity(); + if (!expectedMaterializer.equals(currentMaterializer) + || !expectedApiIdentity.equals(currentApi)) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_CHANGED); + } + requireMatchingProtectedPins(currentMaterializer, currentApi); + } + + private static void requireMatchingProtectedPins( + Binding materializer, AccountJwtJwksConfigMapClient.BindingIdentity api) { + if (!materializer.environmentId().equals(api.environmentId()) + || !materializer.clusterId().equals(api.clusterId()) + || !materializer.namespace().equals(api.namespace()) + || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid()) + || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid())) { + throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_MISMATCH); + } + } + + private static TrustFence trustFence(Binding binding) { + return new TrustFence( + binding.expectedClusterIncarnationUid(), + binding.expectedNamespaceUid(), + binding.bindingDigest(), + binding.configRevision()); + } + + private static BootstrapProgress progress( + Stage stage, + GenerationRequest request, + boolean prepublished, + boolean mountedCorrespondence, + FailureCode failure) { + boolean validatorAcceptanceComplete = false; + List blockers = List.of(failure); + if (stage == Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE) { + blockers = + List.of( + FailureCode.VALIDATOR_ACCEPTANCE_INCOMPLETE, + FailureCode.SIGNER_PROMOTION_NOT_ATTEMPTED); + } + return new BootstrapProgress( + stage, + EnrollmentSource.PROTECTED_BINDINGS_AND_LIVE_FIXED_JWKS_CONFIG_MAP, + true, + true, + request.operationId(), + request.phase(), + request.targetGeneration(), + request.targetKid(), + request.phase() == GenerationPhase.GENERATION_RECORDED, + prepublished, + mountedCorrespondence, + AccountJwtReadinessProbeRepository.INVENTORY_STATUS, + validatorAcceptanceComplete, + false, + false, + blockers); + } + + private record EnrollmentSources( + Binding materializerBinding, + AccountJwtJwksConfigMapClient.BindingIdentity apiIdentity, + EnrollmentIdentity enrollmentIdentity) {} + + private record PromotionOwnerSnapshot( + PreparedGenerationEvidence preparedEvidence, + CommittedSignerEvidence committedEvidence, + PrivatePromotionReceipt privateReceipt) {} + + /** Closed, non-secret identity acknowledgment for one idempotent durable enrollment. */ + public record EnrollmentAcknowledgement( + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String materializerTrustBindingDigest, + String materializerTrustConfigRevision, + String apiBindingDigest, + String apiConfigRevision, + String apiServerUrl, + String apiTlsServerName, + String apiServingCaSha256, + String apiExpectedUsername, + String privateSecretName, + String publicConfigMapName, + String publicConfigMapUid, + String publicConfigMapResourceVersion, + String publicConfigMapSnapshotDigest) {} + + public enum Stage { + PREPUBLICATION_BLOCKED, + MOUNT_CORRESPONDENCE_BLOCKED, + BLOCKED_FOR_VALIDATOR_ACCEPTANCE + } + + public enum EnrollmentSource { + PROTECTED_BINDINGS_AND_LIVE_FIXED_JWKS_CONFIG_MAP + } + + /** Non-secret progress; `false` readiness fields are deliberate until fleet proof exists. */ + public record BootstrapProgress( + Stage stage, + EnrollmentSource enrollmentSource, + boolean enrollmentInitialized, + boolean generationRequestSelected, + UUID operationId, + GenerationPhase generationPhase, + String targetGeneration, + String targetKid, + boolean generationReadbackComplete, + boolean publicKeyPrepublished, + boolean mountedKeyCorrespondence, + String validatorInventoryStatus, + boolean validatorAcceptanceComplete, + boolean signerPromotionCommitted, + boolean issuanceReady, + List blockers) { + public BootstrapProgress { + Objects.requireNonNull(stage); + Objects.requireNonNull(enrollmentSource); + Objects.requireNonNull(operationId); + Objects.requireNonNull(generationPhase); + Objects.requireNonNull(targetGeneration); + Objects.requireNonNull(targetKid); + Objects.requireNonNull(validatorInventoryStatus); + blockers = List.copyOf(blockers); + if (validatorAcceptanceComplete || signerPromotionCommitted || issuanceReady) { + throw new IllegalArgumentException( + "Signer bootstrap progress cannot claim validator acceptance, promotion, or readiness"); + } + if (!enrollmentInitialized || !generationRequestSelected) { + throw new IllegalArgumentException( + "Signer bootstrap progress requires completed Account enrollment and request selection"); + } + } + } + + public enum FailureCode { + PROTECTED_BINDING_UNAVAILABLE, + PROTECTED_API_BINDING_UNAVAILABLE, + PROTECTED_BINDING_MISMATCH, + PROTECTED_BINDING_CHANGED, + PUBLIC_CONFIG_MAP_UNAVAILABLE, + PUBLIC_CONFIG_MAP_INCOMPLETE, + SIGNER_PROMOTION_NOT_ATTEMPTED, + ACCOUNT_STATE_AMBIGUOUS, + ACCOUNT_OWNER_OPERATION_MISMATCH, + ACCOUNT_PREPUBLICATION_UNAVAILABLE, + ACCOUNT_MOUNT_CORRESPONDENCE_UNAVAILABLE, + VALIDATOR_INVENTORY_UNAVAILABLE, + VALIDATOR_ACCEPTANCE_INCOMPLETE + } + + public static final class BootstrapOperationException extends IllegalStateException { + private final FailureCode failureCode; + + public BootstrapOperationException(FailureCode failureCode) { + super("Account JWT signer bootstrap is quarantined: " + failureCode); + this.failureCode = Objects.requireNonNull(failureCode); + } + + public FailureCode failureCode() { + return failureCode; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java new file mode 100644 index 0000000000..1772d03532 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java @@ -0,0 +1,221 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind; + +/** + * Explicit Account-owned active/retained key snapshot for operator-reference fingerprints. + * + *

This class has no key source implementation, default key, or provisioning behavior. The caller + * supplies an owner-controlled source and an explicit post-expiry reconciliation window; every + * fingerprint operation reloads that source and fails closed for a missing, withdrawn, or + * insufficiently retained key. + */ +public final class AccountOperatorAuthorizationFingerprintKeyring { + private static final int MAX_RETAINED_KEYS = 8; + private static final Pattern FINGERPRINT = + Pattern.compile("arfp/v1/([A-Za-z0-9_-]{1,64})/([0-9a-f]{64})"); + private static final String HMAC_ALGORITHM = "HmacSHA256"; + + private final OwnerKeySource source; + private final Clock clock; + private final Duration requiredPostExpiryRetention; + + public AccountOperatorAuthorizationFingerprintKeyring( + OwnerKeySource source, Clock clock, Duration requiredPostExpiryRetention) { + this.source = Objects.requireNonNull(source, "explicit Account operator key source required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + this.requiredPostExpiryRetention = + Objects.requireNonNull(requiredPostExpiryRetention, "retention policy is required"); + if (requiredPostExpiryRetention.isNegative() || requiredPostExpiryRetention.isZero()) { + throw new IllegalArgumentException("Explicit positive reconciliation retention is required"); + } + } + + /** Computes a new issuance fingerprint only with the currently declared active key. */ + public String fingerprintForIssue(ReferenceKind referenceKind, byte[] exactReferenceBytes) { + Objects.requireNonNull(referenceKind, "reference kind is required"); + Snapshot current = requireSnapshot(); + return current.activeKey().calculator().fingerprint(referenceKind, exactReferenceBytes); + } + + /** + * Recomputes the original fingerprint using its exact stored key ID and verifies the supplied + * value in constant time. Retired keys must remain available past both immutable expiries and the + * explicitly configured reconciliation window. + */ + public boolean matchesOriginal( + ReferenceKind referenceKind, + byte[] exactReferenceBytes, + String originalFingerprint, + Instant referenceExpiresAt, + Instant responseEnvelopeExpiresAt) { + Objects.requireNonNull(referenceKind, "reference kind is required"); + Objects.requireNonNull(referenceExpiresAt, "reference expiry is required"); + Objects.requireNonNull(responseEnvelopeExpiresAt, "response expiry is required"); + if (!responseEnvelopeExpiresAt.isAfter(referenceExpiresAt)) { + throw new IllegalArgumentException("Original response expiry must follow reference expiry"); + } + Matcher matcher = originalFingerprint == null ? null : FINGERPRINT.matcher(originalFingerprint); + if (matcher == null || !matcher.matches()) { + throw new IllegalArgumentException("Original Account reference fingerprint is malformed"); + } + + Snapshot current = requireSnapshot(); + String keyId = matcher.group(1); + KeyMaterial key = current.keyFor(keyId); + if (key == null) { + throw new KeyUnavailableException(); + } + if (key != current.activeKey()) { + Instant now = clock.instant(); + if (!now.isBefore(key.retainedUntil())) { + throw new KeyUnavailableException(); + } + Instant requiredUntil; + try { + requiredUntil = responseEnvelopeExpiresAt.plus(requiredPostExpiryRetention); + } catch (RuntimeException invalidHorizon) { + throw new KeyUnavailableException(); + } + if (!key.retainedUntil().isAfter(requiredUntil)) { + throw new KeyUnavailableException(); + } + } + String actual = key.calculator().fingerprint(referenceKind, exactReferenceBytes); + return MessageDigest.isEqual( + actual.getBytes(StandardCharsets.US_ASCII), + originalFingerprint.getBytes(StandardCharsets.US_ASCII)); + } + + private Snapshot requireSnapshot() { + try { + return Objects.requireNonNull(source.readCurrent(), "owner key snapshot is required"); + } catch (KeyUnavailableException unavailable) { + throw unavailable; + } catch (RuntimeException unavailable) { + throw new KeyUnavailableException(); + } + } + + @FunctionalInterface + public interface OwnerKeySource { + /** Reads the owner-controlled active and retained key snapshot afresh for this operation. */ + Snapshot readCurrent(); + } + + /** One active key and at most eight explicitly retained prior keys. */ + public record Snapshot(KeyMaterial activeKey, List retainedKeys) { + public Snapshot { + Objects.requireNonNull(activeKey, "one active Account operator key is required"); + if (activeKey.retainedUntil() != null) { + throw new IllegalArgumentException("Active Account operator key cannot be marked retained"); + } + retainedKeys = + List.copyOf(Objects.requireNonNull(retainedKeys, "retained keys are required")); + if (retainedKeys.size() > MAX_RETAINED_KEYS) { + throw new IllegalArgumentException("Retained Account operator keys exceed their bound"); + } + Set keyIds = new HashSet<>(); + if (!keyIds.add(activeKey.keyId())) { + throw new IllegalArgumentException("Active Account operator key ID is duplicated"); + } + for (KeyMaterial retained : retainedKeys) { + Objects.requireNonNull(retained, "retained Account operator key is required"); + if (retained.retainedUntil() == null || !keyIds.add(retained.keyId())) { + throw new IllegalArgumentException("Retained Account operator key is malformed"); + } + } + } + + private KeyMaterial keyFor(String keyId) { + if (activeKey.keyId().equals(keyId)) { + return activeKey; + } + return retainedKeys.stream() + .filter(value -> value.keyId().equals(keyId)) + .findFirst() + .orElse(null); + } + + @Override + public String toString() { + return "AccountOperatorAuthorizationFingerprintKeyring.Snapshot[key material redacted]"; + } + } + + /** Secret material remains private; only its bounded identifier is exposed. */ + public static final class KeyMaterial { + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + + private final String keyId; + private final AccountOperatorAuthorizationReferenceFingerprint calculator; + private final Instant retainedUntil; + + public KeyMaterial(String keyId, SecretKey secretKey) { + this(keyId, secretKey, null); + } + + public KeyMaterial(String keyId, SecretKey secretKey, Instant retainedUntil) { + if (keyId == null || !KEY_ID.matcher(keyId).matches()) { + throw new IllegalArgumentException("Unsupported Account operator key ID"); + } + Objects.requireNonNull(secretKey, "explicit Account operator key material is required"); + if (!HMAC_ALGORITHM.equalsIgnoreCase(secretKey.getAlgorithm())) { + throw new IllegalArgumentException("Unsupported Account operator key algorithm"); + } + byte[] encoded = secretKey.getEncoded(); + if (encoded == null || encoded.length == 0 || encoded.length > 4096) { + throw new IllegalArgumentException("Unsupported Account operator key material"); + } + byte[] copy = encoded.clone(); + try { + SecretKey immutableCopy = new SecretKeySpec(copy, HMAC_ALGORITHM); + calculator = new AccountOperatorAuthorizationReferenceFingerprint(keyId, immutableCopy); + } finally { + java.util.Arrays.fill(copy, (byte) 0); + } + if (retainedUntil != null && retainedUntil.toEpochMilli() <= 0L) { + throw new IllegalArgumentException("Retained Account operator key expiry is invalid"); + } + this.keyId = keyId; + this.retainedUntil = retainedUntil; + } + + public String keyId() { + return keyId; + } + + private AccountOperatorAuthorizationReferenceFingerprint calculator() { + return calculator; + } + + private Instant retainedUntil() { + return retainedUntil; + } + + @Override + public String toString() { + return "AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial[key material redacted]"; + } + } + + /** Fail-closed result for an absent, withdrawn, expired, or insufficiently retained key. */ + public static final class KeyUnavailableException extends RuntimeException { + public KeyUnavailableException() { + super("Account operator authorization fingerprint key is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java new file mode 100644 index 0000000000..588b7bc6b2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.regex.Pattern; +import javax.crypto.Mac; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +/** Account-owned HMAC identity for the exact bytes of an operator authorization reference. */ +public final class AccountOperatorAuthorizationReferenceFingerprint { + private static final String HMAC_ALGORITHM = "HmacSHA256"; + private static final String DOMAIN = "FireMUD/authorizationReferenceFingerprint/v1"; + private static final String OUTPUT_PREFIX = "arfp/v1/"; + private static final int MAX_KEY_ID_BYTES = 64; + private static final int MAX_KEY_BYTES = 4096; + private static final int MAX_REFERENCE_BYTES = 4096; + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + + private final String keyId; + private final SecretKey key; + + /** + * Creates a calculator with an explicitly supplied HMAC key and its bounded public identifier. + * + *

No key is generated, discovered, or loaded implicitly by this class. + */ + public AccountOperatorAuthorizationReferenceFingerprint(String keyId, SecretKey key) { + if (keyId == null || keyId.length() > MAX_KEY_ID_BYTES || !KEY_ID.matcher(keyId).matches()) { + throw new IllegalArgumentException("Unsupported authorization-reference fingerprint key ID"); + } + if (key == null || !HMAC_ALGORITHM.equalsIgnoreCase(key.getAlgorithm())) { + throw new IllegalArgumentException("Unsupported authorization-reference fingerprint key"); + } + + byte[] encoded = key.getEncoded(); + if (encoded == null || encoded.length == 0 || encoded.length > MAX_KEY_BYTES) { + throw new IllegalArgumentException("Unsupported authorization-reference fingerprint key"); + } + + byte[] keyCopy = encoded.clone(); + try { + this.key = new SecretKeySpec(keyCopy, HMAC_ALGORITHM); + } finally { + Arrays.fill(keyCopy, (byte) 0); + } + this.keyId = keyId; + } + + /** Returns the canonical fingerprint for the supplied exact opaque reference bytes. */ + public String fingerprint(ReferenceKind referenceKind, byte[] referenceBytes) { + if (referenceKind == null) { + throw new IllegalArgumentException("Unsupported operator authorization-reference kind"); + } + if (referenceBytes == null + || referenceBytes.length == 0 + || referenceBytes.length > MAX_REFERENCE_BYTES) { + throw new IllegalArgumentException("Invalid operator authorization-reference bytes"); + } + + byte[] referenceCopy = referenceBytes.clone(); + try { + Mac mac = Mac.getInstance(HMAC_ALGORITHM); + mac.init(key); + updateSegment(mac, DOMAIN.getBytes(StandardCharsets.UTF_8)); + updateSegment(mac, keyId.getBytes(StandardCharsets.UTF_8)); + updateSegment(mac, referenceKind.wireValue.getBytes(StandardCharsets.UTF_8)); + updateSegment(mac, referenceCopy); + return OUTPUT_PREFIX + keyId + "/" + HexFormat.of().formatHex(mac.doFinal()); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("HMAC-SHA-256 is unavailable", exception); + } finally { + Arrays.fill(referenceCopy, (byte) 0); + } + } + + private static void updateSegment(Mac mac, byte[] value) { + byte[] prefix = (Integer.toString(value.length) + ":").getBytes(StandardCharsets.US_ASCII); + mac.update(prefix); + mac.update(value); + } + + @Override + public String toString() { + return "AccountOperatorAuthorizationReferenceFingerprint"; + } + + /** The only reference kinds accepted by ADR 0047. */ + public enum ReferenceKind { + HUMAN_OPERATOR("human_operator"), + AUTOMATION_OPERATOR("automation_operator"); + + private final String wireValue; + + ReferenceKind(String wireValue) { + this.wireValue = Objects.requireNonNull(wireValue); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java new file mode 100644 index 0000000000..159082d2ad --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java @@ -0,0 +1,405 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Pattern; +import javax.crypto.AEADBadTagException; +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +/** Account-owned AEAD primitive for exact, bounded response-byte recovery. */ +@Component +public final class AccountResponseEnvelopeCryptography { + static final int NONCE_BYTES = 12; + static final int TAG_BITS = 128; + static final int TAG_BYTES = TAG_BITS / Byte.SIZE; + static final int MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES = 128 * 1024; + // Covers the authority bundle plus the bounded tuple, projections, identifiers, and framing. + static final int MAX_RESPONSE_BYTES = 144 * 1024; + static final int MAX_BINDING_BYTES = 144 * 1024; + private static final byte[] MAGIC = {'F', 'R', 'E', 'A'}; + private static final byte FORMAT_VERSION = 1; + private static final int FIXED_HEADER_BYTES = MAGIC.length + 1 + 1 + Long.BYTES + NONCE_BYTES; + private static final int MAX_HEADER_BYTES = FIXED_HEADER_BYTES + 32; + static final int MAX_ENVELOPE_BYTES = MAX_HEADER_BYTES + MAX_RESPONSE_BYTES + TAG_BYTES; + private static final byte[] AAD_DOMAIN = + "firemud/account-response-envelope/aad/v1".getBytes(StandardCharsets.US_ASCII); + private static final byte[] BINDING_DOMAIN = + "firemud/account-response-envelope/binding/v1".getBytes(StandardCharsets.US_ASCII); + private static final Pattern SAFE_IDENTIFIER = Pattern.compile("[A-Za-z0-9._:/@+-]{1,256}"); + + private final AccountResponseEnvelopeKeyring keyring; + private final Clock clock; + private final SecureRandom secureRandom; + + @Autowired + public AccountResponseEnvelopeCryptography(AccountResponseEnvelopeKeyring keyring) { + this(keyring, Clock.systemUTC(), new SecureRandom()); + } + + AccountResponseEnvelopeCryptography( + AccountResponseEnvelopeKeyring keyring, Clock clock, SecureRandom secureRandom) { + this.keyring = Objects.requireNonNull(keyring, "keyring"); + this.clock = Objects.requireNonNull(clock, "clock"); + this.secureRandom = Objects.requireNonNull(secureRandom, "secureRandom"); + } + + /** Encrypts exact response bytes under the current active key and immutable operation expiry. */ + public EncryptedResponseEnvelope encrypt( + Binding binding, byte[] exactResponseBytes, Instant immutableRecoveryExpiry) { + Objects.requireNonNull(binding, "binding"); + validateResponse(exactResponseBytes); + long expiryMillis = exactEpochMillis(immutableRecoveryExpiry); + if (!clock.instant().isBefore(immutableRecoveryExpiry)) { + throw new IllegalArgumentException("Recovery expiry must be in the future when sealing"); + } + + AccountResponseEnvelopeKeyring.KeyEntry active = keyring.readCurrent().activeKey(); + byte[] nonce = new byte[NONCE_BYTES]; + secureRandom.nextBytes(nonce); + byte[] header = encodeHeader(active.keyId(), expiryMillis, nonce); + byte[] bindingBytes = canonicalBinding(binding); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, active.secretKey(), new GCMParameterSpec(TAG_BITS, nonce)); + cipher.updateAAD(associatedData(header, bindingBytes)); + byte[] ciphertext = cipher.doFinal(exactResponseBytes); + if (ciphertext.length != exactResponseBytes.length + TAG_BYTES) { + throw new CryptographyUnavailableException(); + } + return new EncryptedResponseEnvelope(concatenate(header, ciphertext)); + } catch (GeneralSecurityException ex) { + throw new CryptographyUnavailableException(); + } + } + + /** + * Decrypts only for the exact immutable owner binding and expiry read from the durable operation. + * The caller must establish current authorization and postconditions before invoking this method. + */ + public byte[] decrypt( + EncryptedResponseEnvelope envelope, Binding expectedBinding, Instant expectedRecoveryExpiry) { + Objects.requireNonNull(envelope, "envelope"); + Objects.requireNonNull(expectedBinding, "expectedBinding"); + long expectedExpiryMillis = exactEpochMillis(expectedRecoveryExpiry); + byte[] encoded = envelope.bytes(); + Header header = parseHeader(encoded); + if (header.expiryMillis() != expectedExpiryMillis) { + throw new IntegrityException(); + } + Instant now = clock.instant(); + if (!now.isBefore(expectedRecoveryExpiry)) { + throw new ResponseRecoveryExpiredException(); + } + + AccountResponseEnvelopeKeyring.KeyEntry key = + keyring.readCurrent().decryptionKey(header.keyId(), now); + byte[] ciphertext = Arrays.copyOfRange(encoded, header.headerLength(), encoded.length); + byte[] bindingBytes = canonicalBinding(expectedBinding); + try { + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init( + Cipher.DECRYPT_MODE, key.secretKey(), new GCMParameterSpec(TAG_BITS, header.nonce())); + cipher.updateAAD(associatedData(Arrays.copyOf(encoded, header.headerLength()), bindingBytes)); + return cipher.doFinal(ciphertext); + } catch (AEADBadTagException ex) { + throw new IntegrityException(); + } catch (GeneralSecurityException ex) { + throw new CryptographyUnavailableException(); + } + } + + private static byte[] encodeHeader(String keyId, long expiryMillis, byte[] nonce) { + byte[] keyIdBytes = keyId.getBytes(StandardCharsets.US_ASCII); + if (keyIdBytes.length == 0 || keyIdBytes.length > 32 || nonce.length != NONCE_BYTES) { + throw new CryptographyUnavailableException(); + } + ByteBuffer header = ByteBuffer.allocate(FIXED_HEADER_BYTES + keyIdBytes.length); + header.put(MAGIC); + header.put(FORMAT_VERSION); + header.put((byte) keyIdBytes.length); + header.put(keyIdBytes); + header.putLong(expiryMillis); + header.put(nonce); + return header.array(); + } + + private static Header parseHeader(byte[] encoded) { + if (encoded == null + || encoded.length < FIXED_HEADER_BYTES + 1 + TAG_BYTES + 1 + || encoded.length > MAX_ENVELOPE_BYTES) { + throw new IntegrityException(); + } + ByteBuffer input = ByteBuffer.wrap(encoded); + byte[] magic = new byte[MAGIC.length]; + input.get(magic); + if (!Arrays.equals(magic, MAGIC) || input.get() != FORMAT_VERSION) { + throw new IntegrityException(); + } + int keyIdLength = Byte.toUnsignedInt(input.get()); + if (keyIdLength < 1 + || keyIdLength > 32 + || input.remaining() < keyIdLength + Long.BYTES + NONCE_BYTES + TAG_BYTES + 1) { + throw new IntegrityException(); + } + byte[] keyIdBytes = new byte[keyIdLength]; + input.get(keyIdBytes); + for (byte value : keyIdBytes) { + if (Byte.toUnsignedInt(value) > 0x7e || Byte.toUnsignedInt(value) < 0x21) { + throw new IntegrityException(); + } + } + String keyId = new String(keyIdBytes, StandardCharsets.US_ASCII); + if (!keyId.matches("[A-Za-z0-9_-]{1,32}")) { + throw new IntegrityException(); + } + long expiryMillis = input.getLong(); + if (expiryMillis <= 0) { + throw new IntegrityException(); + } + byte[] nonce = new byte[NONCE_BYTES]; + input.get(nonce); + int ciphertextBytes = input.remaining(); + if (ciphertextBytes < TAG_BYTES + 1 || ciphertextBytes > MAX_RESPONSE_BYTES + TAG_BYTES) { + throw new IntegrityException(); + } + return new Header(keyId, expiryMillis, nonce, input.position()); + } + + private static byte[] canonicalBinding(Binding binding) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + output.write(BINDING_DOMAIN); + writeString(output, binding.operation()); + writeString(output, binding.requestId()); + writeBytes(output, binding.requestDigest()); + writeString(output, binding.callerWorkload()); + writeString(output, binding.bindingId()); + writeOptionalString(output, binding.lineageId()); + writeOptionalString(output, binding.replacementId()); + writeOptionalString(output, binding.leaseId()); + output.writeLong(binding.issuanceFence()); + writeBytes(output, binding.authorityTupleCanonicalBytes()); + writeBytes(output, binding.membershipVersionMapCanonicalBytes()); + writeBytes(output, binding.authorityEvidenceBundleCanonicalBytes()); + } catch (IOException ex) { + throw new IntegrityException(); + } + byte[] encoded = bytes.toByteArray(); + if (encoded.length > MAX_BINDING_BYTES) { + throw new IllegalArgumentException("Response-envelope binding exceeds its size bound"); + } + return encoded; + } + + private static void writeOptionalString(DataOutputStream output, Optional value) + throws IOException { + output.writeBoolean(value.isPresent()); + if (value.isPresent()) { + writeString(output, value.orElseThrow()); + } + } + + private static void writeString(DataOutputStream output, String value) throws IOException { + byte[] encoded = value.getBytes(StandardCharsets.US_ASCII); + output.writeInt(encoded.length); + output.write(encoded); + } + + private static void writeBytes(DataOutputStream output, byte[] value) throws IOException { + output.writeInt(value.length); + output.write(value); + } + + private static byte[] associatedData(byte[] header, byte[] binding) { + ByteBuffer aad = + ByteBuffer.allocate(AAD_DOMAIN.length + Integer.BYTES * 2 + header.length + binding.length); + aad.put(AAD_DOMAIN); + aad.putInt(header.length); + aad.put(header); + aad.putInt(binding.length); + aad.put(binding); + return aad.array(); + } + + private static byte[] concatenate(byte[] header, byte[] ciphertext) { + if (header.length + ciphertext.length > MAX_ENVELOPE_BYTES) { + throw new IllegalArgumentException("Response envelope exceeds its size bound"); + } + byte[] result = Arrays.copyOf(header, header.length + ciphertext.length); + System.arraycopy(ciphertext, 0, result, header.length, ciphertext.length); + return result; + } + + private static void validateResponse(byte[] response) { + if (response == null || response.length == 0 || response.length > MAX_RESPONSE_BYTES) { + throw new IllegalArgumentException("Response bytes are empty or exceed their size bound"); + } + } + + private static long exactEpochMillis(Instant instant) { + Objects.requireNonNull(instant, "immutableRecoveryExpiry"); + try { + long millis = instant.toEpochMilli(); + if (!Instant.ofEpochMilli(millis).equals(instant) || millis <= 0) { + throw new IllegalArgumentException("Recovery expiry must be a positive exact millisecond"); + } + return millis; + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Recovery expiry is outside the supported range"); + } + } + + private static void validateIdentifier(String value, String fieldName) { + if (value == null || !SAFE_IDENTIFIER.matcher(value).matches()) { + throw new IllegalArgumentException(fieldName + " is not a canonical identifier"); + } + } + + private static void validateOptional(Optional value, String fieldName) { + Objects.requireNonNull(value, fieldName); + value.ifPresent(item -> validateIdentifier(item, fieldName)); + } + + private record Header(String keyId, long expiryMillis, byte[] nonce, int headerLength) {} + + /** + * Immutable, typed operation binding. The owner must derive every field from durable evidence. + */ + public record Binding( + String operation, + String requestId, + byte[] requestDigest, + String callerWorkload, + String bindingId, + Optional lineageId, + Optional replacementId, + Optional leaseId, + long issuanceFence, + byte[] authorityTupleCanonicalBytes, + byte[] membershipVersionMapCanonicalBytes, + byte[] authorityEvidenceBundleCanonicalBytes) { + public Binding { + validateIdentifier(operation, "operation"); + validateIdentifier(requestId, "requestId"); + validateIdentifier(callerWorkload, "callerWorkload"); + validateIdentifier(bindingId, "bindingId"); + validateOptional(lineageId, "lineageId"); + validateOptional(replacementId, "replacementId"); + validateOptional(leaseId, "leaseId"); + if (requestDigest == null || requestDigest.length != 32) { + throw new IllegalArgumentException("requestDigest must contain exactly 32 bytes"); + } + if (authorityTupleCanonicalBytes == null + || authorityTupleCanonicalBytes.length == 0 + || authorityTupleCanonicalBytes.length > 8 * 1024) { + throw new IllegalArgumentException("authority tuple bytes are empty or exceed their bound"); + } + if (membershipVersionMapCanonicalBytes == null + || membershipVersionMapCanonicalBytes.length == 0 + || membershipVersionMapCanonicalBytes.length > 4 * 1024) { + throw new IllegalArgumentException( + "membership version map bytes are empty or exceed their bound"); + } + if (authorityEvidenceBundleCanonicalBytes == null + || authorityEvidenceBundleCanonicalBytes.length == 0 + || authorityEvidenceBundleCanonicalBytes.length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES) { + throw new IllegalArgumentException( + "authority evidence bundle bytes are empty or exceed their bound"); + } + if (issuanceFence <= 0) { + throw new IllegalArgumentException("issuanceFence must be positive"); + } + requestDigest = requestDigest.clone(); + authorityTupleCanonicalBytes = authorityTupleCanonicalBytes.clone(); + membershipVersionMapCanonicalBytes = membershipVersionMapCanonicalBytes.clone(); + authorityEvidenceBundleCanonicalBytes = authorityEvidenceBundleCanonicalBytes.clone(); + } + + @Override + public byte[] requestDigest() { + return requestDigest.clone(); + } + + @Override + public byte[] authorityTupleCanonicalBytes() { + return authorityTupleCanonicalBytes.clone(); + } + + @Override + public byte[] membershipVersionMapCanonicalBytes() { + return membershipVersionMapCanonicalBytes.clone(); + } + + @Override + public byte[] authorityEvidenceBundleCanonicalBytes() { + return authorityEvidenceBundleCanonicalBytes.clone(); + } + + @Override + public String toString() { + return "AccountResponseEnvelopeCryptography.Binding[redacted]"; + } + } + + /** Defensively copied opaque ciphertext; no response bytes are exposed through diagnostics. */ + public record EncryptedResponseEnvelope(byte[] bytes) { + public EncryptedResponseEnvelope { + if (bytes == null) { + throw new IllegalArgumentException("Envelope bytes are required"); + } + bytes = bytes.clone(); + } + + @Override + public byte[] bytes() { + return bytes.clone(); + } + + @Override + public String toString() { + return "EncryptedResponseEnvelope[redacted]"; + } + } + + /** Integrity/format failure; callers must fail closed and must not expose a token. */ + public static final class IntegrityException extends RuntimeException { + private IntegrityException() { + super("Account response envelope failed integrity validation"); + } + } + + /** Maps only the immutable owner-recorded response horizon to the canonical terminal outcome. */ + public static final class ResponseRecoveryExpiredException extends RuntimeException { + private ResponseRecoveryExpiredException() { + super("Account response recovery horizon has expired"); + } + + public String errorCode() { + return "RESPONSE_RECOVERY_EXPIRED"; + } + } + + /** Retryable provider/runtime failure, without including secret or response material. */ + public static final class CryptographyUnavailableException extends RuntimeException { + private CryptographyUnavailableException() { + super("Account response-envelope cryptography is unavailable"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java new file mode 100644 index 0000000000..ffcb7915a5 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java @@ -0,0 +1,291 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.time.Instant; +import java.util.Base64; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * Loads Account's separate response-envelope encryption ring from its mounted read-only directory. + */ +@Component +public final class AccountResponseEnvelopeKeyring { + static final int KEY_BYTES = 32; + static final int MAX_MANIFEST_BYTES = 16 * 1024; + static final int MAX_RETIRING_KEYS = 8; + private static final String MANIFEST_HEADER = "firemud-account-response-envelope-keyring-v1"; + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,32}"); + + private final String mountPath; + + @Autowired + public AccountResponseEnvelopeKeyring( + @Value("${firemud.account.response-envelope.keyring-path:}") String mountPath) { + this.mountPath = mountPath == null ? "" : mountPath; + } + + /** Reloads on every operation so a withdrawn or unreadable mounted key is never cached. */ + Snapshot readCurrent() { + if (mountPath.isBlank()) { + throw new KeyUnavailableException(); + } + try { + Path configuredRoot = Path.of(mountPath); + if (!configuredRoot.isAbsolute()) { + throw new KeyUnavailableException(); + } + Path mountRoot = configuredRoot.toRealPath(); + if (!Files.isDirectory(mountRoot, LinkOption.NOFOLLOW_LINKS)) { + throw new KeyUnavailableException(); + } + // Kubernetes projected Secrets use key -> ..data/key and ..data -> .. symlinks. + // Resolve that projection, but do not let its target leave this configured trust root. + Path projectedKey = mountRoot.resolve("keyring").toRealPath(); + if (!projectedKey.startsWith(mountRoot) + || !Files.isRegularFile(projectedKey, LinkOption.NOFOLLOW_LINKS)) { + throw new KeyUnavailableException(); + } + return parse(readBounded(projectedKey)); + } catch (KeyUnavailableException ex) { + throw ex; + } catch (Exception ex) { + throw new KeyUnavailableException(); + } + } + + private static byte[] readBounded(Path path) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try (SeekableByteChannel channel = + Files.newByteChannel(path, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS))) { + ByteBuffer buffer = ByteBuffer.allocate(1024); + int total = 0; + while (true) { + int count = channel.read(buffer); + if (count < 0) { + break; + } + if (count == 0) { + continue; + } + total += count; + if (total > MAX_MANIFEST_BYTES) { + throw new KeyUnavailableException(); + } + buffer.flip(); + output.write(buffer.array(), buffer.position(), buffer.remaining()); + buffer.clear(); + } + } + return output.toByteArray(); + } + + private static Snapshot parse(byte[] contents) { + if (contents.length == 0 || contents.length > MAX_MANIFEST_BYTES) { + throw new KeyUnavailableException(); + } + String text; + try { + text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(contents)) + .toString(); + } catch (CharacterCodingException ex) { + throw new KeyUnavailableException(); + } + if (text.indexOf('\r') >= 0 || text.indexOf('\0') >= 0 || text.startsWith("\uFEFF")) { + throw new KeyUnavailableException(); + } + for (int index = 0; index < text.length(); index++) { + char value = text.charAt(index); + if (value > 0x7e || (value < 0x20 && value != '\n')) { + throw new KeyUnavailableException(); + } + } + + String normalized = text.endsWith("\n") ? text.substring(0, text.length() - 1) : text; + if (normalized.isEmpty() || normalized.endsWith("\n")) { + throw new KeyUnavailableException(); + } + String[] lines = normalized.split("\n", -1); + if (!MANIFEST_HEADER.equals(lines[0]) || lines.length < 2) { + throw new KeyUnavailableException(); + } + + KeyEntry active = null; + Map allKeys = new HashMap<>(); + Set seenIds = new HashSet<>(); + int retiringCount = 0; + for (int index = 1; index < lines.length; index++) { + String line = lines[index]; + if (line.isEmpty()) { + throw new KeyUnavailableException(); + } + String[] fields = line.split(" ", -1); + if (fields.length == 3 && "active".equals(fields[0])) { + if (active != null) { + throw new KeyUnavailableException(); + } + if (index != 1) { + throw new KeyUnavailableException(); + } + KeyEntry entry = parseEntry(fields[1], fields[2], null); + if (!seenIds.add(entry.keyId())) { + throw new KeyUnavailableException(); + } + active = entry; + allKeys.put(entry.keyId(), entry); + } else if (fields.length == 4 && "retiring".equals(fields[0])) { + if (active == null) { + throw new KeyUnavailableException(); + } + retiringCount++; + if (retiringCount > MAX_RETIRING_KEYS) { + throw new KeyUnavailableException(); + } + long decryptUntilMillis; + try { + if (!fields[2].matches("[1-9][0-9]{0,18}")) { + throw new NumberFormatException(); + } + decryptUntilMillis = Long.parseLong(fields[2]); + if (decryptUntilMillis <= 0) { + throw new NumberFormatException(); + } + } catch (NumberFormatException ex) { + throw new KeyUnavailableException(); + } + Instant decryptUntil; + try { + decryptUntil = Instant.ofEpochMilli(decryptUntilMillis); + } catch (RuntimeException ex) { + throw new KeyUnavailableException(); + } + KeyEntry entry = parseEntry(fields[1], fields[3], decryptUntil); + if (!seenIds.add(entry.keyId())) { + throw new KeyUnavailableException(); + } + allKeys.put(entry.keyId(), entry); + } else { + throw new KeyUnavailableException(); + } + } + if (active == null) { + throw new KeyUnavailableException(); + } + return new Snapshot(active, allKeys); + } + + private static KeyEntry parseEntry(String keyId, String encodedKey, Instant decryptUntil) { + if (keyId == null || !KEY_ID.matcher(keyId).matches() || encodedKey == null) { + throw new KeyUnavailableException(); + } + byte[] keyMaterial; + try { + keyMaterial = Base64.getUrlDecoder().decode(encodedKey); + } catch (IllegalArgumentException ex) { + throw new KeyUnavailableException(); + } + if (keyMaterial.length != KEY_BYTES + || !Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(keyMaterial) + .equals(encodedKey)) { + java.util.Arrays.fill(keyMaterial, (byte) 0); + throw new KeyUnavailableException(); + } + KeyEntry entry = new KeyEntry(keyId, keyMaterial, decryptUntil); + java.util.Arrays.fill(keyMaterial, (byte) 0); + return entry; + } + + static final class Snapshot { + private final KeyEntry active; + private final Map keys; + + private Snapshot(KeyEntry active, Map keys) { + this.active = active; + this.keys = Map.copyOf(keys); + } + + String activeKeyId() { + return active.keyId(); + } + + KeyEntry activeKey() { + return active; + } + + KeyEntry decryptionKey(String keyId, Instant now) { + KeyEntry key = keys.get(keyId); + if (key == null || (key.decryptUntil() != null && !now.isBefore(key.decryptUntil()))) { + throw new KeyUnavailableException(); + } + return key; + } + + @Override + public String toString() { + return "AccountResponseEnvelopeKeyring.Snapshot[redacted]"; + } + } + + static final class KeyEntry { + private final String keyId; + private final byte[] keyMaterial; + private final Instant decryptUntil; + + private KeyEntry(String keyId, byte[] keyMaterial, Instant decryptUntil) { + this.keyId = keyId; + this.keyMaterial = keyMaterial.clone(); + this.decryptUntil = decryptUntil; + } + + String keyId() { + return keyId; + } + + Instant decryptUntil() { + return decryptUntil; + } + + javax.crypto.SecretKey secretKey() { + return new javax.crypto.spec.SecretKeySpec(keyMaterial.clone(), "AES"); + } + + @Override + public String toString() { + return "AccountResponseEnvelopeKeyring.KeyEntry[keyId=" + keyId + ", material=redacted]"; + } + } + + /** Retryable failure for absent, withdrawn, malformed, or unreadable mounted key material. */ + public static final class KeyUnavailableException extends RuntimeException { + private KeyUnavailableException() { + super("Account response-envelope encryption keyring is unavailable"); + } + + public String errorCode() { + return "AUTH_UNAVAILABLE"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java new file mode 100644 index 0000000000..40f6c2becf --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java @@ -0,0 +1,517 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.Snapshot; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.OwnerLinearization; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.Stored; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; + +/** Exact ADR 0047 Account authority evidence for the tenantAdmin StartSession branch. */ +public final class AccountStartSessionOperatorAuthorityBundle { + public static final String BUNDLE_VERSION = StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION; + public static final String HUMAN_EVIDENCE_TYPE = + StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE; + private static final Pattern DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + + private final StartSessionAuthorityEvidenceBundle decoded; + private final byte[] canonicalBytes; + private final Map value; + + private AccountStartSessionOperatorAuthorityBundle(StartSessionAuthorityEvidenceBundle decoded) { + this.decoded = Objects.requireNonNull(decoded, "shared authority bundle is required"); + this.canonicalBytes = decoded.canonicalBytes(); + this.value = decoded.jsonValue(); + } + + /** + * Builds the one supported human branch from Account's already-current source snapshot and the + * control-ui token row proven by {@link AccountControlUiActorService}. + */ + public static AccountStartSessionOperatorAuthorityBundle create( + StartSessionPreAuthorizationReservationTuple tuple, + Snapshot source, + Stored controlUiIssuance, + UUID issuanceOperationId, + OwnerLinearization linearization, + Instant issuedAt, + Instant referenceExpiresAt) { + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + Objects.requireNonNull(source, "current Account source is required"); + Objects.requireNonNull(controlUiIssuance, "current control-ui issuance is required"); + Objects.requireNonNull(issuanceOperationId, "issuance operation identity is required"); + Objects.requireNonNull(linearization, "Account owner linearization is required"); + requireTimeWindow(issuedAt, referenceExpiresAt); + + if (!tuple.actor().accountId().equals(source.actor()) + || !tuple.action().scope().tenantId().equals(source.tenant()) + || !controlUiIssuance.accountId.equals(source.actor()) + || !controlUiIssuance.tenantId.equals(source.tenant())) { + throw denied("Current Account and control-ui source must exactly match the typed actor"); + } + + Map claims = + AccountControlUiIssuanceRepository.object(controlUiIssuance.claims); + requireCurrentTenantClaims(tuple, source, controlUiIssuance, claims, false); + SourceEvidence accountSource = uniqueAccountSource(source, source.actor()); + BundleReference reference = + new BundleReference( + BUNDLE_VERSION, + accountSource.sourceVersion(), + Long.toString(linearization.sourceFence()), + linearization.transactionId()); + String sourceEvidenceId = + sourceEvidenceId(source.evidence(), accountSource.sourceVersion(), reference); + + Map typedScope = + Map.of( + "tenantId", tuple.action().scope().tenantId().toString(), + "targetNamespace", tuple.action().scope().targetNamespace()); + Map authorityScope = + Map.of( + "scope", typedScope, + "actionFamily", tuple.actionFamily(), + "applicableAccountId", source.actor().toString(), + "applicableTenantId", source.tenant().toString()); + Map projection = + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + sourceEvidenceId, + "sourceEvidenceVersion", + accountSource.sourceVersion(), + "projectionStatus", + "CURRENT", + "evaluatedAt", + issuedAt.toString(), + "expiresAt", + referenceExpiresAt.toString()); + Map operationIdentity = + Map.of( + "issuanceOperationId", issuanceOperationId.toString(), + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()); + Map humanEvidence = + humanTenantEvidence(source, controlUiIssuance.jti, claims, false); + + Map bundle = new LinkedHashMap<>(); + bundle.put("bundleVersion", BUNDLE_VERSION); + bundle.put("authorityScope", authorityScope); + bundle.put("accountProjectionEvidence", projection); + bundle.put("issuanceOperationIdentity", operationIdentity); + bundle.put("issuanceKind", "human_operator"); + bundle.put("authorityTuple", source.authorityTuple()); + bundle.put("membershipVersion", source.membershipVersion()); + bundle.put("issuanceFence", reference.sourceFence()); + bundle.put("issuanceEvidence", humanEvidence); + byte[] encoded = AccountControlUiAuthority.canonical(bundle); + AccountStartSessionOperatorAuthorityBundle result = decode(encoded); + result.requireTupleBinding(tuple); + result.requireReferenceBinding(reference); + result.requireCurrent(source, controlUiIssuance, tuple, reference, issuedAt); + return result; + } + + /** Strictly decodes one closed canonical authorityEvidenceBundle/v1 value. */ + public static AccountStartSessionOperatorAuthorityBundle decode(byte[] exactCanonicalBytes) { + return new AccountStartSessionOperatorAuthorityBundle( + StartSessionAuthorityEvidenceBundle.decode(exactCanonicalBytes)); + } + + /** Compares every snapshot-bound authority projection and the exact original source reference. */ + public void requireCurrent( + Snapshot currentSource, + Stored currentControlUiIssuance, + StartSessionPreAuthorizationReservationTuple tuple, + BundleReference originalReference, + Instant now) { + Objects.requireNonNull(currentSource, "current Account source is required"); + Objects.requireNonNull(currentControlUiIssuance, "current control-ui issuance is required"); + Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + Objects.requireNonNull(originalReference, "original Account source reference is required"); + Objects.requireNonNull(now, "current time is required"); + decoded.requireTupleBinding(tuple); + decoded.requireReferenceBinding(toSharedReference(originalReference)); + try { + Map projection = + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); + if (!now.isBefore(originalReferenceExpiresAt()) + || !now.isBefore(instant(string(projection.get("expiresAt"), "projection expiry")))) { + throw denied(true, "Original Account authority evidence is expired"); + } + if (!tuple.actor().accountId().equals(currentSource.actor()) + || !tuple.action().scope().tenantId().equals(currentSource.tenant()) + || !currentControlUiIssuance.accountId.equals(currentSource.actor()) + || !currentControlUiIssuance.tenantId.equals(currentSource.tenant())) { + throw denied(true, "Current Account actor or tenant changed"); + } + Map claims = + AccountControlUiIssuanceRepository.object(currentControlUiIssuance.claims); + requireCurrentTenantClaims(tuple, currentSource, currentControlUiIssuance, claims, true); + SourceEvidence source = uniqueAccountSource(currentSource, currentSource.actor()); + if (!source.sourceVersion().equals(projection.get("sourceEvidenceVersion")) + || !source.sourceVersion().equals(originalReference.sourceVersion()) + || !sourceEvidenceId(currentSource.evidence(), source.sourceVersion(), originalReference) + .equals(projection.get("sourceEvidenceId")) + || !canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) + || !canonicalEquals(currentSource.membershipVersion(), value.get("membershipVersion"))) { + throw denied(true, "Current Account source, generation, or membership changed"); + } + Map expectedEvidence = + humanTenantEvidence(currentSource, currentControlUiIssuance.jti, claims, true); + if (!canonicalEquals(expectedEvidence, value.get("issuanceEvidence"))) { + throw denied(true, "Current human authority evidence changed"); + } + } catch (IllegalArgumentException malformedCurrentAuthority) { + throw new IllegalStateException( + "Current Account authorization evidence is unavailable", malformedCurrentAuthority); + } + } + + /** Current-state proof for a same-attempt replay after the exact response envelope horizon. */ + public void requireCurrentSnapshotForExactReplay( + Snapshot currentSource, + Stored currentControlUiIssuance, + StartSessionPreAuthorizationReservationTuple tuple, + BundleReference originalReference) { + Objects.requireNonNull(currentSource, "current Account source is required"); + Objects.requireNonNull(currentControlUiIssuance, "current control-ui issuance is required"); + Objects.requireNonNull(originalReference, "original Account source reference is required"); + decoded.requireTupleBinding(tuple); + decoded.requireReferenceBinding(toSharedReference(originalReference)); + try { + if (!tuple.actor().accountId().equals(currentSource.actor()) + || !tuple.action().scope().tenantId().equals(currentSource.tenant()) + || !currentControlUiIssuance.accountId.equals(currentSource.actor()) + || !currentControlUiIssuance.tenantId.equals(currentSource.tenant())) { + throw denied(true, "Current Account actor or tenant changed"); + } + Map claims = + AccountControlUiIssuanceRepository.object(currentControlUiIssuance.claims); + requireCurrentTenantClaims(tuple, currentSource, currentControlUiIssuance, claims, true); + SourceEvidence accountSource = uniqueAccountSource(currentSource, currentSource.actor()); + Map projection = + object(value.get("accountProjectionEvidence"), "accountProjectionEvidence"); + if (!accountSource.sourceVersion().equals(originalReference.sourceVersion()) + || !accountSource.sourceVersion().equals(projection.get("sourceEvidenceVersion")) + || !sourceEvidenceId( + currentSource.evidence(), accountSource.sourceVersion(), originalReference) + .equals(projection.get("sourceEvidenceId")) + || !canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple")) + || !canonicalEquals(currentSource.membershipVersion(), value.get("membershipVersion")) + || !canonicalEquals( + humanTenantEvidence(currentSource, currentControlUiIssuance.jti, claims, true), + value.get("issuanceEvidence"))) { + throw denied(true, "Current Account source differs from the consumed authorization"); + } + } catch (IllegalArgumentException malformedCurrentAuthority) { + throw new IllegalStateException( + "Current Account authorization evidence is unavailable", malformedCurrentAuthority); + } + } + + /** Enforces request tuple equality separately from the authority projection. */ + public void requireTupleBinding(StartSessionPreAuthorizationReservationTuple tuple) { + decoded.requireTupleBinding(tuple); + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public BundleReference referenceForSource(Snapshot source, OwnerLinearization linearization) { + SourceEvidence accountSource = uniqueAccountSource(source, source.actor()); + BundleReference reference = + new BundleReference( + BUNDLE_VERSION, + accountSource.sourceVersion(), + Long.toString(linearization.sourceFence()), + linearization.transactionId()); + requireReferenceBinding(reference); + if (!sourceEvidenceId(source.evidence(), accountSource.sourceVersion(), reference) + .equals(sourceEvidenceId())) { + throw denied("Account source reference does not identify this captured source"); + } + return reference; + } + + public Map authorityTuple() { + return decoded.authorityTuple(); + } + + public Map membershipVersion() { + return decoded.membershipVersion(); + } + + public UUID issuanceOperationId() { + return decoded.issuanceOperationId(); + } + + public String controlPlaneRequestId() { + return decoded.controlPlaneRequestId(); + } + + public String authorizationExpiresAt() { + return decoded.authorizationExpiresAt(); + } + + public String sourceEvidenceId() { + return decoded.sourceEvidenceId(); + } + + public String sourceEvidenceVersion() { + return decoded.sourceEvidenceVersion(); + } + + public UUID controlUiTokenJti() { + return decoded.controlUiTokenJti(); + } + + public Map jsonValue() { + return decoded.jsonValue(); + } + + private Instant originalReferenceExpiresAt() { + return decoded.expiresAt(); + } + + private void requireReferenceBinding(BundleReference reference) { + decoded.requireReferenceBinding(toSharedReference(reference)); + } + + static StartSessionAuthorityEvidenceBundle.BundleReference toSharedReference( + BundleReference reference) { + Objects.requireNonNull(reference, "original Account source reference is required"); + return new StartSessionAuthorityEvidenceBundle.BundleReference( + reference.bundleVersion(), + reference.sourceVersion(), + reference.sourceFence(), + reference.linearization()); + } + + static BundleReference fromSharedReference( + StartSessionAuthorityEvidenceBundle.BundleReference reference) { + Objects.requireNonNull(reference, "original Account source reference is required"); + return new BundleReference( + reference.bundleVersion(), + reference.sourceVersion(), + reference.sourceFence(), + reference.linearization()); + } + + private static void requireCurrentTenantClaims( + StartSessionPreAuthorizationReservationTuple tuple, + Snapshot source, + Stored stored, + Map claims, + boolean currentState) { + if (!tuple.actor().accountId().equals(stored.accountId) + || !tuple.actor().accountId().equals(source.actor()) + || !tuple.action().scope().tenantId().equals(stored.tenantId) + || !tuple.action().scope().tenantId().equals(source.tenant()) + || !stored.jti.toString().equals(claims.get("jti")) + || !stored.accountId.toString().equals(claims.get("sub")) + || !stored.accountId.toString().equals(claims.get("accountId")) + || !"control-ui".equals(claims.get("aud")) + || positiveNumber(claims.get("tokenGeneration"), "tokenGeneration") != 1L + || claims.containsKey("assurance") + || claims.containsKey("globalRoles") + || !Map.of(stored.tenantId.toString(), List.of("tenantAdmin")) + .equals(claims.get("scopedRoles")) + || !canonicalEquals(source.authorityTuple(), claims.get("authorityTuple")) + || !canonicalEquals(source.membershipVersion(), claims.get("membershipVersion"))) { + throw denied(currentState, "Current tenantAdmin control-ui evidence is required"); + } + } + + private static Map humanTenantEvidence( + Snapshot source, UUID tokenJti, Map claims, boolean currentState) { + if (claims.containsKey("assurance") || claims.containsKey("globalRoles")) { + throw denied(currentState, "Tenant authority must omit assurance and global-role evidence"); + } + Map tuple = source.authorityTuple(); + long accountGeneration = + positiveNumber(tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + Map tenantGenerations = + object(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + if (!tenantGenerations.keySet().equals(Set.of(source.tenant().toString()))) { + throw denied(currentState, "Exact selected tenant authority generation is required"); + } + long tenantGeneration = + positiveNumber( + tenantGenerations.get(source.tenant().toString()), "tenantAuthorityGeneration"); + Map evidence = new LinkedHashMap<>(); + evidence.put("evidenceType", HUMAN_EVIDENCE_TYPE); + evidence.put("actorAccountId", source.actor().toString()); + evidence.put("controlUiTokenJti", tokenJti.toString()); + evidence.put("role", "tenantAdmin"); + evidence.put("accountGeneration", Long.toString(accountGeneration)); + evidence.put("tenantGeneration", Long.toString(tenantGeneration)); + return Map.copyOf(evidence); + } + + private static String sourceEvidenceId( + byte[] sourceEvidence, String sourceVersion, BundleReference reference) { + Map value = + Map.of( + "schema", + "account-authority-source-linearization/v1", + "sourceType", + "ACCOUNT", + "sourceEvidenceBytesBase64", + Base64.getEncoder().encodeToString(sourceEvidence), + "sourceVersion", + sourceVersion, + "sourceFence", + reference.sourceFence(), + "transactionId", + reference.linearization()); + try { + byte[] digest = + MessageDigest.getInstance("SHA-256").digest(AccountControlUiAuthority.canonical(value)); + return "sha256:" + java.util.HexFormat.of().formatHex(digest); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static SourceEvidence uniqueAccountSource(Snapshot source, UUID actor) { + List matches = + source.sources().stream() + .filter( + candidate -> + candidate.kind() == SourceKind.ACCOUNT + && actor.toString().equals(candidate.scopeId())) + .toList(); + if (matches.size() != 1) { + throw denied("One exact Account source version for the human actor is required"); + } + return matches.getFirst(); + } + + private static void requireTimeWindow(Instant issuedAt, Instant expiresAt) { + Objects.requireNonNull(issuedAt, "issue time is required"); + Objects.requireNonNull(expiresAt, "reference expiry is required"); + if (!issuedAt.isAfter(Instant.EPOCH) + || !expiresAt.isAfter(issuedAt) + || issuedAt.getNano() % 1_000_000 != 0 + || expiresAt.getNano() % 1_000_000 != 0) { + throw denied("Operator evidence timestamps must be positive exact milliseconds"); + } + } + + private static Instant instant(String value) { + try { + Instant parsed = Instant.parse(value); + if (!parsed.toString().equals(value)) { + throw denied("Timestamp is not canonical UTC text"); + } + return parsed; + } catch (RuntimeException malformed) { + throw denied("Timestamp is malformed"); + } + } + + private static boolean canonicalEquals(Object first, Object second) { + if (first == null || second == null) return false; + return MessageDigest.isEqual( + AccountControlUiAuthority.canonical(first), AccountControlUiAuthority.canonical(second)); + } + + @SuppressWarnings("unchecked") + private static Map object(Object value, String field) { + if (!(value instanceof Map map) + || map.keySet().stream().anyMatch(key -> !(key instanceof String))) { + throw denied(field + " must be an object"); + } + return (Map) map; + } + + private static void requireFields(Map value, Set fields, String field) { + if (value == null || !value.keySet().equals(fields)) { + throw denied(field + " has missing or unsupported fields"); + } + } + + private static String string(Object value, String field) { + if (!(value instanceof String text) || text.isEmpty()) { + throw denied(field + " must be a nonempty string"); + } + return text; + } + + private static long positiveNumber(Object value, String field) { + try { + long parsed; + if (value instanceof Number number) { + parsed = Long.parseLong(number.toString()); + } else if (value instanceof String text && DECIMAL.matcher(text).matches()) { + parsed = Long.parseLong(text); + } else { + throw new NumberFormatException(); + } + if (parsed <= 0) throw new NumberFormatException(); + return parsed; + } catch (RuntimeException malformed) { + throw denied(field + " must be a positive canonical integer"); + } + } + + private static IllegalArgumentException denied(String message) { + return new IllegalArgumentException(message); + } + + private static RuntimeException denied(boolean currentState, String message) { + return currentState ? new IllegalStateException(message) : denied(message); + } + + /** Original source reference is a separate typed object, not an extra bundle member. */ + public record BundleReference( + String bundleVersion, String sourceVersion, String sourceFence, String linearization) { + public BundleReference { + new StartSessionAuthorityEvidenceBundle.BundleReference( + bundleVersion, sourceVersion, sourceFence, linearization); + } + + public Map asJsonValue() { + return Map.of( + "bundleVersion", bundleVersion, + "sourceVersion", sourceVersion, + "sourceFence", sourceFence, + "linearization", linearization); + } + + public static BundleReference fromJsonValue(Object raw) { + Map value = object(raw, "bundleReference"); + requireFields( + value, + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization"), + "bundleReference"); + return new BundleReference( + string(value.get("bundleVersion"), "bundleVersion"), + string(value.get("sourceVersion"), "sourceVersion"), + string(value.get("sourceFence"), "sourceFence"), + string(value.get("linearization"), "linearization")); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java new file mode 100644 index 0000000000..a4bb79030e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java @@ -0,0 +1,1322 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient.Purpose; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceRecord; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.Status; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.Current; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.OwnerLinearization; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.Binding; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Conditionally composed Account owner service for the approved human StartSession path. Its Spring + * composition and receiving transport are disabled by default; every public operation authenticates + * the immediate certificate-derived peer before parsing request data or opening Account storage. + */ +public final class AccountStartSessionOperatorAuthorizationService { + private static final String ENVELOPE_OPERATION = "human-start-session-authorization/v1"; + private static final int REFERENCE_RANDOM_BYTES = 32; + private static final int MAX_REFERENCE_TEXT_BYTES = 128; + private static final Pattern REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final Pattern SAFE_ENVELOPE_REQUEST_ID = + Pattern.compile("[A-Za-z0-9._:/@+-]{1,256}"); + private static final Set RESPONSE_FIELDS = + Set.of( + "operatorAuthorizationReference", + "authorizationReferenceFingerprint", + "expiresAt", + "authorityEvidenceBundle", + "bundleReference"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountControlUiActorService actors; + private final AccountControlUiIssuanceRepository issuanceOperations; + private final StartSessionReservationEvidenceClient reservationEvidence; + private final AccountStartSessionOperatorAuthorizationRepository repository; + private final AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys; + private final AccountResponseEnvelopeCryptography responseCryptography; + private final AccountHostedTermsService hostedTerms; + private final TransactionTemplate lookupTransaction; + private final Clock clock; + private final SecureRandom secureRandom; + private final String loggingPeerUri; + private final String gameSessionPeerUri; + private final String gameDesignPeerUri; + private final long referenceLifetimeMillis; + private final long responseRecoveryWindowMillis; + + /** + * All custody and timing inputs are explicit. In particular, this service does not reuse the + * control-ui envelope instance, create or discover HMAC keys, or provide policy defaults. + */ + public AccountStartSessionOperatorAuthorizationService( + AccountControlUiActorService actors, + AccountControlUiIssuanceRepository issuanceOperations, + StartSessionReservationEvidenceClient reservationEvidence, + AccountStartSessionOperatorAuthorizationRepository repository, + AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, + AccountResponseEnvelopeCryptography dedicatedOperatorResponseCryptography, + AccountHostedTermsService hostedTerms, + PlatformTransactionManager transactions, + Clock clock, + SecureRandom secureRandom, + String exactLoggingPeerUri, + String exactGameSessionPeerUri, + Duration referenceLifetime, + Duration responseRecoveryWindow) { + this.actors = Objects.requireNonNull(actors, "current Account actor service is required"); + this.issuanceOperations = + Objects.requireNonNull(issuanceOperations, "Account control-ui issuance owner is required"); + this.reservationEvidence = + Objects.requireNonNull(reservationEvidence, "Logging claim evidence client is required"); + this.repository = Objects.requireNonNull(repository, "Account owner repository is required"); + this.fingerprintKeys = + Objects.requireNonNull(fingerprintKeys, "explicit Account fingerprint keyring is required"); + responseCryptography = + Objects.requireNonNull( + dedicatedOperatorResponseCryptography, + "separate operator response-envelope cryptography is required"); + this.hostedTerms = + Objects.requireNonNull(hostedTerms, "Account environment source is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + this.secureRandom = Objects.requireNonNull(secureRandom, "secure random is required"); + loggingPeerUri = exactPeer(exactLoggingPeerUri, "logging-admin-service"); + gameSessionPeerUri = exactPeer(exactGameSessionPeerUri, "game-session-service"); + gameDesignPeerUri = sameNamespacePeer(gameSessionPeerUri, "game-design-service"); + referenceLifetimeMillis = policyMillis(referenceLifetime, "reference lifetime", 5 * 60_000L); + responseRecoveryWindowMillis = + policyMillis(responseRecoveryWindow, "response recovery window", 60_000L); + lookupTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + lookupTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * ISSUE: current exact Logging peer, fresh original claim, current actor, one owner transaction. + */ + public AuthorizationResponse issue(IssueRequest request) { + requirePeer(loggingPeerUri); + Objects.requireNonNull(request, "issue request is required"); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(request.canonicalTupleBytes()); + requirePositiveFence(request.reservationClaimFence(), "reservationClaimFence"); + requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId"); + ReadCurrentClaimEvidenceResponse claim = + reservationEvidence.readCurrentClaimEvidence( + tuple, + request.reservationOwnerId(), + request.reservationClaimFence(), + request.claimOwnerId(), + request.claimFence(), + Purpose.ISSUE); + requireClaimEcho( + claim, + tuple, + request.reservationOwnerId(), + request.reservationClaimFence(), + request.claimOwnerId(), + request.claimFence()); + + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + IssuePreparation preparation = + actors.withCurrent( + request.controlUiJwt(), + tuple.action().scope().tenantId(), + environment, + current -> { + IssuanceRecord existing = findRecord(tuple.controlPlaneRequestId()).orElse(null); + OwnerLinearization linearization = + existing == null ? issuanceOperations.captureOwnerLinearization() : null; + return new IssuePreparation(current, existing, linearization); + }); + + if (preparation.existing() != null) { + IssuanceRecord original = preparation.existing(); + requireOriginalBinding( + original, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AuthorizationResponse response = openOriginalResponse(tuple, original); + return actors.withCurrent( + request.controlUiJwt(), + tuple.action().scope().tenantId(), + environment, + current -> { + requireSameCurrent(preparation.current(), current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(original, exact); + requireOriginalBinding( + exact, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) + .requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + original.bundleReference()), + clock.instant()); + return response; + }); + } + + PreparedIssuance candidate = + prepareIssuance(preparation.current(), tuple, request, preparation.linearization()); + IssueOutcome outcome = + actors.withCurrent( + request.controlUiJwt(), + tuple.action().scope().tenantId(), + environment, + current -> { + requireSameCurrent(preparation.current(), current); + candidate + .bundle() + .requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + candidate.candidate().bundleReference()), + clock.instant()); + var created = repository.createOrReadExact(candidate.candidate()); + requireOriginalBinding( + created.issuance(), + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + if (created.created()) { + requireCandidateRecord(candidate.candidate(), created.issuance()); + } + return new IssueOutcome(created.created(), created.issuance()); + }); + if (outcome.created()) { + return candidate.response(); + } + + AuthorizationResponse response = openOriginalResponse(tuple, outcome.issuance()); + return actors.withCurrent( + request.controlUiJwt(), + tuple.action().scope().tenantId(), + environment, + current -> { + requireSameCurrent(preparation.current(), current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(outcome.issuance(), exact); + AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) + .requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()), + clock.instant()); + return response; + }); + } + + /** + * RECOVER: lookup-only, fresh recovery claim, current original actor, exact original response. + */ + public AuthorizationResponse recover(RecoverRequest request) { + requirePeer(loggingPeerUri); + Objects.requireNonNull(request, "recovery request is required"); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(request.canonicalTupleBytes()); + requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId"); + requirePositiveFence(request.reservationClaimFence(), "reservationClaimFence"); + requireNonNilUuid(request.claimOwnerId(), "claimOwnerId"); + requirePositiveFence(request.claimFence(), "claimFence"); + ReadCurrentClaimEvidenceResponse claim = + reservationEvidence.readCurrentClaimEvidence( + tuple, + request.reservationOwnerId(), + request.reservationClaimFence(), + request.claimOwnerId(), + request.claimFence(), + Purpose.RECOVER); + requireClaimEcho( + claim, + tuple, + request.reservationOwnerId(), + request.reservationClaimFence(), + request.claimOwnerId(), + request.claimFence()); + + IssuanceRecord observed = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireOriginalBinding( + observed, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(observed.authorityEvidenceBundle()); + bundle.requireTupleBinding(tuple); + UUID tokenJti = bundle.controlUiTokenJti(); + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + Current preparation = + actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + tokenJti, + environment, + current -> { + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(observed, exact); + requireOriginalBinding( + exact, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + return current; + }); + AuthorizationResponse response = openOriginalResponse(tuple, observed); + return actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + tokenJti, + environment, + current -> { + requireSameCurrent(preparation, current); + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(observed, exact); + requireOriginalBinding( + exact, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()) + .requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()), + clock.instant()); + return response; + }); + } + + /** REDEEM: exact Game Session peer before tuple parsing or durable reference lookup. */ + public RedemptionResult redeem(RedeemRequest request) { + requirePeer(gameSessionPeerUri); + Objects.requireNonNull(request, "redemption request is required"); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(request.canonicalTupleBytes()); + String reference = requireReference(request.operatorAuthorizationReference()); + byte[] referenceBytes = reference.getBytes(StandardCharsets.US_ASCII); + try { + requireFingerprint(request.authorizationReferenceFingerprint()); + requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId"); + requirePositiveFence(request.reservationClaimFence(), "reservationClaimFence"); + requireNonNilUuid(request.ownerAttemptId(), "ownerAttemptId"); + requirePositiveFence(request.ownerFence(), "ownerFence"); + + IssuanceRecord observed = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireOriginalBinding( + observed, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + boolean sameAttemptReplay = + observed.status() == Status.REDEEMED + && gameSessionPeerUri.equals(observed.redemptionRedeemerWorkloadUri()) + && request.ownerAttemptId().equals(observed.redemptionOwnerAttemptId()) + && Objects.equals( + Long.valueOf(request.ownerFence()), observed.redemptionOwnerFence()); + if (observed.status() == Status.REDEEMED && !sameAttemptReplay) { + throw denied("A consumed StartSession reference cannot authorize another owner attempt"); + } + if (!fingerprintKeys.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + referenceBytes, + observed.authorizationReferenceFingerprint(), + observed.referenceExpiresAt(), + observed.responseEnvelopeExpiresAt())) { + throw denied("Original Account authorization reference does not match"); + } + if (!constantTimeEquals( + observed.authorizationReferenceFingerprint(), + request.authorizationReferenceFingerprint())) { + throw denied("Forwarded Account authorization fingerprint changed"); + } + + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(observed.authorityEvidenceBundle()); + bundle.requireTupleBinding(tuple); + var originalResponse = tryOpenOriginalResponse(observed, bundle, tuple); + if (originalResponse.isEmpty() && !sameAttemptReplay) { + throw denied("Original Account issuance response is no longer recoverable"); + } + if (originalResponse.isPresent() + && !constantTimeEquals( + reference, originalResponse.orElseThrow().operatorAuthorizationReference())) { + throw denied("Redeemed opaque reference differs from the original Account response"); + } + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + return actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + bundle.controlUiTokenJti(), + environment, + current -> { + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredIssuance(observed, exact); + requireOriginalBinding( + exact, + tuple, + request.canonicalTupleBytes(), + request.reservationOwnerId(), + request.reservationClaimFence()); + Instant currentInstant = clock.instant(); + if (sameAttemptReplay + && (originalResponse.isEmpty() + || !currentInstant.isBefore(observed.referenceExpiresAt()))) { + bundle.requireCurrentSnapshotForExactReplay( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + observed.bundleReference())); + } else { + bundle.requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + observed.bundleReference()), + currentInstant); + } + RedemptionResult result = + repository.redeemExact( + new RedemptionRequest( + tuple.controlPlaneRequestId(), + request.canonicalTupleBytes(), + observed.authorizationReferenceFingerprint(), + observed.reservationOwnerId(), + observed.reservationClaimFence(), + gameSessionPeerUri, + request.ownerAttemptId(), + request.ownerFence(), + observed.authorityEvidenceBundle(), + currentInstant)); + requireRedemptionProjection(result, observed); + if (sameAttemptReplay != result.replay()) { + throw denied("Account returned a changed one-time redemption outcome"); + } + return result; + }); + } finally { + Arrays.fill(referenceBytes, (byte) 0); + } + } + + /** + * Returns only the immutable original projection of an already-redeemed operation to the exact + * same-namespace Game Design peer. This read neither exposes a credential nor changes owner + * state; Account independently revalidates the original committed actor and source. + */ + public RedeemedOperationProjection readRedeemedOperationProjection( + ReadRedeemedOperationProjectionRequest request) { + requirePeer(gameDesignPeerUri); + Objects.requireNonNull(request, "redeemed operation projection request is required"); + byte[] exactTupleBytes = request.canonicalPreAuthorizationTuple(); + StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(exactTupleBytes); + requireFingerprint(request.authorizationReferenceFingerprint()); + requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId"); + requirePositiveFence(request.reservationClaimFence(), "reservationClaimFence"); + requireNonNilUuid(request.ownerAttemptId(), "ownerAttemptId"); + requirePositiveFence(request.ownerFence(), "ownerFence"); + if (!"game-session-service".equals(tuple.targetOwner())) { + throw denied("Operation projection is limited to the Game Session owner"); + } + + IssuanceRecord observed = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireOriginalBinding( + observed, + tuple, + exactTupleBytes, + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(observed.authorityEvidenceBundle()); + bundle.requireTupleBinding(tuple); + requireRedeemedProjectionBinding(observed, tuple, request, bundle, clock.instant()); + + var environment = hostedTerms.captureCurrentEnvironmentBoundary(); + return actors.withCurrentCommitted( + tuple.actor().accountId(), + tuple.action().scope().tenantId(), + bundle.controlUiTokenJti(), + environment, + current -> { + IssuanceRecord exact = + findRecord(tuple.controlPlaneRequestId()).orElseThrow(NotFoundException::new); + requireSameStoredRedemption(observed, exact); + requireOriginalBinding( + exact, + tuple, + exactTupleBytes, + request.reservationOwnerId(), + request.reservationClaimFence()); + AccountStartSessionOperatorAuthorityBundle exactBundle = + AccountStartSessionOperatorAuthorityBundle.decode(exact.authorityEvidenceBundle()); + exactBundle.requireTupleBinding(tuple); + requireRedeemedProjectionBinding(exact, tuple, request, exactBundle, clock.instant()); + exactBundle.requireCurrent( + current.source(), + current.stored(), + tuple, + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + exact.bundleReference()), + clock.instant()); + return projection(exact); + }); + } + + private PreparedIssuance prepareIssuance( + Current current, + StartSessionPreAuthorizationReservationTuple tuple, + IssueRequest request, + OwnerLinearization linearization) { + Objects.requireNonNull(linearization, "Account owner source linearization is required"); + byte[] exactTuple = request.canonicalTupleBytes(); + Instant issuedAt = Instant.ofEpochMilli(clock.millis()); + Instant referenceExpiresAt = addMillis(issuedAt, referenceLifetimeMillis); + Instant responseExpiresAt = addMillis(referenceExpiresAt, responseRecoveryWindowMillis); + UUID issuanceOperationId = UUID.randomUUID(); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + tuple, + current.source(), + current.stored(), + issuanceOperationId, + linearization, + issuedAt, + referenceExpiresAt); + var bundleReference = bundle.referenceForSource(current.source(), linearization); + + byte[] random = new byte[REFERENCE_RANDOM_BYTES]; + secureRandom.nextBytes(random); + String authorizationReference = Base64.getUrlEncoder().withoutPadding().encodeToString(random); + Arrays.fill(random, (byte) 0); + byte[] referenceBytes = authorizationReference.getBytes(StandardCharsets.US_ASCII); + byte[] responseBytes = null; + try { + String fingerprint = + fingerprintKeys.fingerprintForIssue(ReferenceKind.HUMAN_OPERATOR, referenceBytes); + AuthorizationResponse response = + new AuthorizationResponse( + authorizationReference, + fingerprint, + referenceExpiresAt, + bundle.canonicalBytes(), + bundleReference); + responseBytes = encodeResponse(response); + EncryptedResponseEnvelope envelope = + responseCryptography.encrypt( + responseBinding( + issuanceOperationId, + tuple, + exactTuple, + loggingPeerUri, + linearization.sourceFence(), + bundle), + responseBytes, + responseExpiresAt); + IssuanceCandidate candidate = + new IssuanceCandidate( + tuple.controlPlaneRequestId(), + exactTuple, + tuple.mutationDigest(), + loggingPeerUri, + request.reservationOwnerId(), + request.reservationClaimFence(), + issuanceOperationId, + linearization.sourceFence(), + AccountStartSessionOperatorAuthorityBundle.toSharedReference(bundleReference), + bundle.canonicalBytes(), + fingerprint, + envelope.bytes(), + issuedAt, + referenceExpiresAt, + responseExpiresAt); + return new PreparedIssuance(bundle, response, candidate); + } finally { + Arrays.fill(referenceBytes, (byte) 0); + if (responseBytes != null) Arrays.fill(responseBytes, (byte) 0); + } + } + + private AuthorizationResponse openOriginalResponse( + StartSessionPreAuthorizationReservationTuple tuple, IssuanceRecord record) { + if (record.responseEnvelopeErasedAt() != null) { + throw new ResponseEnvelopeErasedException(); + } + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(record.authorityEvidenceBundle()); + bundle.requireTupleBinding(tuple); + byte[] plaintext = null; + try { + plaintext = + responseCryptography.decrypt( + new EncryptedResponseEnvelope(record.encryptedResponseEnvelope()), + responseBinding( + record.issuanceOperationId(), + tuple, + record.preAuthorizationTuple(), + record.issuanceWorkloadUri(), + record.issuanceFence(), + bundle), + record.responseEnvelopeExpiresAt()); + AuthorizationResponse response = decodeResponse(plaintext); + requireResponseMatchesRecord(response, record); + return response; + } finally { + if (plaintext != null) Arrays.fill(plaintext, (byte) 0); + } + } + + private Optional tryOpenOriginalResponse( + IssuanceRecord record, + AccountStartSessionOperatorAuthorityBundle bundle, + StartSessionPreAuthorizationReservationTuple tuple) { + if (record.responseEnvelopeErasedAt() != null + || !clock.instant().isBefore(record.responseEnvelopeExpiresAt())) { + return Optional.empty(); + } + byte[] plaintext = null; + try { + plaintext = + responseCryptography.decrypt( + new EncryptedResponseEnvelope(record.encryptedResponseEnvelope()), + responseBinding( + record.issuanceOperationId(), + tuple, + record.preAuthorizationTuple(), + record.issuanceWorkloadUri(), + record.issuanceFence(), + bundle), + record.responseEnvelopeExpiresAt()); + AuthorizationResponse response = decodeResponse(plaintext); + requireResponseMatchesRecord(response, record); + return Optional.of(response); + } catch (AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException expired) { + return Optional.empty(); + } finally { + if (plaintext != null) Arrays.fill(plaintext, (byte) 0); + } + } + + private Binding responseBinding( + UUID operationId, + StartSessionPreAuthorizationReservationTuple tuple, + byte[] exactTuple, + String callerWorkload, + long issuanceFence, + AccountStartSessionOperatorAuthorityBundle bundle) { + return new Binding( + ENVELOPE_OPERATION, + envelopeBindingRequestId(tuple.controlPlaneRequestId()), + sha256(exactTuple), + callerWorkload, + operationId.toString(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + issuanceFence, + AccountControlUiAuthority.canonical(bundle.authorityTuple()), + AccountControlUiAuthority.canonical(bundle.membershipVersion()), + bundle.canonicalBytes()); + } + + static String envelopeBindingRequestId(String requestId) { + if (SAFE_ENVELOPE_REQUEST_ID.matcher(requestId).matches()) { + return requestId; + } + return java.util.HexFormat.of().formatHex(sha256(requestId.getBytes(StandardCharsets.UTF_8))); + } + + private static byte[] encodeResponse(AuthorizationResponse response) { + return AccountControlUiAuthority.canonical( + Map.of( + "operatorAuthorizationReference", response.operatorAuthorizationReference(), + "authorizationReferenceFingerprint", response.authorizationReferenceFingerprint(), + "expiresAt", response.expiresAt().toString(), + "authorityEvidenceBundle", + AccountStartSessionOperatorAuthorityBundle.decode( + response.authorityEvidenceBundle()) + .jsonValue(), + "bundleReference", response.bundleReference().asJsonValue())); + } + + private static AuthorizationResponse decodeResponse(byte[] exactBytes) { + try { + String json = new String(exactBytes, StandardCharsets.UTF_8); + Map root = JSON.readValue(json, new TypeReference<>() {}); + if (!root.keySet().equals(RESPONSE_FIELDS)) { + throw denied("Original response envelope has changed fields"); + } + String reference = requireReference(root.get("operatorAuthorizationReference")); + String fingerprint = requireFingerprint(root.get("authorizationReferenceFingerprint")); + Instant expiresAt = canonicalInstant(root.get("expiresAt")); + byte[] bundleBytes = AccountControlUiAuthority.canonical(root.get("authorityEvidenceBundle")); + AccountStartSessionOperatorAuthorityBundle.decode(bundleBytes); + var sourceReference = + AccountStartSessionOperatorAuthorityBundle.BundleReference.fromJsonValue( + root.get("bundleReference")); + byte[] canonical = + encodeResponse( + new AuthorizationResponse( + reference, fingerprint, expiresAt, bundleBytes, sourceReference)); + if (!MessageDigest.isEqual(canonical, exactBytes)) { + throw denied("Original response envelope is not canonical"); + } + return new AuthorizationResponse( + reference, fingerprint, expiresAt, bundleBytes, sourceReference); + } catch (IllegalStateException failure) { + throw failure; + } catch (RuntimeException malformed) { + throw denied("Original response envelope is malformed"); + } + } + + private void requireResponseMatchesRecord(AuthorizationResponse response, IssuanceRecord record) { + var bundle = + AccountStartSessionOperatorAuthorityBundle.decode(record.authorityEvidenceBundle()); + if (!response + .authorizationReferenceFingerprint() + .equals(record.authorizationReferenceFingerprint()) + || !response.expiresAt().equals(record.referenceExpiresAt()) + || !Arrays.equals(response.authorityEvidenceBundle(), record.authorityEvidenceBundle()) + || !response + .bundleReference() + .bundleVersion() + .equals(AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION) + || !response.bundleReference().sourceVersion().equals(bundleSourceVersion(bundle)) + || !AccountStartSessionOperatorAuthorityBundle.toSharedReference(response.bundleReference()) + .equals(record.bundleReference()) + || !response + .bundleReference() + .sourceFence() + .equals(Long.toString(record.issuanceFence()))) { + throw denied("Original issuance response differs from the immutable Account record"); + } + byte[] referenceBytes = + response.operatorAuthorizationReference().getBytes(StandardCharsets.US_ASCII); + try { + if (!fingerprintKeys.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + referenceBytes, + record.authorizationReferenceFingerprint(), + record.referenceExpiresAt(), + record.responseEnvelopeExpiresAt())) { + throw denied("Original Account response reference does not match its stored fingerprint"); + } + } finally { + Arrays.fill(referenceBytes, (byte) 0); + } + } + + private static void requireSameCurrent(Current expected, Current observed) { + if (!sameCurrentSource(expected.source(), observed.source()) + || !sameControlUiIssuance(expected.stored(), observed.stored())) { + throw denied("Account actor or source changed between preparation and owner commit"); + } + } + + private static boolean sameCurrentSource( + AccountControlUiAuthority.Snapshot first, AccountControlUiAuthority.Snapshot second) { + return first.actor().equals(second.actor()) + && first.tenant().equals(second.tenant()) + && Arrays.equals(first.evidence(), second.evidence()) + && Arrays.equals( + AccountControlUiAuthority.canonical(first.authorityTuple()), + AccountControlUiAuthority.canonical(second.authorityTuple())) + && Arrays.equals( + AccountControlUiAuthority.canonical(first.membershipVersion()), + AccountControlUiAuthority.canonical(second.membershipVersion())); + } + + private static boolean sameControlUiIssuance( + AccountControlUiIssuanceRepository.Stored first, + AccountControlUiIssuanceRepository.Stored second) { + return first != null + && second != null + && Objects.equals(first.requestId, second.requestId) + && Objects.equals(first.operationId, second.operationId) + && Objects.equals(first.jti, second.jti) + && Objects.equals(first.accountId, second.accountId) + && Objects.equals(first.tenantId, second.tenantId) + && Objects.equals(first.callerContextId, second.callerContextId) + && Objects.equals(first.caller, second.caller) + && Objects.equals(first.requestMacKeyId, second.requestMacKeyId) + && Objects.equals(first.requestDigest, second.requestDigest) + && Objects.equals(first.status, second.status) + && Objects.equals(first.tokenHash, second.tokenHash) + && Arrays.equals(first.claims, second.claims) + && Arrays.equals(first.sources, second.sources) + && Arrays.equals(first.bundle, second.bundle) + && Arrays.equals(first.signerReceipt, second.signerReceipt) + && Arrays.equals(first.pendingRegistry, second.pendingRegistry) + && Arrays.equals(first.activeRegistry, second.activeRegistry) + && Objects.equals(first.issuedAt, second.issuedAt) + && Objects.equals(first.expiresAt, second.expiresAt) + && Objects.equals(first.recoveryExpiry, second.recoveryExpiry); + } + + private static void requireCandidateRecord(IssuanceCandidate candidate, IssuanceRecord record) { + if (record.status() != Status.ISSUED + || !candidate.controlPlaneRequestId().equals(record.controlPlaneRequestId()) + || !Arrays.equals(candidate.preAuthorizationTuple(), record.preAuthorizationTuple()) + || !candidate.mutationDigest().equals(record.mutationDigest()) + || !candidate.issuanceWorkloadUri().equals(record.issuanceWorkloadUri()) + || !candidate.reservationOwnerId().equals(record.reservationOwnerId()) + || candidate.reservationClaimFence() != record.reservationClaimFence() + || !candidate.issuanceOperationId().equals(record.issuanceOperationId()) + || candidate.issuanceFence() != record.issuanceFence() + || !candidate.bundleReference().equals(record.bundleReference()) + || !Arrays.equals(candidate.authorityEvidenceBundle(), record.authorityEvidenceBundle()) + || !candidate + .authorizationReferenceFingerprint() + .equals(record.authorizationReferenceFingerprint()) + || !Arrays.equals(candidate.encryptedResponseEnvelope(), record.encryptedResponseEnvelope()) + || !candidate.issuedAt().equals(record.issuedAt()) + || !candidate.referenceExpiresAt().equals(record.referenceExpiresAt()) + || !candidate.responseEnvelopeExpiresAt().equals(record.responseEnvelopeExpiresAt()) + || record.responseEnvelopeErasedAt() != null) { + throw denied("New Account issuance differs from its exact durable candidate"); + } + } + + private static String bundleSourceVersion(AccountStartSessionOperatorAuthorityBundle bundle) { + return bundle.sourceEvidenceVersion(); + } + + private static void requireRedemptionProjection( + RedemptionResult result, IssuanceRecord issuance) { + if (!issuance + .authorizationReferenceFingerprint() + .equals(result.authorizationReferenceFingerprint()) + || !Arrays.equals(issuance.authorityEvidenceBundle(), result.authorityEvidenceBundle()) + || !issuance.issuanceOperationId().equals(result.issuanceOperationId()) + || issuance.issuanceFence() != result.issuanceFence()) { + throw denied("Account redemption returned a changed authority projection"); + } + } + + private Optional findRecord(String controlPlaneRequestId) { + return Objects.requireNonNull( + lookupTransaction.execute( + ignored -> repository.findByControlPlaneRequestId(controlPlaneRequestId)), + "Account lookup transaction result"); + } + + private static void requireClaimEcho( + ReadCurrentClaimEvidenceResponse evidence, + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwnerId, + long reservationClaimFence, + UUID currentClaimOwnerId, + long currentClaimFence) { + if (!tuple.controlPlaneRequestId().equals(evidence.getControlPlaneRequestId()) + || !Arrays.equals( + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + evidence.getPreAuthorizationTupleJson().toByteArray()) + || !tuple.mutationDigest().equals(evidence.getMutationDigest()) + || !reservationOwnerId.toString().equals(evidence.getReservationOwnerId()) + || reservationClaimFence != evidence.getReservationClaimFence() + || !currentClaimOwnerId.toString().equals(evidence.getClaimOwnerId()) + || currentClaimFence != evidence.getClaimFence()) { + throw denied("Logging/Admin current reservation claim differs from the exact request"); + } + } + + private static StartSessionPreAuthorizationReservationTuple decodeTuple(byte[] exactTupleBytes) { + if (exactTupleBytes == null || exactTupleBytes.length == 0) { + throw new IllegalArgumentException("Canonical StartSession reservation tuple is required"); + } + String json = new String(exactTupleBytes, StandardCharsets.UTF_8); + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json); + if (!Arrays.equals(exactTupleBytes, tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) { + throw new IllegalArgumentException("StartSession reservation tuple bytes are not canonical"); + } + return tuple; + } + + private void requireOriginalBinding( + IssuanceRecord record, + StartSessionPreAuthorizationReservationTuple tuple, + byte[] exactTuple, + UUID reservationOwnerId, + long reservationClaimFence) { + if (!tuple.controlPlaneRequestId().equals(record.controlPlaneRequestId()) + || !Arrays.equals(exactTuple, record.preAuthorizationTuple()) + || !tuple.mutationDigest().equals(record.mutationDigest()) + || !loggingPeerUri.equals(record.issuanceWorkloadUri()) + || !reservationOwnerId.equals(record.reservationOwnerId()) + || reservationClaimFence != record.reservationClaimFence()) { + throw denied("StartSession request conflicts with the original Account issuance"); + } + } + + private void requireRedeemedProjectionBinding( + IssuanceRecord record, + StartSessionPreAuthorizationReservationTuple tuple, + ReadRedeemedOperationProjectionRequest request, + AccountStartSessionOperatorAuthorityBundle bundle, + Instant now) { + if (record.status() != Status.REDEEMED + || !gameSessionPeerUri.equals(record.redemptionRedeemerWorkloadUri()) + || !request.ownerAttemptId().equals(record.redemptionOwnerAttemptId()) + || !Objects.equals(Long.valueOf(request.ownerFence()), record.redemptionOwnerFence()) + || !constantTimeEquals( + record.authorizationReferenceFingerprint(), request.authorizationReferenceFingerprint()) + || !constantTimeEquals( + record.authorizationReferenceFingerprint(), record.redemptionReferenceFingerprint()) + || !Arrays.equals( + record.authorityEvidenceBundle(), record.redemptionAuthorityEvidenceBundle()) + || !tuple.controlPlaneRequestId().equals(bundle.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(record.mutationDigest()) + || !bundle.issuanceOperationId().equals(record.issuanceOperationId()) + || !bundle.sourceEvidenceVersion().equals(record.bundleReference().sourceVersion()) + || !bundle.authorizationExpiresAt().equals(record.referenceExpiresAt().toString()) + || record.redeemedAt().isBefore(record.issuedAt()) + || now.isBefore(record.redeemedAt()) + || !record.redeemedAt().isBefore(record.referenceExpiresAt()) + || !now.isBefore(record.referenceExpiresAt())) { + throw denied("Stored redeemed operation does not match the exact current read request"); + } + } + + private static RedeemedOperationProjection projection(IssuanceRecord record) { + return new RedeemedOperationProjection( + record.controlPlaneRequestId(), + record.preAuthorizationTuple(), + record.mutationDigest(), + record.authorizationReferenceFingerprint(), + record.reservationOwnerId(), + record.reservationClaimFence(), + record.redemptionRedeemerWorkloadUri(), + record.redemptionOwnerAttemptId(), + record.redemptionOwnerFence(), + record.referenceExpiresAt(), + record.redeemedAt(), + record.issuanceOperationId(), + record.issuanceFence(), + AccountStartSessionOperatorAuthorityBundle.fromSharedReference(record.bundleReference()), + record.authorityEvidenceBundle()); + } + + private static void requireSameStoredIssuance(IssuanceRecord original, IssuanceRecord observed) { + if (!original.controlPlaneRequestId().equals(observed.controlPlaneRequestId()) + || !Arrays.equals(original.preAuthorizationTuple(), observed.preAuthorizationTuple()) + || !original.mutationDigest().equals(observed.mutationDigest()) + || !original.issuanceWorkloadUri().equals(observed.issuanceWorkloadUri()) + || !original.reservationOwnerId().equals(observed.reservationOwnerId()) + || original.reservationClaimFence() != observed.reservationClaimFence() + || !original.issuanceOperationId().equals(observed.issuanceOperationId()) + || original.issuanceFence() != observed.issuanceFence() + || !original.bundleReference().equals(observed.bundleReference()) + || !Arrays.equals(original.authorityEvidenceBundle(), observed.authorityEvidenceBundle()) + || !original + .authorizationReferenceFingerprint() + .equals(observed.authorizationReferenceFingerprint()) + || !Arrays.equals( + original.encryptedResponseEnvelope(), observed.encryptedResponseEnvelope()) + || !original.issuedAt().equals(observed.issuedAt()) + || !original.referenceExpiresAt().equals(observed.referenceExpiresAt()) + || !original.responseEnvelopeExpiresAt().equals(observed.responseEnvelopeExpiresAt()) + || !Objects.equals( + original.responseEnvelopeErasedAt(), observed.responseEnvelopeErasedAt())) { + throw denied("Immutable Account StartSession issuance changed during owner revalidation"); + } + } + + private static void requireSameStoredRedemption( + IssuanceRecord original, IssuanceRecord observed) { + requireSameStoredIssuance(original, observed); + if (original.status() != Status.REDEEMED + || observed.status() != Status.REDEEMED + || !Objects.equals( + original.redemptionRedeemerWorkloadUri(), observed.redemptionRedeemerWorkloadUri()) + || !Objects.equals(original.redemptionOwnerAttemptId(), observed.redemptionOwnerAttemptId()) + || !Objects.equals(original.redemptionOwnerFence(), observed.redemptionOwnerFence()) + || !Objects.equals(original.redeemedAt(), observed.redeemedAt()) + || !constantTimeEquals( + original.redemptionReferenceFingerprint(), observed.redemptionReferenceFingerprint()) + || !Arrays.equals( + original.redemptionAuthorityEvidenceBundle(), + observed.redemptionAuthorityEvidenceBundle())) { + throw denied("Original Account redemption changed during current-source revalidation"); + } + } + + private static byte[] sha256(byte[] value) { + try { + return MessageDigest.getInstance("SHA-256").digest(value); + } catch (NoSuchAlgorithmException unavailable) { + throw new IllegalStateException("SHA-256 is unavailable", unavailable); + } + } + + private static Instant canonicalInstant(Object value) { + if (!(value instanceof String text)) throw denied("Original response expiry must be text"); + Instant instant; + try { + instant = Instant.parse(text); + } catch (RuntimeException malformed) { + throw denied("Original response expiry is malformed"); + } + if (!instant.toString().equals(text)) throw denied("Original response expiry is not canonical"); + return instant; + } + + private static String requireReference(Object value) { + if (!(value instanceof String text) + || text.getBytes(StandardCharsets.US_ASCII).length > MAX_REFERENCE_TEXT_BYTES + || !REFERENCE.matcher(text).matches()) { + throw denied("Opaque StartSession authorization reference is malformed"); + } + byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(text); + } catch (RuntimeException malformed) { + throw denied("Opaque StartSession authorization reference is malformed"); + } + try { + if (decoded.length != REFERENCE_RANDOM_BYTES + || !Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(text)) { + throw denied("Opaque StartSession authorization reference is not canonical"); + } + } finally { + Arrays.fill(decoded, (byte) 0); + } + return text; + } + + private static String requireFingerprint(Object value) { + if (!(value instanceof String text) + || !text.matches("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}")) { + throw denied("Account authorization-reference fingerprint is malformed"); + } + return text; + } + + private static boolean constantTimeEquals(String first, String second) { + return second != null + && MessageDigest.isEqual( + first.getBytes(StandardCharsets.US_ASCII), second.getBytes(StandardCharsets.US_ASCII)); + } + + private static void requirePeer(String exactUri) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !exactUri.equals(peer.uri())) { + throw denied("Exact authenticated internal workload identity is required"); + } + } + + private static String exactPeer(String value, String expectedService) { + return GrpcPeerIdentity.parseUri(value) + .map(GrpcPeerIdentity::uri) + .filter(value::equals) + .filter(uri -> uri.endsWith("/sa/" + expectedService)) + .orElseThrow( + () -> new IllegalArgumentException("Exact configured workload URI is required")); + } + + private static String sameNamespacePeer(String exactPeerUri, String service) { + GrpcPeerIdentity peer = + GrpcPeerIdentity.parseUri(exactPeerUri) + .orElseThrow( + () -> new IllegalArgumentException("Exact configured workload URI is required")); + return exactPeer("spiffe://firemud/ns/" + peer.namespace() + "/sa/" + service, service); + } + + private static long policyMillis(Duration value, String field, long maximum) { + Objects.requireNonNull(value, field + " policy is required"); + long millis; + try { + millis = value.toMillis(); + } catch (ArithmeticException outOfRange) { + throw new IllegalArgumentException(field + " is outside the supported range"); + } + if (millis <= 0 || millis > maximum || !Duration.ofMillis(millis).equals(value)) { + throw new IllegalArgumentException( + field + " must be an explicit bounded millisecond duration"); + } + return millis; + } + + private static Instant addMillis(Instant value, long millis) { + try { + return Instant.ofEpochMilli(Math.addExact(value.toEpochMilli(), millis)); + } catch (RuntimeException overflow) { + throw new IllegalArgumentException( + "Operator reference expiry is outside the supported range"); + } + } + + private static void requireNonNilUuid(UUID value, String field) { + if (value == null || new UUID(0L, 0L).equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical nonnil UUID"); + } + } + + private static void requirePositiveFence(long value, String field) { + if (value <= 0) throw new IllegalArgumentException(field + " must be positive"); + } + + private static IllegalStateException denied(String reason) { + return new IllegalStateException(reason); + } + + private record IssuePreparation( + Current current, IssuanceRecord existing, OwnerLinearization linearization) { + private IssuePreparation { + Objects.requireNonNull(current, "current Account actor is required"); + if ((existing == null) != (linearization != null)) { + throw denied("Issue preparation must contain either an original record or its fence"); + } + } + } + + private record PreparedIssuance( + AccountStartSessionOperatorAuthorityBundle bundle, + AuthorizationResponse response, + IssuanceCandidate candidate) { + private PreparedIssuance { + Objects.requireNonNull(bundle, "authority bundle is required"); + Objects.requireNonNull(response, "exact response is required"); + Objects.requireNonNull(candidate, "durable issuance candidate is required"); + } + } + + private record IssueOutcome(boolean created, IssuanceRecord issuance) { + private IssueOutcome { + Objects.requireNonNull(issuance, "durable issuance result is required"); + } + } + + public record IssueRequest( + String controlUiJwt, + byte[] canonicalTupleBytes, + UUID reservationOwnerId, + long reservationClaimFence, + UUID claimOwnerId, + long claimFence) { + public IssueRequest { + canonicalTupleBytes = copy(canonicalTupleBytes); + } + + @Override + public byte[] canonicalTupleBytes() { + return copy(canonicalTupleBytes); + } + + @Override + public String toString() { + return "IssueRequest[control-ui JWT and tuple redacted]"; + } + } + + public record RecoverRequest( + byte[] canonicalTupleBytes, + UUID reservationOwnerId, + long reservationClaimFence, + UUID claimOwnerId, + long claimFence) { + public RecoverRequest { + canonicalTupleBytes = copy(canonicalTupleBytes); + } + + @Override + public byte[] canonicalTupleBytes() { + return copy(canonicalTupleBytes); + } + + @Override + public String toString() { + return "RecoverRequest[tuple redacted]"; + } + } + + public record RedeemRequest( + byte[] canonicalTupleBytes, + String operatorAuthorizationReference, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + UUID ownerAttemptId, + long ownerFence) { + public RedeemRequest { + canonicalTupleBytes = copy(canonicalTupleBytes); + } + + @Override + public byte[] canonicalTupleBytes() { + return copy(canonicalTupleBytes); + } + + @Override + public String toString() { + return "RedeemRequest[tuple, reference, fingerprint redacted]"; + } + } + + /** The exact original tuple, fingerprint and owner bindings; contains no JWT or opaque ref. */ + public record ReadRedeemedOperationProjectionRequest( + byte[] canonicalPreAuthorizationTuple, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + UUID ownerAttemptId, + long ownerFence) { + public ReadRedeemedOperationProjectionRequest { + canonicalPreAuthorizationTuple = copy(canonicalPreAuthorizationTuple); + } + + @Override + public byte[] canonicalPreAuthorizationTuple() { + return copy(canonicalPreAuthorizationTuple); + } + + @Override + public String toString() { + return "ReadRedeemedOperationProjectionRequest[tuple and fingerprint redacted]"; + } + } + + /** Immutable, credential-free Account projection of the original exact redeemed operation. */ + public record RedeemedOperationProjection( + String controlPlaneRequestId, + byte[] canonicalPreAuthorizationTuple, + String mutationDigest, + String authorizationReferenceFingerprint, + UUID reservationOwnerId, + long reservationClaimFence, + String redeemerWorkloadUri, + UUID ownerAttemptId, + long ownerFence, + Instant referenceExpiresAt, + Instant redeemedAt, + UUID issuanceOperationId, + long issuanceFence, + AccountStartSessionOperatorAuthorityBundle.BundleReference bundleReference, + byte[] authorityEvidenceBundle) { + public RedeemedOperationProjection { + canonicalPreAuthorizationTuple = copy(canonicalPreAuthorizationTuple); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + Objects.requireNonNull(bundleReference, "original bundle reference is required"); + } + + @Override + public byte[] canonicalPreAuthorizationTuple() { + return copy(canonicalPreAuthorizationTuple); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public String toString() { + return "RedeemedOperationProjection[authority evidence redacted]"; + } + } + + /** Exact response bytes are only stored in the encrypted owner envelope. */ + public record AuthorizationResponse( + String operatorAuthorizationReference, + String authorizationReferenceFingerprint, + Instant expiresAt, + byte[] authorityEvidenceBundle, + AccountStartSessionOperatorAuthorityBundle.BundleReference bundleReference) { + public AuthorizationResponse { + requireReference(operatorAuthorizationReference); + requireFingerprint(authorizationReferenceFingerprint); + Objects.requireNonNull(expiresAt, "reference expiry is required"); + authorityEvidenceBundle = copy(authorityEvidenceBundle); + Objects.requireNonNull(bundleReference, "source bundle reference is required"); + } + + @Override + public byte[] authorityEvidenceBundle() { + return copy(authorityEvidenceBundle); + } + + @Override + public String toString() { + return "AuthorizationResponse[reference, bundle, and fingerprint redacted]"; + } + } + + public static final class NotFoundException extends RuntimeException { + public NotFoundException() { + super("No original StartSession operator authorization exists"); + } + } + + /** Terminal, fail-closed outcome for ISSUE/RECOVER after exact response material is erased. */ + public static final class ResponseEnvelopeErasedException extends IllegalStateException { + private ResponseEnvelopeErasedException() { + super("Original Account StartSession response envelope is no longer recoverable"); + } + } + + private static byte[] copy(byte[] value) { + return value == null ? null : value.clone(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProvider.java new file mode 100644 index 0000000000..c20f8abcc4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProvider.java @@ -0,0 +1,70 @@ +package net.firedevops.firemud.accountservice.service.session; + +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; + +/** + * Dedicated standalone Lettuce client for Account Coordination operations. + * + *

The trusted owner configuration is supplied explicitly as a Redis URI. This class does not + * consult Spring's ambient Redis connection factory, choose an endpoint, or supply credentials. The + * provider owns the client; each returned physical connection is owned by the invocation and must + * be closed by its caller. + */ +public final class LettuceAccountCoordinationPinnedConnectionProvider + implements AccountCoordinationPinnedConnectionProvider, AutoCloseable { + private final RedisClient client; + private final AtomicBoolean closed = new AtomicBoolean(); + + public LettuceAccountCoordinationPinnedConnectionProvider(RedisURI coordinationRedisUri) { + this.client = + Objects.requireNonNull( + RedisClient.create( + Objects.requireNonNull(coordinationRedisUri, "coordinationRedisUri")), + "Lettuce RedisClient creation returned no client"); + try { + // Configure the dedicated standalone client before any physical connection is opened. + this.client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + } catch (RuntimeException configurationFailure) { + try { + this.client.shutdown(); + } catch (RuntimeException shutdownFailure) { + configurationFailure.addSuppressed(shutdownFailure); + } + throw configurationFailure; + } + } + + @Override + public StatefulRedisConnection openPinnedConnection() { + if (closed.get()) { + throw new IllegalStateException("Account Coordination Redis client is closed"); + } + StatefulRedisConnection connection = client.connect(ByteArrayCodec.INSTANCE); + if (closed.get()) { + try { + connection.close(); + } catch (RuntimeException closeFailure) { + IllegalStateException failure = + new IllegalStateException("Account Coordination Redis client is closed"); + failure.addSuppressed(closeFailure); + throw failure; + } + throw new IllegalStateException("Account Coordination Redis client is closed"); + } + return connection; + } + + /** Shuts down this provider's dedicated client; callers close each returned connection. */ + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + client.shutdown(); + } + } +} diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index e8742830ac..b51fe45e89 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -78,6 +78,10 @@ firemud: - account.v1.AccountService/JoinPublicProductionMembership - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity - account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility + - account.v1.StartSessionOperatorAuthorizationService/IssueHumanOperatorAuthorizationReference + - account.v1.StartSessionOperatorAuthorizationService/RecoverOperatorAuthorizationReference + - account.v1.StartSessionOperatorAuthorizationService/RedeemOperatorAuthorization + - account.v1.StartSessionOperatorAuthorizationService/ReadRedeemedOperationProjection grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 83aed7dc83..1af06e52a7 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -57,6 +57,8 @@ firemud: connect-token-expiration-ms: 30000 actor-staging-eligibility: enabled: ${FIREMUD_ACCOUNT_ACTOR_STAGING_ELIGIBILITY_ENABLED:false} + start-session-operator-authorization: + enabled: ${FIREMUD_ACCOUNT_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED:false} mail: from: no-reply@firemud.local verification-url: http://localhost:8080/auth/verify-email?token=%s @@ -65,6 +67,7 @@ firemud: stripe-api-key: test-key platform-fee-percent: 5 auth: + session-safety-margin-ms: ${FIREMUD_AUTH_SESSION_SAFETY_MARGIN_MS:300000} http: enabled: true role-requirement: AUTHENTICATED @@ -107,6 +110,10 @@ firemud: - account.v1.AccountService/JoinPublicProductionMembership - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity - account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility + - account.v1.StartSessionOperatorAuthorizationService/IssueHumanOperatorAuthorizationReference + - account.v1.StartSessionOperatorAuthorizationService/RecoverOperatorAuthorizationReference + - account.v1.StartSessionOperatorAuthorizationService/RedeemOperatorAuthorization + - account.v1.StartSessionOperatorAuthorizationService/ReadRedeemedOperationProjection management: endpoints: diff --git a/services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql b/services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql new file mode 100644 index 0000000000..b7d89002d7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql @@ -0,0 +1,86 @@ +ALTER TABLE account_start_session_operator_authorizations + ALTER COLUMN encrypted_response_envelope DROP NOT NULL; + +ALTER TABLE account_start_session_operator_authorizations + ADD COLUMN response_envelope_erased_at TIMESTAMPTZ; + +ALTER TABLE account_start_session_operator_authorizations + ADD CONSTRAINT account_start_session_operator_authorizations_envelope_erasure_state + CHECK ( + (encrypted_response_envelope IS NOT NULL AND response_envelope_erased_at IS NULL) + OR + (encrypted_response_envelope IS NULL + AND response_envelope_erased_at IS NOT NULL + AND response_envelope_erased_at >= response_envelope_expires_at) + ); + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_start_session_operator_authorization_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'ISSUED' + OR NEW.redemption_redeemer_workload_uri IS NOT NULL + OR NEW.redemption_owner_attempt_id IS NOT NULL + OR NEW.redemption_owner_fence IS NOT NULL + OR NEW.redeemed_at IS NOT NULL + OR NEW.redemption_reference_fingerprint IS NOT NULL + OR NEW.redemption_authority_evidence_bundle IS NOT NULL + OR NEW.encrypted_response_envelope IS NULL + OR NEW.response_envelope_erased_at IS NOT NULL THEN + RAISE EXCEPTION 'StartSession authorization rows must begin unredeemed and unerased' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'StartSession operator authorization evidence cannot be deleted' + USING ERRCODE = '23514'; + END IF; + + IF OLD.encrypted_response_envelope IS NOT NULL + AND OLD.response_envelope_erased_at IS NULL + AND NEW.encrypted_response_envelope IS NULL + AND NEW.response_envelope_erased_at IS NULL THEN + IF OLD.response_envelope_expires_at > clock_timestamp() + OR (to_jsonb(NEW) - ARRAY['encrypted_response_envelope','response_envelope_erased_at']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['encrypted_response_envelope','response_envelope_erased_at']) THEN + RAISE EXCEPTION 'StartSession response envelope cannot be erased before expiry or with other changes' + USING ERRCODE = '23514'; + END IF; + NEW.response_envelope_erased_at := clock_timestamp(); + RETURN NEW; + END IF; + + IF (to_jsonb(NEW) - ARRAY['status','redemption_redeemer_workload_uri', + 'redemption_owner_attempt_id','redemption_owner_fence','redeemed_at', + 'redemption_reference_fingerprint','redemption_authority_evidence_bundle']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status','redemption_redeemer_workload_uri', + 'redemption_owner_attempt_id','redemption_owner_fence','redeemed_at', + 'redemption_reference_fingerprint','redemption_authority_evidence_bundle']) + OR OLD.status <> 'ISSUED' + OR NEW.status <> 'REDEEMED' + OR OLD.encrypted_response_envelope IS NULL + OR OLD.response_envelope_erased_at IS NOT NULL + OR OLD.redemption_redeemer_workload_uri IS NOT NULL + OR OLD.redemption_owner_attempt_id IS NOT NULL + OR OLD.redemption_owner_fence IS NOT NULL + OR OLD.redeemed_at IS NOT NULL + OR OLD.redemption_reference_fingerprint IS NOT NULL + OR OLD.redemption_authority_evidence_bundle IS NOT NULL + OR NEW.redemption_redeemer_workload_uri IS NULL + OR NEW.redemption_owner_attempt_id IS NULL + OR NEW.redemption_owner_fence IS NULL + OR NEW.redeemed_at IS NULL + OR NEW.redemption_reference_fingerprint IS DISTINCT FROM NEW.authorization_reference_fingerprint + OR NEW.redemption_authority_evidence_bundle IS DISTINCT FROM NEW.authority_evidence_bundle + OR NEW.redemption_redeemer_workload_uri IS DISTINCT FROM + regexp_replace(OLD.issuance_workload_uri, '/sa/logging-admin-service$', '/sa/game-session-service') THEN + RAISE EXCEPTION 'StartSession authorization evidence is immutable except one exact redemption or expired envelope erasure' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql b/services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql new file mode 100644 index 0000000000..1647862a34 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql @@ -0,0 +1,37 @@ +ALTER TABLE account_control_ui_issuance_operations + ADD COLUMN registry_cleanup_deadline_epoch_millis BIGINT; + +ALTER TABLE account_control_ui_issuance_operations + ADD CONSTRAINT account_control_ui_registry_cleanup_deadline_bound CHECK ( + registry_cleanup_deadline_epoch_millis IS NULL + OR (registry_cleanup_deadline_epoch_millis >= expires_at_epoch_second::NUMERIC * 1000 + AND registry_cleanup_deadline_epoch_millis <= 9007199254740991) + ); + +-- Retained pre-migration rows stay NULL and byte-for-byte unchanged. New operations carry one +-- immutable physical cleanup deadline; old rows cannot be advanced or reinterpreted. +-- [jooq ignore start] +CREATE FUNCTION account_control_ui_cleanup_deadline_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.registry_cleanup_deadline_epoch_millis IS NULL THEN + RAISE EXCEPTION 'New control-ui issuance requires cleanup deadline evidence' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF OLD.registry_cleanup_deadline_epoch_millis IS NULL + OR NEW.registry_cleanup_deadline_epoch_millis + IS DISTINCT FROM OLD.registry_cleanup_deadline_epoch_millis THEN + RAISE EXCEPTION 'Control-ui cleanup deadline is immutable and legacy rows cannot advance' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_control_ui_cleanup_deadline_immutable + BEFORE INSERT OR UPDATE ON account_control_ui_issuance_operations + FOR EACH ROW EXECUTE FUNCTION account_control_ui_cleanup_deadline_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql b/services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql new file mode 100644 index 0000000000..d04bc50eb4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql @@ -0,0 +1,60 @@ +-- [jooq ignore start] +DO $$ +DECLARE + envelope_table REGCLASS := to_regclass('account_start_session_operator_authorizations'); + envelope_column SMALLINT; + matching_constraints INTEGER; + size_constraint_name TEXT; +BEGIN + IF envelope_table IS NULL THEN + RAISE EXCEPTION 'StartSession authorization table is missing' + USING ERRCODE = '55000'; + END IF; + + SELECT attnum + INTO envelope_column + FROM pg_attribute + WHERE attrelid = envelope_table + AND attname = 'encrypted_response_envelope' + AND NOT attisdropped; + + IF envelope_column IS NULL THEN + RAISE EXCEPTION 'StartSession response-envelope column is missing' + USING ERRCODE = '55000'; + END IF; + + SELECT COUNT(*), MIN(conname::TEXT) + INTO matching_constraints, size_constraint_name + FROM pg_constraint + WHERE conrelid = envelope_table + AND contype = 'c' + AND convalidated + AND conkey = ARRAY[envelope_column]::SMALLINT[] + AND lower( + replace( + regexp_replace( + pg_get_expr(conbin, conrelid), '[[:space:]()]', '', 'g'), + '"', + '')) IN ( + 'octet_lengthencrypted_response_envelopebetween1and65536', + 'octet_lengthencrypted_response_envelope>=1andoctet_lengthencrypted_response_envelope<=65536'); + + IF matching_constraints <> 1 THEN + RAISE EXCEPTION + 'Expected exactly one StartSession encrypted-response size guard, found %', + matching_constraints + USING ERRCODE = '55000'; + END IF; + + EXECUTE format( + 'ALTER TABLE %s DROP CONSTRAINT %I', + envelope_table, + size_constraint_name); +END; +$$; +-- [jooq ignore stop] + +-- Only the old size guard changes; retained ciphertext and immutable/erasure guards stay intact. +ALTER TABLE account_start_session_operator_authorizations + ADD CONSTRAINT account_start_session_operator_authz_envelope_size_bound + CHECK (octet_length(encrypted_response_envelope) BETWEEN 1 AND 163840); diff --git a/services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql b/services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql new file mode 100644 index 0000000000..0b58352821 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql @@ -0,0 +1,142 @@ +CREATE TABLE account_start_session_operator_authorizations ( + control_plane_request_id VARCHAR(128) PRIMARY KEY + CHECK (octet_length(control_plane_request_id) BETWEEN 1 AND 128), + pre_authorization_tuple BYTEA NOT NULL + CHECK (octet_length(pre_authorization_tuple) BETWEEN 1 AND 8192), + mutation_digest VARCHAR(64) NOT NULL + CHECK (mutation_digest ~ '^[0-9a-f]{64}$'), + issuance_workload_uri VARCHAR(256) NOT NULL + CHECK (issuance_workload_uri ~ '^spiffe://firemud/ns/([a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])/sa/logging-admin-service$'), + reservation_owner_id UUID NOT NULL, + reservation_claim_fence BIGINT NOT NULL CHECK (reservation_claim_fence > 0), + issuance_operation_id UUID NOT NULL UNIQUE, + issuance_fence BIGINT NOT NULL CHECK (issuance_fence > 0), + bundle_version VARCHAR(32) NOT NULL + CHECK (bundle_version = 'authorityEvidenceBundle/v1'), + bundle_source_version VARCHAR(19) NOT NULL + CHECK (bundle_source_version ~ '^[1-9][0-9]{0,18}$' + AND bundle_source_version::NUMERIC <= 9223372036854775807), + bundle_source_fence VARCHAR(19) NOT NULL + CHECK (bundle_source_fence ~ '^[1-9][0-9]{0,18}$' + AND bundle_source_fence = issuance_fence::TEXT), + bundle_linearization VARCHAR(20) NOT NULL + CHECK (bundle_linearization ~ '^[1-9][0-9]{0,19}$' + AND bundle_linearization::NUMERIC <= 18446744073709551615), + authority_evidence_bundle BYTEA NOT NULL + CHECK (octet_length(authority_evidence_bundle) BETWEEN 1 AND 131072), + authorization_reference_fingerprint VARCHAR(137) NOT NULL UNIQUE + CHECK (authorization_reference_fingerprint ~ '^arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}$'), + encrypted_response_envelope BYTEA NOT NULL + CHECK (octet_length(encrypted_response_envelope) BETWEEN 1 AND 65536), + issued_at TIMESTAMPTZ NOT NULL, + reference_expires_at TIMESTAMPTZ NOT NULL, + response_envelope_expires_at TIMESTAMPTZ NOT NULL, + status VARCHAR(16) NOT NULL CHECK (status IN ('ISSUED', 'REDEEMED')), + redemption_redeemer_workload_uri VARCHAR(256) + CHECK (redemption_redeemer_workload_uri IS NULL OR + redemption_redeemer_workload_uri ~ '^spiffe://firemud/ns/([a-z0-9]|[a-z0-9][a-z0-9-]{0,61}[a-z0-9])/sa/game-session-service$'), + redemption_owner_attempt_id UUID, + redemption_owner_fence BIGINT CHECK (redemption_owner_fence IS NULL OR redemption_owner_fence > 0), + redeemed_at TIMESTAMPTZ, + redemption_reference_fingerprint VARCHAR(137) + CHECK (redemption_reference_fingerprint IS NULL OR + redemption_reference_fingerprint ~ '^arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}$'), + redemption_authority_evidence_bundle BYTEA + CHECK (redemption_authority_evidence_bundle IS NULL OR + octet_length(redemption_authority_evidence_bundle) BETWEEN 1 AND 131072), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK (reservation_owner_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (issuance_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID), + CHECK (issued_at > CAST('1970-01-01 00:00:00+00:00' AS TIMESTAMPTZ)), + CHECK (reference_expires_at > issued_at + AND reference_expires_at <= issued_at + INTERVAL '5' MINUTE), + CHECK (response_envelope_expires_at > reference_expires_at + AND response_envelope_expires_at <= reference_expires_at + INTERVAL '1' MINUTE), + CHECK ( + (status = 'ISSUED' + AND redemption_redeemer_workload_uri IS NULL + AND redemption_owner_attempt_id IS NULL + AND redemption_owner_fence IS NULL + AND redeemed_at IS NULL + AND redemption_reference_fingerprint IS NULL + AND redemption_authority_evidence_bundle IS NULL) + OR + (status = 'REDEEMED' + AND redemption_redeemer_workload_uri IS NOT NULL + AND redemption_owner_attempt_id IS NOT NULL + AND redemption_owner_attempt_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND redemption_owner_fence IS NOT NULL + AND redeemed_at IS NOT NULL + AND redeemed_at >= issued_at + AND redeemed_at < reference_expires_at + AND redemption_reference_fingerprint = authorization_reference_fingerprint + AND redemption_authority_evidence_bundle = authority_evidence_bundle) + ) +); + +-- [jooq ignore start] +CREATE FUNCTION account_start_session_operator_authorization_guard() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.status <> 'ISSUED' + OR NEW.redemption_redeemer_workload_uri IS NOT NULL + OR NEW.redemption_owner_attempt_id IS NOT NULL + OR NEW.redemption_owner_fence IS NOT NULL + OR NEW.redeemed_at IS NOT NULL + OR NEW.redemption_reference_fingerprint IS NOT NULL + OR NEW.redemption_authority_evidence_bundle IS NOT NULL THEN + RAISE EXCEPTION 'StartSession authorization rows must begin unredeemed' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'StartSession operator authorization evidence cannot be deleted' + USING ERRCODE = '23514'; + END IF; + + IF (to_jsonb(NEW) - ARRAY['status','redemption_redeemer_workload_uri', + 'redemption_owner_attempt_id','redemption_owner_fence','redeemed_at', + 'redemption_reference_fingerprint','redemption_authority_evidence_bundle']) IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['status','redemption_redeemer_workload_uri', + 'redemption_owner_attempt_id','redemption_owner_fence','redeemed_at', + 'redemption_reference_fingerprint','redemption_authority_evidence_bundle']) + OR OLD.status <> 'ISSUED' + OR NEW.status <> 'REDEEMED' + OR OLD.redemption_redeemer_workload_uri IS NOT NULL + OR OLD.redemption_owner_attempt_id IS NOT NULL + OR OLD.redemption_owner_fence IS NOT NULL + OR OLD.redeemed_at IS NOT NULL + OR OLD.redemption_reference_fingerprint IS NOT NULL + OR OLD.redemption_authority_evidence_bundle IS NOT NULL + OR NEW.redemption_redeemer_workload_uri IS NULL + OR NEW.redemption_owner_attempt_id IS NULL + OR NEW.redemption_owner_fence IS NULL + OR NEW.redeemed_at IS NULL + OR NEW.redemption_reference_fingerprint IS DISTINCT FROM NEW.authorization_reference_fingerprint + OR NEW.redemption_authority_evidence_bundle IS DISTINCT FROM NEW.authority_evidence_bundle + OR NEW.redemption_redeemer_workload_uri IS DISTINCT FROM + regexp_replace(OLD.issuance_workload_uri, '/sa/logging-admin-service$', '/sa/game-session-service') THEN + RAISE EXCEPTION 'StartSession authorization evidence is immutable except one exact redemption' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_start_session_operator_authorization_no_truncate() +RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'StartSession operator authorization evidence cannot be truncated' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_start_session_operator_authorization_immutable + BEFORE INSERT OR UPDATE OR DELETE ON account_start_session_operator_authorizations + FOR EACH ROW EXECUTE FUNCTION account_start_session_operator_authorization_guard(); +CREATE TRIGGER account_start_session_operator_authorization_no_truncate + BEFORE TRUNCATE ON account_start_session_operator_authorizations + FOR EACH STATEMENT EXECUTE FUNCTION account_start_session_operator_authorization_no_truncate(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/redis/lua/account-control-ui-registry-cas.lua b/services/account-service/src/main/resources/redis/lua/account-control-ui-registry-cas.lua new file mode 100644 index 0000000000..1cb8029b0b --- /dev/null +++ b/services/account-service/src/main/resources/redis/lua/account-control-ui-registry-cas.lua @@ -0,0 +1,59 @@ +-- Account-owned control-ui only. The client separately proves owner COMMITTED before activation. +if #KEYS ~= 1 or #ARGV ~= 3 then return -1 end +local key, expected, replacement, cleanupDeadline = KEYS[1], ARGV[1], ARGV[2], ARGV[3] +if not string.match(key, '^session:auth:token:[0-9a-f]+$') or #key ~= 83 + or #replacement == 0 or #replacement > 32768 or #expected > 32768 + or not string.match(cleanupDeadline, '^[1-9][0-9]*$') or #cleanupDeadline > 16 then return -1 end +local deadline = tonumber(cleanupDeadline) +if not deadline or deadline > 9007199254740991 then return -1 end +local now = redis.call('TIME') +if deadline <= tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000) then return -2 end +local ok, nextRecord = pcall(cjson.decode, replacement) +if not ok or type(nextRecord) ~= 'table' or nextRecord.schemaVersion ~= 1 + or nextRecord.profile ~= 'control-ui' or nextRecord.type ~= 'control-ui' + or nextRecord.audience ~= 'control-ui' or nextRecord.issuer ~= 'firemud-account-service' + or nextRecord.tokenHash ~= string.sub(key, 20) + or nextRecord.globalRoles ~= nil or nextRecord.scopedRoles ~= nil + or type(nextRecord.exp) ~= 'number' + or nextRecord.exp <= 0 or math.floor(nextRecord.exp) ~= nextRecord.exp + or nextRecord.exp > 9007199254740 + or type(nextRecord.registryCleanupDeadlineEpochMillis) ~= 'number' + or math.floor(nextRecord.registryCleanupDeadlineEpochMillis) + ~= nextRecord.registryCleanupDeadlineEpochMillis + or nextRecord.registryCleanupDeadlineEpochMillis ~= deadline + or nextRecord.registryCleanupDeadlineEpochMillis < nextRecord.exp * 1000 then return -1 end +local current = redis.call('GET', key) +if current == replacement then + if redis.call('PEXPIRETIME', key) ~= deadline then return -3 end + -- Reassert identical bytes/deadline on this physical connection so its WAITAOF covers retry. + redis.call('SET', key, replacement, 'PXAT', cleanupDeadline) + return 0 +end +if expected == '' then + if current then return -4 end + if nextRecord.state ~= 'pending' or nextRecord.registryVersion ~= 1 then return -1 end +else + if not current or current ~= expected then return -4 end + if redis.call('PEXPIRETIME', key) ~= deadline then return -3 end + local priorOk, prior = pcall(cjson.decode, expected) + if not priorOk then return -1 end + local activation = prior.state == 'pending' and prior.registryVersion == 1 + and nextRecord.state == 'active' and nextRecord.registryVersion == 2 + local revocation = ((prior.state == 'pending' and prior.registryVersion == 1) + or (prior.state == 'active' and prior.registryVersion == 2)) + and nextRecord.state == 'revoked' and nextRecord.registryVersion == 3 + if not activation and not revocation then return -1 end + local function equal(a, b) + if type(a) ~= type(b) then return false end + if type(a) ~= 'table' then return a == b end + for k,v in pairs(a) do if not equal(v,b[k]) then return false end end + for k,_ in pairs(b) do if a[k] == nil then return false end end + return true + end + prior.state, prior.registryVersion = nil, nil + nextRecord.state, nextRecord.registryVersion = nil, nil + if not equal(prior,nextRecord) then return -1 end +end +redis.call('SET', key, replacement, 'PXAT', cleanupDeadline) +return 1 + diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLoggingTestClasspathIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLoggingTestClasspathIntegrationTest.java new file mode 100644 index 0000000000..2ccfab5457 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountLoggingTestClasspathIntegrationTest.java @@ -0,0 +1,20 @@ +package integration.net.firedevops.firemud.accountservice; + +import static org.assertj.core.api.Assertions.assertThat; + +import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceGrpcService; +import org.junit.jupiter.api.Test; + +/** Verifies Account can use Logging proof code without importing Logging's Flyway migrations. */ +class AccountLoggingTestClasspathIntegrationTest { + @Test + void retainsLoggingProofClassesAndOnlyAccountMigrationResources() { + assertThat(StartSessionReservationEvidenceGrpcService.class).isNotNull(); + assertThat(StartSessionReservationMutationTestFixtures.class).isNotNull(); + + ClassLoader classLoader = getClass().getClassLoader(); + assertThat(classLoader.getResource("db/migration/V1__baseline.sql")).isNull(); + assertThat(classLoader.getResource("db/migration/V1__init.sql")).isNotNull(); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java new file mode 100644 index 0000000000..eccc4280bd --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java @@ -0,0 +1,355 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.Connection; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real PostgreSQL raw-source and lock-order definitions. Complete external authenticated capture + * and terminal owner RPC readbacks are explicitly test-only stipulated fixtures, NOT production + * caller/source/World proof. These tests do not claim genuine issuance or COMMIT_ORDER provenance. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiSourceGuardPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void ownerSourceGuardPrerequisiteSchemaIsInstalledBeforeGuardBackfill() { + Context c = context(); + for (String relation : + List.of( + "account_draft_authorization_source_locks", + "account_draft_authorization_fences", + "account_draft_authorization_sources", + "account_draft_authorization_owner_readbacks", + "account_draft_authorization_source_changes", + "account_draft_authorization_changed_scopes", + "account_tenant_creation_bootstrap_operations", + "account_individual_creator_party_sources", + "account_tenant_creator_party_history", + "account_fresh_creator_party_association_operations", + "account_hosted_terms_scopes", + "account_hosted_terms_catalog_versions", + "account_hosted_terms_publication_operations", + "account_individual_hosted_terms_acceptances", + "account_hosted_terms_environment_binding_heads", + "account_hosted_terms_environment_bindings", + "account_hosted_terms_environment_binding_publications")) { + assertThat(c.dsl.fetchOne("SELECT to_regclass(?)::TEXT", relation).get(0, String.class)) + .as("migrated relation %s", relation) + .isNotNull(); + } + for (String function : + List.of( + "account_draft_authorization_immutable_guard()", + "account_draft_authorization_is_settled(uuid)", + "account_publication_authorization_source_sort_key(text)", + "account_control_ui_source_keys(text,jsonb)", + "account_control_ui_required_source_guard()")) { + assertThat(c.dsl.fetchOne("SELECT to_regprocedure(?)::TEXT", function).get(0, String.class)) + .as("migrated function %s", function) + .isNotNull(); + } + } + + @Test + void rawProtectedMutationCannotBypassOriginalFenceButNoOpAndUnrelatedAccountRemainWritable() { + Context c = context(); + var binding = binding(c); + c.tx( + () -> { + c.fences.reserve(binding); + c.fences.claimCommitOrder(binding); + return null; + }); + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", + "test-only-bypass", + binding.actorAccountId()))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("every original owner settles"); + c.tx( + () -> + c.dsl.execute( + "UPDATE accounts SET id = id WHERE account_uuid = ?", binding.actorAccountId())); + // Username/email are not captured Account security/role fields. Existing protections still + // apply. + c.tx( + () -> + c.dsl.execute( + "UPDATE accounts SET username = ? WHERE account_uuid = ?", + "test-noop-metadata", + binding.actorAccountId())); + UUID unrelated = account(c); + changePassword(c, unrelated, "test-only-unrelated-account-change"); + var ordering = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT ordering FROM account_draft_authorization_fences WHERE operation_id = ?", + binding.operationId()), + "Original authorization fence readback required"); + assertThat(ordering.get("ordering", String.class)).isEqualTo("COMMIT_ORDER"); + } + + @Test + void exactAllOwnerSettlementUnblocksButOneOrMixedReadbackDoesNot() { + for (Outcome outcome : Outcome.values()) { + Context c = context(); + var binding = binding(c); + c.tx( + () -> { + c.fences.reserve(binding); + c.fences.claimCommitOrder(binding); + return null; + }); + terminal(c, binding, Owner.WORLD, outcome); + assertThatThrownBy(() -> changePassword(c, binding.actorAccountId(), "test-only-blocked")) + .isInstanceOf(DataAccessException.class); + terminal(c, binding, Owner.GAME_DESIGN, outcome); + changePassword(c, binding.actorAccountId(), "test-only-settled-change"); + var settlement = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT account_draft_authorization_is_settled(?) AS settled", + binding.operationId()), + "Exact owner settlement readback required"); + assertThat(settlement.get("settled", Boolean.class)).isTrue(); + } + Context c = context(); + var binding = binding(c); + c.tx( + () -> { + c.fences.reserve(binding); + c.fences.claimCommitOrder(binding); + return null; + }); + terminal(c, binding, Owner.WORLD, Outcome.COMMITTED); + terminal(c, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThatThrownBy(() -> changePassword(c, binding.actorAccountId(), "test-only-mixed-denied")) + .isInstanceOf(DataAccessException.class); + } + + @Test + void sourceFirstContentionRollsBackRowsFirstProducerWithoutWaitingOrTerminalReceipt() + throws Exception { + Context c = context(); + var binding = binding(c); + try (Connection writer = c.source.getConnection()) { + writer.setAutoCommit(false); + try (var statement = + writer.prepareStatement( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE")) { + statement.setString(1, binding.sources().getFirst().key()); + statement.executeQuery().close(); + } + Instant started = Instant.now(); + assertThatThrownBy( + () -> + c.tx( + () -> { + c.dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", + binding.actorAccountId()); + c.fences.lockProducerSourcesNowait(binding.sources()); + c.fences.reserve(binding); + return c.fences.claimCommitOrder(binding); + })) + .isInstanceOf(DataAccessException.class); + assertThat(Duration.between(started, Instant.now())).isLessThan(Duration.ofSeconds(2)); + assertThat(c.dsl.fetchCount(DSL.table("account_draft_authorization_fences"))).isZero(); + assertThat(c.dsl.fetchCount(DSL.table("account_draft_authorization_owner_readbacks"))) + .isZero(); + writer.rollback(); + } + c.tx( + () -> { + c.fences.lockProducerSourcesNowait(binding.sources()); + c.fences.reserve(binding); + return c.fences.claimCommitOrder(binding); + }); + assertThatThrownBy( + () -> changePassword(c, binding.actorAccountId(), "test-only-producer-first")) + .isInstanceOf(DataAccessException.class); + } + + @Test + void waitingAndRevokeIntentCanStillBeRecordedWhileActualMutationStaysDenied() { + Context c = context(); + var binding = binding(c); + c.tx(() -> c.fences.reserve(binding)); + var intent = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), binding.sources(), new byte[] {11}); + assertThat(c.tx(() -> c.fences.requestSourceChange(intent))).isFalse(); + assertThat(c.tx(() -> c.fences.read(binding)).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.REVOKE_ORDER); + assertThatThrownBy(() -> changePassword(c, binding.actorAccountId(), "test-only-before-aborts")) + .isInstanceOf(DataAccessException.class); + terminal(c, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); + terminal(c, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); + assertThat(c.tx(() -> c.fences.sourceMutationPermitted(intent))).isTrue(); + changePassword(c, binding.actorAccountId(), "test-only-after-aborts"); + } + + private static void terminal( + Context c, DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { + c.tx( + () -> { + c.fences.recordOwnerReadback( + binding, + new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {7})); + return null; + }); + } + + private static void changePassword(Context c, UUID id, String hash) { + c.tx( + () -> { + Account account = new AccountRepository(c.dsl).findByAccountUuid(id).orElseThrow(); + account.setPasswordHash(hash); + return new AccountRepository(c.dsl).save(account); + }); + } + + private static UUID account(Context c) { + return c.tx( + () -> { + Account row = new Account(); + String suffix = UUID.randomUUID().toString(); + row.setUsername("test-" + suffix); + row.setEmail(suffix + "@example.test"); + row.setPasswordHash("test-only-hash"); + return new AccountRepository(c.dsl).save(row).getAccountUuid(); + }); + } + + private static DraftAuthorizationFenceBinding binding(Context c) { + UUID actor = account(c); + var complete = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "test-only-tenant-key", + 2, + "test-only-tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "test-only/base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-only-world-payload")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "test-region", + "aggregate", + "test-region", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + actor, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + "test-only-source-fixture".getBytes(java.nio.charset.StandardCharsets.UTF_8)))); + } + + private static Context context() { + String schema = "control_ui_guard_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context(source, dsl, new DraftAuthorizationFenceRepository(dsl), transaction); + } + + private record Context( + DriverManagerDataSource source, + DSLContext dsl, + DraftAuthorizationFenceRepository fences, + TransactionTemplate transaction) { + T tx(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java new file mode 100644 index 0000000000..2df2df1f65 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java @@ -0,0 +1,603 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Physical PostgreSQL proof for the exact, read-only committed-issuance repository. + * + *

The SQL fixture advances only the actual V74 row through its guarded storage states. Its + * opaque payloads establish neither control-ui token authority nor genuine authorization issuance, + * protected-response encryption, or registry activation. + */ +@SuppressWarnings("resource") +class AccountControlUiCommittedIssuanceRepositoryIntegrationTest { + private static final String MIGRATION_LOCATION = "classpath:db/migration"; + private static final AccountPostgresIntegrationFixture postgres = + new AccountPostgresIntegrationFixture(); + private final Set schemas = new HashSet<>(); + + @BeforeAll + static void startPostgres() { + postgres.start(); + } + + @AfterAll + static void stopPostgres() { + postgres.stop(); + } + + @AfterEach + void dropTestOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(postgres.dataSource()); + for (String schema : schemas) { + if (!schema.matches("account_control_ui_committed_[a-f0-9]{32}")) { + throw new IllegalStateException("Refusing to dispose an unowned PostgreSQL schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + schemas.clear(); + } + + @Test + void readsOnlyExactCommittedEvidenceInsideTheOwnerTransaction() { + Context context = context(); + IssuanceSeed seed = context.insertCandidate(); + + assertThatThrownBy(() -> context.repository.readCommitted(seed.tokenHash())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Committed Account issuance read requires an Account transaction"); + + assertThatThrownBy(() -> context.commitCandidate(seed)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("Protected original control-ui response is absent"); + assertThat(context.status(seed.requestId())).isEqualTo("CANDIDATE"); + + context.insertProtectedResponse(seed); + context.commitCandidate(seed); + var evidence = + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow()); + + assertThat(evidence.requestId()).isEqualTo(seed.requestId()); + assertThat(evidence.operationId()).isEqualTo(seed.operationId()); + assertThat(evidence.tokenJti()).isEqualTo(seed.tokenJti()); + assertThat(evidence.accountId()).isEqualTo(context.owner().accountId()); + assertThat(evidence.tenantId()).isEqualTo(context.owner().tenantId()); + assertThat(evidence.callerWorkload()).isEqualTo(seed.callerWorkload()); + assertThat(evidence.callerContextId()).isEqualTo(seed.callerContextId()); + assertThat(evidence.requestDigest()).isEqualTo(seed.requestDigest()); + assertThat(evidence.claims()).containsExactly(seed.claims()); + assertThat(evidence.source()).containsExactly(seed.source()); + assertThat(evidence.bundle()).containsExactly(seed.bundle()); + assertThat(evidence.signerReceipt()).containsExactly(seed.signerReceipt()); + assertThat(evidence.issuedAtEpochSecond()).isEqualTo(seed.issuedAtEpochSecond()); + assertThat(evidence.expiresAtEpochSecond()).isEqualTo(seed.expiresAtEpochSecond()); + assertThat(evidence.status()).isEqualTo("COMMITTED"); + assertThat(evidence.tokenHash()).isEqualTo(seed.tokenHash()); + assertThat(evidence.pendingRegistry()).containsExactly(seed.pendingRegistry()); + assertThat(evidence.activeRegistry()).containsExactly(seed.activeRegistry()); + assertThat(evidence.pendingReceipt()).containsExactly(seed.pendingReceipt()); + assertThat(evidence.committedAt()).isNotNull(); + assertThat(evidence.recoveryFailedAt()).isNull(); + assertThat( + context.inTransaction( + () -> + Objects.requireNonNull( + context.transactionDsl.fetchOne( + "SELECT encrypted_response FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()), + "Missing committed control-ui response envelope row for operation " + + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.encryptedResponse()); + assertThat( + context.inTransaction( + () -> + Objects.requireNonNull( + context.transactionDsl.fetchOne( + "SELECT owner_binding FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()), + "Missing committed control-ui owner-binding row for operation " + + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.ownerBinding()); + + byte[] exposedClaims = evidence.claims(); + exposedClaims[0] ^= 0x7f; + assertThat( + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow().claims())) + .containsExactly(seed.claims()); + } + + @Test + void missingCandidateAndRevokedIssuancesDoNotReadAsCommitted() { + Context context = context(); + IssuanceSeed candidate = context.insertCandidate(); + IssuanceSeed revoked = context.insertCommitted(); + context.revokeCommitted(revoked); + + assertThat(context.inTransaction(() -> context.repository.readCommitted("f".repeat(64)))) + .isEmpty(); + assertThatThrownBy( + () -> + context.inTransaction( + () -> context.repository.readCommitted(candidate.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + assertThat(context.status(candidate.requestId())).isEqualTo("CANDIDATE"); + assertThat(context.status(revoked.requestId())).isEqualTo("REVOKED"); + assertThatThrownBy( + () -> + context.inTransaction(() -> context.repository.readCommitted(revoked.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + } + + @Test + void importedPostgresGuardsRejectRewritingOrDeletingCommittedEvidence() { + Context context = context(); + IssuanceSeed seed = context.insertCommitted(); + + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET source_payload = ? WHERE request_id = ?", + bytes("test-only-rewritten-source"), + seed.requestId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "DELETE FROM account_control_ui_issuance_operations WHERE request_id = ?", + seed.requestId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "UPDATE account_control_ui_response_envelopes " + + "SET encrypted_response = ? WHERE operation_id = ?", + bytes("test-only-rewritten-envelope"), + seed.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + context.inTransaction( + () -> + context.transactionDsl.execute( + "DELETE FROM account_control_ui_response_envelopes WHERE operation_id = ?", + seed.operationId()))) + .isInstanceOf(DataAccessException.class); + + var retained = + context.inTransaction( + () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow()); + assertThat(retained.source()).containsExactly(seed.source()); + assertThat( + context.inTransaction( + () -> + Objects.requireNonNull( + context.transactionDsl.fetchOne( + "SELECT encrypted_response FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()), + "Missing retained control-ui response envelope row for operation " + + seed.operationId()) + .get(0, byte[].class))) + .containsExactly(seed.encryptedResponse()); + } + + @Test + void committedReadShareLockLinearizesBeforeConcurrentRevocation() throws Exception { + Context context = context(); + IssuanceSeed seed = context.insertCommitted(); + CountDownLatch readerHasLoadedEvidence = new CountDownLatch(1); + CountDownLatch releaseReaderTransaction = new CountDownLatch(1); + CountDownLatch revocationIsAboutToUpdate = new CountDownLatch(1); + AtomicInteger readerPid = new AtomicInteger(); + AtomicInteger revokerPid = new AtomicInteger(); + ExecutorService executor = Executors.newFixedThreadPool(2); + + Future reader = + executor.submit( + () -> + context.inTransaction( + () -> { + var evidence = + context.repository.readCommitted(seed.tokenHash()).orElseThrow(); + readerPid.set( + Objects.requireNonNull( + context.transactionDsl.fetchOne("SELECT pg_backend_pid()"), + "Missing PostgreSQL backend pid row for committed-read reader") + .get(0, Integer.class)); + readerHasLoadedEvidence.countDown(); + await(releaseReaderTransaction, "reader transaction release"); + return evidence; + })); + Future revocation; + try { + assertThat(readerHasLoadedEvidence.await(5, TimeUnit.SECONDS)).isTrue(); + revocation = + executor.submit( + () -> + context.inTransaction( + () -> { + revokerPid.set( + Objects.requireNonNull( + context.transactionDsl.fetchOne("SELECT pg_backend_pid()"), + "Missing PostgreSQL backend pid row for concurrent revoker") + .get(0, Integer.class)); + revocationIsAboutToUpdate.countDown(); + context.transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'COMMITTED'", + seed.requestId()); + return null; + })); + assertThat(revocationIsAboutToUpdate.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat( + waitUntilBlockedBy( + context, revokerPid.get(), readerPid.get(), TimeUnit.SECONDS.toNanos(5))) + .as("the revocation UPDATE waits on the repository's FOR SHARE row lock") + .isTrue(); + assertThat(revocation.isDone()).isFalse(); + } finally { + releaseReaderTransaction.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(5, TimeUnit.SECONDS)) { + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)) + .as("reader and revocation transactions terminate after releasing the row lock") + .isTrue(); + } + } + + assertThat(reader.get(5, TimeUnit.SECONDS).status()).isEqualTo("COMMITTED"); + revocation.get(5, TimeUnit.SECONDS); + assertThat(context.status(seed.requestId())).isEqualTo("REVOKING"); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.readCommitted(seed.tokenHash()))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); + } + + private static boolean waitUntilBlockedBy( + Context context, int waitingPid, int blockingPid, long timeoutNanos) + throws InterruptedException { + long deadline = System.nanoTime() + timeoutNanos; + while (System.nanoTime() < deadline) { + Boolean blocked = + Objects.requireNonNull( + context.adminDsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity " + + "WHERE pid = ? AND wait_event_type = 'Lock' " + + "AND ? = ANY(pg_blocking_pids(pid)))", + waitingPid, + blockingPid), + "Missing PostgreSQL lock-wait status readback") + .get(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) { + return true; + } + Thread.sleep(10L); + } + return false; + } + + private static void await(CountDownLatch latch, String purpose) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for " + purpose); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for " + purpose, interrupted); + } + } + + private Context context() { + String schema = "account_control_ui_committed_" + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + DriverManagerDataSource dataSource = postgres.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DSLContext adminDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + return new Context(transactionDsl, adminDsl, dataSource); + } + + private static FreshTenantCreationEvidence tenantEvidence(UUID tenantId) { + UUID requestId = UUID.randomUUID(); + UUID operationId = UUID.randomUUID(); + String tenantKey = "committed-issuance-" + requestId.toString().substring(0, 12); + String requestDigest = + GameTenantCreationDigest.requestDigest("prod", requestId, tenantKey, "test tenant", null); + long sourceGameRowId = 7001L; + String provenance = "NEW_GAME_ROW"; + return new FreshTenantCreationEvidence( + 1, + "prod", + requestId, + operationId, + requestDigest, + tenantId, + sourceGameRowId, + tenantKey, + provenance, + GameTenantCreationDigest.evidenceDigest( + "prod", + requestId, + operationId, + requestDigest, + tenantId, + sourceGameRowId, + tenantKey, + provenance)); + } + + private static String tokenHash() { + return UUID.randomUUID().toString().replace("-", "").repeat(2); + } + + private static String digest() { + return UUID.randomUUID().toString().replace("-", "").repeat(2); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private record OwnerIdentity(UUID accountId, UUID tenantId) {} + + private record IssuanceSeed( + UUID requestId, + UUID operationId, + UUID tokenJti, + String callerWorkload, + UUID callerContextId, + String requestDigest, + byte[] claims, + byte[] source, + byte[] bundle, + byte[] signerReceipt, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + OffsetDateTime recoveryExpiresAt, + String tokenHash, + byte[] pendingRegistry, + byte[] activeRegistry, + byte[] pendingReceipt, + byte[] encryptedResponse, + byte[] ownerBinding) {} + + private static final class Context { + private final DSLContext transactionDsl; + private final DSLContext adminDsl; + private final TransactionTemplate transaction; + private final AccountControlUiCommittedIssuanceRepository repository; + private final OwnerIdentity owner; + + Context(DSLContext transactionDsl, DSLContext adminDsl, DriverManagerDataSource dataSource) { + this.transactionDsl = transactionDsl; + this.adminDsl = adminDsl; + transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + repository = new AccountControlUiCommittedIssuanceRepository(transactionDsl); + owner = + inTransaction( + () -> { + String suffix = UUID.randomUUID().toString(); + Account account = new Account(); + account.setUsername("cui-" + suffix.replace("-", "")); + account.setEmail("control-ui-committed-" + suffix + "@example.test"); + account.setPasswordHash("test-only-account-password-hash"); + Account saved = new AccountRepository(transactionDsl).save(account); + UUID tenantId = UUID.randomUUID(); + new FreshTenantIdentityAssociationRepository(transactionDsl, "prod") + .importVerified(tenantEvidence(tenantId)); + return new OwnerIdentity(saved.getAccountUuid(), tenantId); + }); + } + + OwnerIdentity owner() { + return owner; + } + + T inTransaction(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + + void inTransactionWithoutResult(Runnable action) { + transaction.executeWithoutResult(ignored -> action.run()); + } + + IssuanceSeed insertCandidate() { + IssuanceSeed seed = newSeed(); + inTransactionWithoutResult(() -> insertPrepared(seed)); + inTransactionWithoutResult(() -> advanceToCandidate(seed)); + return seed; + } + + IssuanceSeed insertCommitted() { + IssuanceSeed seed = insertCandidate(); + insertProtectedResponse(seed); + commitCandidate(seed); + return seed; + } + + void insertProtectedResponse(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "INSERT INTO account_control_ui_response_envelopes " + + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "VALUES (?, ?, ?, CAST(? AS timestamptz))", + seed.operationId(), + seed.encryptedResponse(), + seed.ownerBinding(), + seed.recoveryExpiresAt())); + } + + void commitCandidate(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'COMMITTED', pending_receipt = ?, " + + "committed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'CANDIDATE'", + seed.pendingReceipt(), + seed.requestId())); + } + + void revokeCommitted(IssuanceSeed seed) { + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'COMMITTED'", + seed.requestId())); + inTransactionWithoutResult( + () -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKED', revocation_receipt = ? " + + "WHERE request_id = ? AND status = 'REVOKING'", + bytes("test-only-revocation-receipt"), + seed.requestId())); + } + + String status(UUID requestId) { + return inTransaction( + () -> + Objects.requireNonNull( + transactionDsl.fetchOne( + "SELECT status FROM account_control_ui_issuance_operations WHERE request_id = ?", + requestId), + "Missing Account control-ui issuance status row for request " + requestId) + .get(0, String.class)); + } + + private void insertPrepared(IssuanceSeed seed) { + transactionDsl.execute( + "INSERT INTO account_control_ui_issuance_operations (" + + "request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload, " + + "caller_context_id, request_mac_key_id, request_digest, claims_payload, " + + "source_payload, bundle_payload, signer_receipt, issued_at_epoch_second, " + + "expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, " + + "recovery_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, " + + "'PREPARED')", + seed.requestId(), + seed.operationId(), + seed.tokenJti(), + owner.accountId(), + owner.tenantId(), + seed.callerWorkload(), + seed.callerContextId(), + "test-mac1", + seed.requestDigest(), + seed.claims(), + seed.source(), + seed.bundle(), + seed.signerReceipt(), + seed.issuedAtEpochSecond(), + seed.expiresAtEpochSecond(), + seed.expiresAtEpochSecond() * 1000L, + seed.recoveryExpiresAt()); + } + + private void advanceToCandidate(IssuanceSeed seed) { + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'CANDIDATE', token_hash = ?, pending_registry = ?, " + + "active_registry = ? WHERE request_id = ? AND status = 'PREPARED'", + seed.tokenHash(), + seed.pendingRegistry(), + seed.activeRegistry(), + seed.requestId()); + } + + private static IssuanceSeed newSeed() { + UUID requestId = UUID.randomUUID(); + long issuedAt = Instant.now().getEpochSecond(); + return new IssuanceSeed( + requestId, + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://test-only/logging-admin", + UUID.randomUUID(), + digest(), + bytes("test-only-claims-" + requestId), + bytes("test-only-source-" + requestId), + bytes("test-only-authority-bundle-" + requestId), + bytes("test-only-signer-receipt-" + requestId), + issuedAt, + issuedAt + 300, + OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 60), ZoneOffset.UTC), + tokenHash(), + bytes("test-only-pending-registry-" + requestId), + bytes("test-only-active-registry-" + requestId), + bytes("test-only-pending-receipt-" + requestId), + bytes("opaque-test-only-encrypted-response-fixture-" + requestId), + bytes("opaque-test-only-owner-binding-" + requestId)); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java index d88b6f4378..627d60ce9d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java @@ -253,10 +253,11 @@ void controlUiIssuanceMustStartPreparedAndCanCommitAfterProtectedResponseReadbac + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, " + "caller_workload, caller_context_id, request_mac_key_id, request_digest, " + "claims_payload, source_payload, bundle_payload, signer_receipt, " - + "issued_at_epoch_second, expires_at_epoch_second, recovery_expires_at, " + + "issued_at_epoch_second, expires_at_epoch_second, " + + "registry_cleanup_deadline_epoch_millis, recovery_expires_at, " + "status, token_hash, pending_registry, active_registry, pending_receipt, " + "committed_at) VALUES (?, ?, ?, ?, ?, 'test', ?, 'test-key', ?, ?, ?, ?, ?, ?, ?, " - + "?::timestamptz, 'COMMITTED', ?, ?, ?, ?, CURRENT_TIMESTAMP)", + + "?, ?::timestamptz, 'COMMITTED', ?, ?, ?, ?, CURRENT_TIMESTAMP)", UUID.randomUUID(), rejectedOperationId, UUID.randomUUID(), @@ -270,6 +271,7 @@ void controlUiIssuanceMustStartPreparedAndCanCommitAfterProtectedResponseReadbac candidate, issuedAt, issuedAt + 300, + (issuedAt + 300) * 1000L, recoveryExpiresAt, "b".repeat(64), candidate, @@ -1227,6 +1229,7 @@ private static ControlUiIssuance insertCommittedControlUiIssuance( UUID tokenJti = UUID.randomUUID(); long issuedAt = Instant.now().getEpochSecond(); long expiresAt = issuedAt + 300; + long cleanupDeadlineEpochMillis = expiresAt * 1000L; OffsetDateTime recoveryExpiresAt = OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 30), ZoneOffset.UTC); byte[] candidate = new byte[] {1, 2, 3}; @@ -1245,9 +1248,10 @@ private static ControlUiIssuance insertCommittedControlUiIssuance( + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, " + "caller_workload, caller_context_id, request_mac_key_id, request_digest, " + "claims_payload, source_payload, bundle_payload, signer_receipt, " - + "issued_at_epoch_second, expires_at_epoch_second, recovery_expires_at, status) " + + "issued_at_epoch_second, expires_at_epoch_second, " + + "registry_cleanup_deadline_epoch_millis, recovery_expires_at, status) " + "VALUES (?, ?, ?, ?, ?, 'test-workload', ?, 'test-key', ?, ?, ?, ?, ?, ?, ?, " - + "?::timestamptz, 'PREPARED')", + + "?, ?::timestamptz, 'PREPARED')", requestId, operationId, tokenJti, @@ -1261,6 +1265,7 @@ private static ControlUiIssuance insertCommittedControlUiIssuance( candidate, issuedAt, expiresAt, + cleanupDeadlineEpochMillis, recoveryExpiresAt); context .dsl() diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java new file mode 100644 index 0000000000..d6af74fd8a --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java @@ -0,0 +1,1213 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.FlywayException; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.IntegrityConstraintViolationException; +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.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private final Set schemas = new HashSet<>(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @AfterEach + void dropTestOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.matches("account_start_session_auth_[a-f0-9]{32}")) { + throw new IllegalStateException("Refusing to dispose an unowned PostgreSQL schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + schemas.clear(); + } + + @Test + void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { + Context context = context(); + IssuanceCandidate candidate = candidate(context, tuple()); + + var created = context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + IssuanceCandidate differentOutput = withDifferentOutputs(candidate); + var duplicate = + context.inTransaction(() -> context.repository.createOrReadExact(differentOutput)); + + assertThat(created.created()).isTrue(); + assertThat(duplicate.created()).isFalse(); + assertThat(duplicate.issuance().issuanceOperationId()) + .isEqualTo(candidate.issuanceOperationId()); + assertThat(duplicate.issuance().encryptedResponseEnvelope()) + .containsExactly(candidate.encryptedResponseEnvelope()); + assertThat(duplicate.issuance().responseEnvelopeErasedAt()).isNull(); + assertThat(duplicate.issuance().bundleReference()).isEqualTo(candidate.bundleReference()); + var persistedBeforeRedemption = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(persistedBeforeRedemption.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.ISSUED); + + RedemptionRequest request = redemption(candidate, OWNER_ATTEMPT_ID, 11L); + var redeemed = context.inTransaction(() -> context.repository.redeemExact(request)); + var replay = context.inTransaction(() -> context.repository.redeemExact(request)); + assertThat(redeemed.replay()).isFalse(); + assertThat(replay.replay()).isTrue(); + assertThat(replay.authorityEvidenceBundle()).containsExactly(bytes("authority-bundle-v1")); + var retainedAfterRedemption = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(retainedAfterRedemption.bundleReference()).isEqualTo(candidate.bundleReference()); + assertThat(retainedAfterRedemption.bundleReference().linearization()).isEqualTo("123456789"); + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET bundle_linearization = ? WHERE control_plane_request_id = ?", + "123456788", + REQUEST_ID))) + .isInstanceOf(IntegrityConstraintViolationException.class); + assertThat( + context.inTransaction( + () -> + context + .repository + .findByControlPlaneRequestId(REQUEST_ID) + .orElseThrow() + .status())) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + } + + @Test + void realPostgresAllowsEqualIssueAndRedemptionTimestampsAtMillisecondPrecision() { + Context context = context(); + IssuanceCandidate candidate = candidate(context, tuple()); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + + RedemptionRequest request = redemption(candidate, OWNER_ATTEMPT_ID, 11L, candidate.issuedAt()); + var redeemed = context.inTransaction(() -> context.repository.redeemExact(request)); + + assertThat(redeemed.replay()).isFalse(); + var persisted = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(persisted.redeemedAt()).isEqualTo(candidate.issuedAt()); + assertThat(persisted.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + } + + @Test + void realPostgresRejectsRedemptionTimestampEarlierThanIssuance() { + Context context = context(); + IssuanceCandidate candidate = candidate(context, tuple()); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + + RedemptionRequest request = + redemption(candidate, OWNER_ATTEMPT_ID, 11L, candidate.issuedAt().minusMillis(1)); + assertThatThrownBy(() -> context.inTransaction(() -> context.repository.redeemExact(request))) + .isInstanceOf(IntegrityConstraintViolationException.class); + + var persisted = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(persisted.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.ISSUED); + assertThat(persisted.redeemedAt()).isNull(); + } + + @Test + void realPostgresAcceptsCanonicalNfcRequestIdAt128Utf8BytesAndRejectsOversizeBeforeInsert() { + Context context = context(); + String boundedRequestId = "é".repeat(64); + StartSessionPreAuthorizationReservationTuple boundaryTuple = + tuple(boundedRequestId, "128-byte NFC request ID boundary"); + IssuanceCandidate candidate = candidate(context, boundaryTuple, boundedRequestId); + + var created = context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + var retry = context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + assertThat(created.created()).isTrue(); + assertThat(retry.created()).isFalse(); + assertThat(retry.issuance().controlPlaneRequestId()).isEqualTo(boundedRequestId); + assertThat( + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(boundedRequestId))) + .isPresent(); + + String oversizedRequestId = "é".repeat(65); + String malformedTupleJson = + boundaryTuple + .canonicalJson() + .replace( + "\"requestId\":\"" + boundedRequestId + "\"", + "\"requestId\":\"" + oversizedRequestId + "\""); + assertThat(malformedTupleJson).contains(oversizedRequestId); + IssuanceCandidate oversized = + candidate( + context, boundedRequestId, bytes(malformedTupleJson), boundaryTuple.mutationDigest()); + int before = context.countRows(); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(oversized))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(context.countRows()).isEqualTo(before); + } + + @Test + void realPostgresAcceptsSharedRaw64DigestAndRejectsPrefixedMalformedOrChangedDigests() { + Context context = context(); + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + IssuanceCandidate canonical = candidate(context, tuple); + + assertThat(canonical.mutationDigest()).matches("[0-9a-f]{64}"); + assertThat(canonical.mutationDigest()).doesNotStartWith("sha256:"); + var created = context.inTransaction(() -> context.repository.createOrReadExact(canonical)); + assertThat(created.created()).isTrue(); + assertThat(created.issuance().mutationDigest()).isEqualTo(tuple.mutationDigest()); + + String digest = canonical.mutationDigest(); + String changedDigest = (digest.charAt(0) == '0' ? "1" : "0") + digest.substring(1); + for (String invalidDigest : new String[] {"sha256:" + digest, "not-a-digest", changedDigest}) { + IssuanceCandidate invalid = + candidate( + context, + canonical.controlPlaneRequestId(), + canonical.preAuthorizationTuple(), + invalidDigest); + int rowsBeforeInvalidDigest = context.countRows(); + + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(invalid))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(context.countRows()).isEqualTo(rowsBeforeInvalidDigest); + } + } + + @Test + void realPostgresAndRepositoryAcceptOnlyThe160KiBEnvelopeStorageBound() { + Context context = context(); + IssuanceCandidate base = candidate(context, tuple()); + byte[] maximumEnvelope = new byte[160 * 1024]; + Arrays.fill(maximumEnvelope, (byte) 0x5a); + IssuanceCandidate maximum = withEnvelope(base, maximumEnvelope); + + var created = context.inTransaction(() -> context.repository.createOrReadExact(maximum)); + assertThat(created.created()).isTrue(); + assertThat(created.issuance().encryptedResponseEnvelope()).containsExactly(maximumEnvelope); + + IssuanceCandidate overLimit = + candidateWithUniqueIdentity( + context, new byte[(160 * 1024) + 1], "repository and SQL envelope bound + 1"); + int rowCountBeforeRejectedCandidates = context.countRows(); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(overLimit))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("encrypted response envelope"); + assertThat(context.countRows()).isEqualTo(rowCountBeforeRejectedCandidates); + + assertThatThrownBy(() -> insertV126Row(context, overLimit)) + .isInstanceOf(IntegrityConstraintViolationException.class) + .hasMessageContaining("account_start_session_operator_authz_envelope_size_bound"); + assertThat(context.countRows()).isEqualTo(rowCountBeforeRejectedCandidates); + } + + @Test + void realPostgresFingerprintConstraintAllowsMaximumKeyIdAndRejectsDot() { + Context context = context(); + IssuanceCandidate maximumKeyId = + withFingerprint( + candidate(context, tuple()), + "arfp/v1/" + "k".repeat(64) + "/" + "a".repeat(64), + ISSUANCE_OPERATION_ID); + + assertThat(maximumKeyId.authorizationReferenceFingerprint()).hasSize(137); + assertThat( + context + .inTransaction(() -> context.repository.createOrReadExact(maximumKeyId)) + .created()) + .isTrue(); + assertThat( + context + .inTransaction( + () -> + context.repository.redeemExact( + redemption(maximumKeyId, OWNER_ATTEMPT_ID, 11L))) + .replay()) + .isFalse(); + + String dottedRequestId = REQUEST_ID + "-dot-key"; + StartSessionPreAuthorizationReservationTuple dottedTuple = + tuple(dottedRequestId, "invalid fingerprint key ID database constraint"); + IssuanceCandidate dottedKeyId = + withFingerprint( + candidate(context, dottedTuple, dottedRequestId), + "arfp/v1/key.with.dot/" + "b".repeat(64), + UUID.randomUUID()); + + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "INSERT INTO account_start_session_operator_authorizations " + + "(control_plane_request_id, pre_authorization_tuple, " + + "mutation_digest, issuance_workload_uri, reservation_owner_id, " + + "reservation_claim_fence, " + + "issuance_operation_id, issuance_fence, bundle_version, " + + "bundle_source_version, bundle_source_fence, " + + "bundle_linearization, authority_evidence_bundle, " + + "authorization_reference_fingerprint, " + + "encrypted_response_envelope, issued_at, reference_expires_at, " + + "response_envelope_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "'ISSUED')", + dottedKeyId.controlPlaneRequestId(), + dottedKeyId.preAuthorizationTuple(), + dottedKeyId.mutationDigest(), + dottedKeyId.issuanceWorkloadUri(), + dottedKeyId.reservationOwnerId(), + dottedKeyId.reservationClaimFence(), + dottedKeyId.issuanceOperationId(), + dottedKeyId.issuanceFence(), + dottedKeyId.bundleReference().bundleVersion(), + dottedKeyId.bundleReference().sourceVersion(), + dottedKeyId.bundleReference().sourceFence(), + dottedKeyId.bundleReference().linearization(), + dottedKeyId.authorityEvidenceBundle(), + dottedKeyId.authorizationReferenceFingerprint(), + dottedKeyId.encryptedResponseEnvelope(), + OffsetDateTime.ofInstant(dottedKeyId.issuedAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant( + dottedKeyId.referenceExpiresAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant( + dottedKeyId.responseEnvelopeExpiresAt(), ZoneOffset.UTC)))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThat(context.countRows()).isEqualTo(1); + } + + @Test + void concurrentExactIssuanceRetriesReturnOneOriginalOutput() throws Exception { + Context context = context(); + IssuanceCandidate firstCandidate = candidate(context, tuple()); + IssuanceCandidate secondCandidate = withDifferentOutputs(firstCandidate); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to race exact issuance retry"); + } + return context.inTransaction( + () -> context.repository.createOrReadExact(firstCandidate)); + }); + Future second = + executor.submit( + () -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to race exact issuance retry"); + } + return context.inTransaction( + () -> context.repository.createOrReadExact(secondCandidate)); + }); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + var firstResult = first.get(10, TimeUnit.SECONDS); + var secondResult = second.get(10, TimeUnit.SECONDS); + + assertThat( + List.of(firstResult, secondResult).stream() + .filter( + AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult + ::created) + .toList()) + .hasSize(1); + assertThat(firstResult.issuance().issuanceOperationId()) + .isEqualTo(secondResult.issuance().issuanceOperationId()); + assertThat(firstResult.issuance().encryptedResponseEnvelope()) + .containsExactly(secondResult.issuance().encryptedResponseEnvelope()); + assertThat(firstResult.issuance().issuanceOperationId()) + .isIn(firstCandidate.issuanceOperationId(), secondCandidate.issuanceOperationId()); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void changedTupleOrReservationBindingConflictsAndMalformedTupleNeverWrites() { + Context context = context(); + IssuanceCandidate candidate = candidate(context, tuple()); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + StartSessionPreAuthorizationReservationTuple changedTuple = tuple("changed audit reason"); + IssuanceCandidate changedTupleCandidate = + copyCandidate( + candidate, + canonicalBytes(changedTuple), + changedTuple.mutationDigest(), + RESERVATION_OWNER_ID, + candidate.reservationClaimFence()); + IssuanceCandidate changedClaim = + copyCandidate( + candidate, + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + RESERVATION_OWNER_ID, + candidate.reservationClaimFence() + 1L); + + assertThatThrownBy( + () -> + context.inTransaction( + () -> context.repository.createOrReadExact(changedTupleCandidate))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(changedClaim))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + + int beforeMalformed = context.countRows(); + IssuanceCandidate malformed = + copyCandidate( + candidate, + bytes("{malformed"), + candidate.mutationDigest(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence()); + assertThatThrownBy( + () -> context.inTransaction(() -> context.repository.createOrReadExact(malformed))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(context.countRows()).isEqualTo(beforeMalformed); + } + + @Test + void twoConcurrentDifferentOwnerAttemptsCanConsumeOnlyOneReference() throws Exception { + Context context = context(); + IssuanceCandidate candidate = candidate(context, tuple()); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future first = + executor.submit(() -> raceRedemption(context, candidate, ready, start, 12L)); + Future second = + executor.submit(() -> raceRedemption(context, candidate, ready, start, 13L)); + assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + Object firstResult = first.get(10, TimeUnit.SECONDS); + Object secondResult = second.get(10, TimeUnit.SECONDS); + List results = List.of(firstResult, secondResult); + assertThat( + results.stream() + .filter( + AccountStartSessionOperatorAuthorizationRepository.RedemptionResult.class + ::isInstance) + .toList()) + .hasSize(1); + assertThat(results.stream().filter(IllegalStateException.class::isInstance).toList()) + .hasSize(1); + var retained = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(retained.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(retained.redemptionOwnerAttemptId()) + .isIn( + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"), + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef8")); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void expiredReferenceCannotBeConsumedAndSqlGuardsRetainEvidence() { + Context context = context(); + IssuanceCandidate candidate = candidate(context, tuple()); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + RedemptionRequest expired = + new RedemptionRequest( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.authorizationReferenceFingerprint(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + OWNER_URI, + OWNER_ATTEMPT_ID, + 11L, + candidate.authorityEvidenceBundle(), + candidate.referenceExpiresAt()); + assertThatThrownBy(() -> context.inTransaction(() -> context.repository.redeemExact(expired))) + .isInstanceOf( + AccountStartSessionOperatorAuthorizationRepository.ReferenceExpiredException.class); + + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET authority_evidence_bundle = ? WHERE control_plane_request_id = ?", + bytes("rewritten"), + REQUEST_ID))) + .isInstanceOf(IntegrityConstraintViolationException.class); + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "DELETE FROM account_start_session_operator_authorizations " + + "WHERE control_plane_request_id = ?", + REQUEST_ID))) + .isInstanceOf(IntegrityConstraintViolationException.class); + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "TRUNCATE account_start_session_operator_authorizations"))) + .isInstanceOf(IntegrityConstraintViolationException.class); + + var retained = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(retained.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.ISSUED); + assertThat(retained.authorityEvidenceBundle()) + .containsExactly(candidate.authorityEvidenceBundle()); + } + + @Test + void responseEnvelopeErasureUsesDatabaseWallClockAndPreservesRedeemedCompactEvidence() { + Context context = context(); + Instant databaseNow = canonicalDatabaseNow(context); + IssuanceCandidate candidate = + candidate( + tuple(), + databaseNow.minusSeconds(2), + databaseNow.plusSeconds(10), + databaseNow.plusSeconds(12)); + context.inTransaction(() -> context.repository.createOrReadExact(candidate)); + + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET encrypted_response_envelope = NULL " + + "WHERE control_plane_request_id = ?", + candidate.controlPlaneRequestId()))) + .isInstanceOf(IntegrityConstraintViolationException.class); + + var erased = + context.inTransaction( + () -> { + assertThat( + ((OffsetDateTime) + context.transactionDsl.fetchValue("SELECT transaction_timestamp()")) + .toInstant()) + .isBefore(candidate.responseEnvelopeExpiresAt()); + var redeemed = + context.repository.redeemExact( + redemption( + candidate, OWNER_ATTEMPT_ID, 11L, candidate.issuedAt().plusSeconds(1))); + assertThat(redeemed.replay()).isFalse(); + assertThatThrownBy( + () -> + context.repository.eraseExpiredResponseEnvelope( + candidate.controlPlaneRequestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("evidence unavailable"); + + waitUntilDatabaseTime(context, candidate.responseEnvelopeExpiresAt()); + return context.repository.eraseExpiredResponseEnvelope( + candidate.controlPlaneRequestId()); + }); + + assertThat(erased.erasedNow()).isTrue(); + assertThat(erased.issuance().encryptedResponseEnvelope()).isNull(); + assertThat(erased.issuance().responseEnvelopeErasedAt()) + .isNotNull() + .isAfterOrEqualTo(candidate.responseEnvelopeExpiresAt()); + assertThat(erased.issuance().status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(erased.issuance().controlPlaneRequestId()) + .isEqualTo(candidate.controlPlaneRequestId()); + assertThat(erased.issuance().preAuthorizationTuple()) + .containsExactly(candidate.preAuthorizationTuple()); + assertThat(erased.issuance().mutationDigest()).isEqualTo(candidate.mutationDigest()); + assertThat(erased.issuance().authorizationReferenceFingerprint()) + .isEqualTo(candidate.authorizationReferenceFingerprint()); + assertThat(erased.issuance().authorityEvidenceBundle()) + .containsExactly(candidate.authorityEvidenceBundle()); + assertThat(erased.issuance().redemptionOwnerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID); + assertThat(erased.issuance().redemptionOwnerFence()).isEqualTo(11L); + assertThat(erased.issuance().redemptionReferenceFingerprint()) + .isEqualTo(candidate.authorizationReferenceFingerprint()); + assertThat(erased.issuance().redemptionAuthorityEvidenceBundle()) + .containsExactly(candidate.authorityEvidenceBundle()); + + var retry = + context.inTransaction( + () -> + context.repository.eraseExpiredResponseEnvelope(candidate.controlPlaneRequestId())); + assertThat(retry.erasedNow()).isFalse(); + assertThat(retry.issuance().responseEnvelopeErasedAt()) + .isEqualTo(erased.issuance().responseEnvelopeErasedAt()); + + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET encrypted_response_envelope = ? " + + "WHERE control_plane_request_id = ?", + candidate.encryptedResponseEnvelope(), + candidate.controlPlaneRequestId()))) + .isInstanceOf(IntegrityConstraintViolationException.class); + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET redemption_owner_fence = redemption_owner_fence + 1 " + + "WHERE control_plane_request_id = ?", + candidate.controlPlaneRequestId()))) + .isInstanceOf(IntegrityConstraintViolationException.class); + + Instant expiredAt = canonicalDatabaseNow(context); + StartSessionPreAuthorizationReservationTuple expiredTuple = + tuple("start-session/operator/" + UUID.randomUUID(), "expired erase-state guard test"); + IssuanceCandidate expiredUnredeemed = expiredCandidate(expiredTuple, expiredAt); + context.inTransaction(() -> context.repository.createOrReadExact(expiredUnredeemed)); + Instant redeemedAt = expiredUnredeemed.issuedAt().plusSeconds(1); + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET encrypted_response_envelope = NULL, status = 'REDEEMED', " + + "redemption_redeemer_workload_uri = ?, " + + "redemption_owner_attempt_id = ?, redemption_owner_fence = ?, " + + "redeemed_at = CAST(? AS TIMESTAMPTZ), " + + "redemption_reference_fingerprint = ?, " + + "redemption_authority_evidence_bundle = ? " + + "WHERE control_plane_request_id = ?", + OWNER_URI, + OWNER_ATTEMPT_ID, + 11L, + OffsetDateTime.ofInstant(redeemedAt, ZoneOffset.UTC), + expiredUnredeemed.authorizationReferenceFingerprint(), + expiredUnredeemed.authorityEvidenceBundle(), + expiredUnredeemed.controlPlaneRequestId()))) + .isInstanceOf(IntegrityConstraintViolationException.class); + + var retained = + context.inTransaction( + () -> + context + .repository + .findByControlPlaneRequestId(candidate.controlPlaneRequestId()) + .orElseThrow()); + assertThat(retained.encryptedResponseEnvelope()).isNull(); + assertThat(retained.responseEnvelopeErasedAt()) + .isEqualTo(erased.issuance().responseEnvelopeErasedAt()); + assertThat(retained.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(retained.redemptionOwnerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID); + } + + @Test + void v126RetainedEnvelopeSurvivesAdditiveErasureMigration() { + Context context = contextAt("126"); + IssuanceCandidate candidate = candidate(context, tuple()); + insertV126Row(context, candidate); + + Flyway.configure() + .dataSource(context.dataSource) + .schemas(context.schema) + .defaultSchema(context.schema) + .placeholders(Map.of("serviceSchema", context.schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + var retained = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(retained.encryptedResponseEnvelope()) + .containsExactly(candidate.encryptedResponseEnvelope()); + assertThat(retained.responseEnvelopeErasedAt()).isNull(); + assertThat(retained.preAuthorizationTuple()).containsExactly(candidate.preAuthorizationTuple()); + assertThat(retained.authorizationReferenceFingerprint()) + .isEqualTo(candidate.authorizationReferenceFingerprint()); + } + + @Test + void v1262RetainedMaximumLegacyEnvelopeSurvivesForwardSizeMigration() { + Context context = contextAt("126.2"); + IssuanceCandidate base = candidate(context, tuple()); + byte[] retainedLegacyEnvelope = new byte[64 * 1024]; + Arrays.fill(retainedLegacyEnvelope, (byte) 0x2d); + IssuanceCandidate legacy = withEnvelope(base, retainedLegacyEnvelope); + insertV126Row(context, legacy); + + Flyway.configure() + .dataSource(context.dataSource) + .schemas(context.schema) + .defaultSchema(context.schema) + .placeholders(Map.of("serviceSchema", context.schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + + var retained = + context.inTransaction( + () -> context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow()); + assertThat(retained.encryptedResponseEnvelope()).containsExactly(retainedLegacyEnvelope); + assertThat(retained.responseEnvelopeErasedAt()).isNull(); + assertThat(retained.preAuthorizationTuple()).containsExactly(legacy.preAuthorizationTuple()); + assertThat(retained.authorityEvidenceBundle()) + .containsExactly(legacy.authorityEvidenceBundle()); + assertThat(retained.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.ISSUED); + + assertThatThrownBy( + () -> + context.inTransactionWithoutResult( + () -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET authority_evidence_bundle = ? " + + "WHERE control_plane_request_id = ?", + bytes("changed-retained-evidence"), + legacy.controlPlaneRequestId()))) + .isInstanceOf(IntegrityConstraintViolationException.class); + assertThat( + context.inTransaction( + () -> + context + .repository + .findByControlPlaneRequestId(legacy.controlPlaneRequestId()) + .orElseThrow() + .encryptedResponseEnvelope())) + .containsExactly(retainedLegacyEnvelope); + } + + @Test + void v1263FailsClosedWhenLegacyEnvelopeSizeGuardIsAmbiguous() { + Context context = contextAt("126.2"); + context.adminDsl.execute( + "ALTER TABLE account_start_session_operator_authorizations " + + "ADD CONSTRAINT account_start_session_operator_authorizations_duplicate_size_guard " + + "CHECK (octet_length(encrypted_response_envelope) BETWEEN 1 AND 65536)"); + assertThat(legacyEnvelopeSizeGuardCount(context)).isEqualTo(2L); + + assertThatThrownBy( + () -> + Flyway.configure() + .dataSource(context.dataSource) + .schemas(context.schema) + .defaultSchema(context.schema) + .placeholders(Map.of("serviceSchema", context.schema)) + .locations("classpath:db/migration") + .load() + .migrate()) + .isInstanceOf(FlywayException.class) + .hasMessageContaining("V126.3"); + + assertThat(legacyEnvelopeSizeGuardCount(context)).isEqualTo(2L); + } + + private long legacyEnvelopeSizeGuardCount(Context context) { + var countRecord = + Objects.requireNonNull( + context.adminDsl.fetchOne( + "SELECT count(*) " + + "FROM pg_constraint c " + + "JOIN pg_attribute a ON a.attrelid = c.conrelid " + + "AND a.attname = 'encrypted_response_envelope' AND NOT a.attisdropped " + + "WHERE c.conrelid = 'account_start_session_operator_authorizations'::regclass " + + "AND c.contype = 'c' AND c.convalidated " + + "AND c.conkey = ARRAY[a.attnum]::SMALLINT[] " + + "AND lower(replace(regexp_replace(pg_get_expr(c.conbin, c.conrelid), " + + "'[[:space:]()]', '', 'g'), '\"', '')) IN (" + + "'octet_lengthencrypted_response_envelopebetween1and65536', " + + "'octet_lengthencrypted_response_envelope>=1andoctet_lengthencrypted_response_envelope<=65536')"), + "Expected a count row for legacy envelope size guards"); + return Objects.requireNonNull( + countRecord.get(0, Long.class), "Expected a non-null legacy envelope guard count"); + } + + private Context context() { + return contextAt(null); + } + + private Context contextAt(String targetVersion) { + String schema = "account_start_session_auth_" + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + DriverManagerDataSource dataSource = POSTGRES.dataSource(schema); + var migration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + migration.target(org.flywaydb.core.api.MigrationVersion.fromVersion(targetVersion)); + } + migration.load().migrate(); + DSLContext transactionDsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DSLContext adminDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context( + transactionDsl, + adminDsl, + transaction, + new AccountStartSessionOperatorAuthorizationRepository(transactionDsl), + dataSource, + schema); + } + + private static void insertV126Row(Context context, IssuanceCandidate candidate) { + context.adminDsl.execute( + "INSERT INTO account_start_session_operator_authorizations " + + "(control_plane_request_id, pre_authorization_tuple, mutation_digest, " + + "issuance_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "issuance_operation_id, issuance_fence, bundle_version, bundle_source_version, " + + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, " + + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, " + + "reference_expires_at, response_envelope_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ), " + + "CAST(? AS TIMESTAMPTZ), 'ISSUED')", + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + candidate.issuanceWorkloadUri(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + candidate.issuanceOperationId(), + candidate.issuanceFence(), + candidate.bundleReference().bundleVersion(), + candidate.bundleReference().sourceVersion(), + candidate.bundleReference().sourceFence(), + candidate.bundleReference().linearization(), + candidate.authorityEvidenceBundle(), + candidate.authorizationReferenceFingerprint(), + candidate.encryptedResponseEnvelope(), + OffsetDateTime.ofInstant(candidate.issuedAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant(candidate.referenceExpiresAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant(candidate.responseEnvelopeExpiresAt(), ZoneOffset.UTC)); + } + + private static Instant databaseNow(Context context) { + return Objects.requireNonNull( + (OffsetDateTime) context.adminDsl.fetchValue("SELECT clock_timestamp()")) + .toInstant(); + } + + private static Instant canonicalDatabaseNow(Context context) { + return databaseNow(context).truncatedTo(ChronoUnit.MILLIS); + } + + private static void waitUntilDatabaseTime(Context context, Instant boundary) { + long timeoutNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(20); + while (databaseNow(context).isBefore(boundary)) { + if (System.nanoTime() >= timeoutNanos) { + throw new IllegalStateException("Timed out waiting for PostgreSQL wall clock boundary"); + } + try { + Thread.sleep(10L); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted waiting for PostgreSQL wall clock boundary", interrupted); + } + } + } + + private static Object raceRedemption( + Context context, + IssuanceCandidate candidate, + CountDownLatch ready, + CountDownLatch start, + long ownerFence) { + ready.countDown(); + try { + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to race redemption"); + } + UUID attemptId = + ownerFence == 12L + ? UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7") + : UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef8"); + return context.inTransaction( + () -> context.repository.redeemExact(redemption(candidate, attemptId, ownerFence))); + } catch (IllegalStateException conflictOrUnavailable) { + return conflictOrUnavailable; + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + return new IllegalStateException("Interrupted while waiting to race redemption", interrupted); + } + } + + private static IssuanceCandidate withDifferentOutputs(IssuanceCandidate original) { + return new IssuanceCandidate( + original.controlPlaneRequestId(), + original.preAuthorizationTuple(), + original.mutationDigest(), + original.issuanceWorkloadUri(), + original.reservationOwnerId(), + original.reservationClaimFence(), + UUID.randomUUID(), + original.issuanceFence() + 1L, + bundleReference(original.issuanceFence() + 1L), + bytes("different bundle"), + "arfp/v1/key-2/" + "b".repeat(64), + bytes("different encrypted response"), + original.issuedAt().plusSeconds(1), + original.referenceExpiresAt().plusSeconds(1), + original.responseEnvelopeExpiresAt().plusSeconds(1)); + } + + private static IssuanceCandidate withFingerprint( + IssuanceCandidate original, String fingerprint, UUID operationId) { + return new IssuanceCandidate( + original.controlPlaneRequestId(), + original.preAuthorizationTuple(), + original.mutationDigest(), + original.issuanceWorkloadUri(), + original.reservationOwnerId(), + original.reservationClaimFence(), + operationId, + original.issuanceFence(), + original.bundleReference(), + original.authorityEvidenceBundle(), + fingerprint, + original.encryptedResponseEnvelope(), + original.issuedAt(), + original.referenceExpiresAt(), + original.responseEnvelopeExpiresAt()); + } + + private static IssuanceCandidate copyCandidate( + IssuanceCandidate original, + byte[] tuple, + String digest, + UUID reservationOwner, + long reservationFence) { + return new IssuanceCandidate( + original.controlPlaneRequestId(), + tuple, + digest, + original.issuanceWorkloadUri(), + reservationOwner, + reservationFence, + original.issuanceOperationId(), + original.issuanceFence(), + original.bundleReference(), + original.authorityEvidenceBundle(), + original.authorizationReferenceFingerprint(), + original.encryptedResponseEnvelope(), + original.issuedAt(), + original.referenceExpiresAt(), + original.responseEnvelopeExpiresAt()); + } + + private static IssuanceCandidate candidate( + Context context, StartSessionPreAuthorizationReservationTuple tuple) { + return candidate(context, tuple, REQUEST_ID); + } + + private static IssuanceCandidate candidate( + Context context, StartSessionPreAuthorizationReservationTuple tuple, String requestId) { + return candidate(context, requestId, canonicalBytes(tuple), tuple.mutationDigest()); + } + + private static IssuanceCandidate candidate( + Context context, String requestId, byte[] tupleBytes, String digest) { + Instant issuedAt = canonicalDatabaseNow(context).minusSeconds(2); + return new IssuanceCandidate( + requestId, + tupleBytes, + digest, + ISSUER_URI, + RESERVATION_OWNER_ID, + 3L, + ISSUANCE_OPERATION_ID, + 7L, + bundleReference(7L), + bytes("authority-bundle-v1"), + "arfp/v1/key-1/" + "a".repeat(64), + bytes("encrypted-original-response-envelope"), + issuedAt, + issuedAt.plusSeconds(180), + issuedAt.plusSeconds(210)); + } + + private static IssuanceCandidate withEnvelope( + IssuanceCandidate source, byte[] encryptedResponseEnvelope) { + return new IssuanceCandidate( + source.controlPlaneRequestId(), + source.preAuthorizationTuple(), + source.mutationDigest(), + source.issuanceWorkloadUri(), + source.reservationOwnerId(), + source.reservationClaimFence(), + source.issuanceOperationId(), + source.issuanceFence(), + source.bundleReference(), + source.authorityEvidenceBundle(), + source.authorizationReferenceFingerprint(), + encryptedResponseEnvelope, + source.issuedAt(), + source.referenceExpiresAt(), + source.responseEnvelopeExpiresAt()); + } + + private static IssuanceCandidate candidateWithUniqueIdentity( + Context context, byte[] encryptedResponseEnvelope, String auditReason) { + String requestId = "start-session/operator/" + UUID.randomUUID(); + var tuple = tuple(requestId, auditReason); + IssuanceCandidate base = candidate(context, tuple, requestId); + String randomHex = + UUID.randomUUID().toString().replace("-", "") + + UUID.randomUUID().toString().replace("-", ""); + return new IssuanceCandidate( + base.controlPlaneRequestId(), + base.preAuthorizationTuple(), + base.mutationDigest(), + base.issuanceWorkloadUri(), + base.reservationOwnerId(), + base.reservationClaimFence(), + UUID.randomUUID(), + base.issuanceFence(), + base.bundleReference(), + base.authorityEvidenceBundle(), + "arfp/v1/key-1/" + randomHex, + encryptedResponseEnvelope, + base.issuedAt(), + base.referenceExpiresAt(), + base.responseEnvelopeExpiresAt()); + } + + private static IssuanceCandidate candidate( + StartSessionPreAuthorizationReservationTuple tuple, + Instant issuedAt, + Instant referenceExpiresAt, + Instant responseEnvelopeExpiresAt) { + return new IssuanceCandidate( + tuple.controlPlaneRequestId(), + canonicalBytes(tuple), + tuple.mutationDigest(), + ISSUER_URI, + RESERVATION_OWNER_ID, + 3L, + ISSUANCE_OPERATION_ID, + 7L, + bundleReference(7L), + bytes("authority-bundle-v1"), + "arfp/v1/key-1/" + "a".repeat(64), + bytes("encrypted-original-response-envelope"), + issuedAt, + referenceExpiresAt, + responseEnvelopeExpiresAt); + } + + private static IssuanceCandidate expiredCandidate( + StartSessionPreAuthorizationReservationTuple tuple, Instant databaseNow) { + String uniqueFingerprint = + "arfp/v1/key-1/" + + UUID.randomUUID().toString().replace("-", "") + + UUID.randomUUID().toString().replace("-", ""); + return new IssuanceCandidate( + tuple.controlPlaneRequestId(), + canonicalBytes(tuple), + tuple.mutationDigest(), + ISSUER_URI, + RESERVATION_OWNER_ID, + 3L, + UUID.randomUUID(), + 8L, + bundleReference(8L), + bytes("expired-authority-bundle-v1"), + uniqueFingerprint, + bytes("expired-original-response-envelope"), + databaseNow.minusSeconds(240), + databaseNow.minusSeconds(60), + databaseNow.minusSeconds(30)); + } + + private static RedemptionRequest redemption( + IssuanceCandidate candidate, UUID ownerAttemptId, long ownerFence) { + return redemption(candidate, ownerAttemptId, ownerFence, candidate.issuedAt().plusSeconds(1)); + } + + private static RedemptionRequest redemption( + IssuanceCandidate candidate, UUID ownerAttemptId, long ownerFence, Instant now) { + return new RedemptionRequest( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.authorizationReferenceFingerprint(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + OWNER_URI, + ownerAttemptId, + ownerFence, + candidate.authorityEvidenceBundle(), + now); + } + + private static StartSessionPreAuthorizationReservationTuple tuple() { + return tuple("StartSession Account authorization repository integration test"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String auditReason) { + return tuple(REQUEST_ID, auditReason); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String controlPlaneRequestId, String auditReason) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + return StartSessionPreAuthorizationReservationTuple.createHuman( + controlPlaneRequestId, ACTOR_ID, action); + } + + private static byte[] canonicalBytes(StartSessionPreAuthorizationReservationTuple tuple) { + return tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static BundleReference bundleReference(long sourceFence) { + return new BundleReference( + "authorityEvidenceBundle/v1", "12", Long.toString(sourceFence), "123456789"); + } + + private static final UUID TENANT_ID = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); + private static final UUID ACTOR_ID = UUID.fromString("d888ddc4-4a62-4b25-9bab-c4f94860c2ca"); + private static final String REQUEST_ID = + "start-session/operator/2355f292-ab9c-458c-8d52-aef18b9254e8"; + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ca1b63bf-f09f-4a55-96bf-a1fd2e22349e"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("37b1f37d-05d2-4aab-8ed9-c01acbf6606e"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"); + private static final String ISSUER_URI = "spiffe://firemud/ns/prod/sa/logging-admin-service"; + private static final String OWNER_URI = "spiffe://firemud/ns/prod/sa/game-session-service"; + + private static final class Context { + private final DSLContext transactionDsl; + private final DSLContext adminDsl; + private final TransactionTemplate transaction; + private final AccountStartSessionOperatorAuthorizationRepository repository; + private final DriverManagerDataSource dataSource; + private final String schema; + + Context( + DSLContext transactionDsl, + DSLContext adminDsl, + TransactionTemplate transaction, + AccountStartSessionOperatorAuthorizationRepository repository, + DriverManagerDataSource dataSource, + String schema) { + this.transactionDsl = transactionDsl; + this.adminDsl = adminDsl; + this.transaction = transaction; + this.repository = repository; + this.dataSource = dataSource; + this.schema = schema; + } + + T inTransaction(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + + void inTransactionWithoutResult(Runnable action) { + transaction.executeWithoutResult(ignored -> action.run()); + } + + int countRows() { + return Objects.requireNonNull( + adminDsl.fetchOne( + "SELECT count(*) FROM account_start_session_operator_authorizations"), + "Missing Account StartSession authorization row-count readback") + .get(0, Integer.class); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java new file mode 100644 index 0000000000..8c5f88adad --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java @@ -0,0 +1,575 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl.ControlUiPrimaryIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Flyway/PostgreSQL owner storage proof only. Primary authentication, canonical authority, + * signer capture and Redis/TLS/WAITAOF are explicitly test-only doubles. The tenant source is a + * stipulated external Game Design fixture, not genuine owner provenance. No private proof + * constructor is bypassed: Coordination creates its receipt through its normal transport path. + * Opaque envelope fixture bytes prove retention, not AEAD, genuine issuance or physical Redis. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiIssuancePostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void originalPreparedCandidateCommittedAndLostResponseReadBackExactOwnerBytes() { + Context c = context(); + Fixture f = new Fixture(c); + var prepared = f.prepare(); + assertThat(prepared.status).isEqualTo("PREPARED"); + assertThat(prepared.expiresAt).isEqualTo(prepared.issuedAt.plusSeconds(300)); + assertThat(prepared.expiryMillis()).isEqualTo(prepared.expiresAt.toEpochMilli() + 300_000L); + assertThat(prepared.recoveryExpiry).isEqualTo(prepared.issuedAt.plusSeconds(60)); + var candidate = f.candidate(prepared); + assertThat(candidate.status).isEqualTo("CANDIDATE"); + Transport transport = new Transport(candidate); + var pending = + transport.client.registerPending( + candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); + var committed = c.tx(() -> c.operations.commit(candidate, pending)); + assertThat(committed.stored.status).isEqualTo("COMMITTED"); + + // Discard the commit response and re-read through a fresh repository instance/transaction. + var reread = + c.tx(() -> new AccountControlUiIssuanceRepository(c.dsl).findRequest(prepared.requestId)); + var recovered = c.tx(() -> c.operations.requireCommitted(reread)); + assertOriginal(prepared, recovered.stored); + assertThat(recovered.tokenHash()).isEqualTo(candidate.tokenHash); + assertThat(recovered.pendingRegistry()).isEqualTo(candidate.pendingRegistry); + assertThat(recovered.activeRegistry()).isEqualTo(candidate.activeRegistry); + assertThat(reread.expiryMillis()).isEqualTo(prepared.expiryMillis()); + var envelope = + Objects.requireNonNull( + c.tx(() -> c.operations.envelope(reread)), + "Original protected response envelope readback required"); + assertThat(envelope.encrypted()).isEqualTo(f.encryptedResponse); + assertThat(envelope.binding()).isEqualTo(f.ownerBinding); + assertThat(c.dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))).isEqualTo(1); + assertThat(c.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); + } + + @Test + void explicitlyConfiguredZeroMarginIsPresentOnNewOwnerRows() { + Context c = context(); + var prepared = new Fixture(c).prepare(0L); + + assertThat(prepared.registryCleanupDeadlineEpochMillis) + .isEqualTo(prepared.expiresAt.toEpochMilli()); + } + + @Test + void v126_2PreservesRetainedPreparedRowAndDeniesCurrentUseAndAdvance() { + Context c = contextAt("126.1"); + Fixture f = new Fixture(c); + UUID operationId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + Instant issuedAt = + Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS).minusSeconds(10); + Instant expiresAt = issuedAt.plusSeconds(300); + OffsetDateTime recoveryExpiresAt = + OffsetDateTime.ofInstant(issuedAt.plusSeconds(60), ZoneOffset.UTC); + byte[] claims = + bytes( + "{\"accountId\":\"" + + f.actor + + "\",\"jti\":\"" + + tokenJti + + "\",\"iat\":" + + issuedAt.getEpochSecond() + + ",\"nbf\":" + + issuedAt.getEpochSecond() + + ",\"exp\":" + + expiresAt.getEpochSecond() + + ",\"tokenGeneration\":1,\"authorityTuple\":{}," + + "\"membershipVersion\":{},\"issuanceFence\":1}"); + byte[] source = bytes("{\"historicalFixture\":true}"); + byte[] bundle = bytes("{\"authoritySourceVersions\":[],\"bundleRef\":{}}"); + byte[] signerReceipt = bytes("test-only-historical-signer-receipt"); + // Historical V126.1 fixture seeding uses real owner IDs but is not a production issuance path. + c.tx( + () -> + c.dsl.execute( + "INSERT INTO account_control_ui_issuance_operations" + + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload, caller_context_id," + + " request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt," + + " issued_at_epoch_second, expires_at_epoch_second, recovery_expires_at, status)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')", + f.request, + operationId, + tokenJti, + f.actor, + f.tenant, + "spiffe://test-only/control-ui", + UUID.randomUUID(), + "historical-test", + "c".repeat(64), + claims, + source, + bundle, + signerReceipt, + issuedAt.getEpochSecond(), + expiresAt.getEpochSecond(), + recoveryExpiresAt)); + var before = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE request_id = ?", + f.request), + "Historically seeded pre-deadline row required"); + + migrateToLatest(c); + + var after = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE request_id = ?", + f.request), + "Retained row must remain after additive migration"); + assertLegacyFieldsUnchanged(before, after); + assertThat(after.get("registry_cleanup_deadline_epoch_millis", Long.class)).isNull(); + + var retained = c.tx(() -> c.operations.findRequest(f.request)); + assertThat(retained.status).isEqualTo("PREPARED"); + assertThatThrownBy(retained::expiryMillis).isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + c.tx( + () -> + c.operations.bindCandidate( + retained, + "d".repeat(64), + bytes("test-only-envelope"), + bytes("test-only-binding"), + f.signer))) + .isInstanceOf(IllegalStateException.class); + assertThat(c.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isZero(); + var afterDeniedAdvance = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE request_id = ?", + f.request), + "Denied advancement must preserve retained row"); + assertLegacyFieldsUnchanged(before, afterDeniedAdvance); + assertThat(afterDeniedAdvance.get("registry_cleanup_deadline_epoch_millis", Long.class)) + .isNull(); + } + + @Test + void changedOriginalAndDirectSqlByteOrTimingChangesCannotRewriteRetainedOperation() { + Context c = context(); + Fixture f = new Fixture(c); + var prepared = f.prepare(); + var candidate = f.candidate(prepared); + Transport transport = new Transport(candidate); + var pending = + transport.client.registerPending( + candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); + c.tx(() -> c.operations.commit(candidate, pending)); + var changedRow = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations WHERE request_id = ?", + prepared.requestId), + "Original issuance row required before changed-input definition"); + changedRow.set( + changedRow.field("claims_payload", byte[].class), bytes("test-only-changed-original")); + var changed = new AccountControlUiIssuanceRepository.Stored(changedRow); + assertThatThrownBy(() -> c.tx(() -> c.operations.requireCommitted(changed))) + .isInstanceOf(IllegalStateException.class); + for (String column : + List.of("claims_payload", "source_payload", "bundle_payload", "signer_receipt")) { + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "UPDATE account_control_ui_issuance_operations SET " + + column + + " = ? WHERE request_id = ?", + bytes("test-only-rewrite"), + prepared.requestId))) + .isInstanceOf(DataAccessException.class); + } + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "UPDATE account_control_ui_issuance_operations" + + " SET recovery_expires_at = recovery_expires_at + INTERVAL '1 second' WHERE request_id = ?", + prepared.requestId))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "UPDATE account_control_ui_response_envelopes" + + " SET encrypted_response = ? WHERE operation_id = ?", + bytes("test-only-envelope-rewrite"), + prepared.operationId))) + .isInstanceOf(DataAccessException.class); + // A new row cannot evade the actual PostgreSQL-specific recovery bound either. + assertThatThrownBy( + () -> + c.tx( + () -> + c.dsl.execute( + "INSERT INTO account_control_ui_issuance_operations" + + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload, caller_context_id," + + " request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt," + + " issued_at_epoch_second, expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, recovery_expires_at, status)" + + " SELECT ?, ?, ?, account_uuid, tenant_uuid, caller_workload, caller_context_id, request_mac_key_id," + + " request_digest, claims_payload, source_payload, bundle_payload, signer_receipt, issued_at_epoch_second," + + " expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, to_timestamp(issued_at_epoch_second + 61), 'PREPARED'" + + " FROM account_control_ui_issuance_operations WHERE request_id = ?", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + prepared.requestId))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("account_control_ui_recovery_expiry_bound"); + assertOriginal(prepared, c.tx(() -> c.operations.findRequest(prepared.requestId))); + } + + @Test + void + durableRevokingDeniesCommittedRecoveryAndUnavailableExternalRevocationIsNotTerminalSuccess() { + Context c = context(); + Fixture f = new Fixture(c); + var prepared = f.prepare(); + var candidate = f.candidate(prepared); + Transport transport = new Transport(candidate); + var pending = + transport.client.registerPending( + candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); + var committed = c.tx(() -> c.operations.commit(candidate, pending)); + var revoking = c.tx(() -> c.operations.beginRecoveryFailure(committed.stored)); + assertThat(revoking.status).isEqualTo("REVOKING"); + assertThatThrownBy(() -> c.tx(() -> c.operations.requireCommitted(committed.stored))) + .isInstanceOf(IllegalStateException.class); + when(transport.commands.get(any(byte[].class))) + .thenThrow(new IllegalStateException("test-only transport unavailable")); + assertThatThrownBy(() -> transport.client.revoke(revoking)) + .isInstanceOf(IllegalStateException.class); + var held = c.tx(() -> c.operations.findRequest(prepared.requestId)); + assertThat(held.status).isEqualTo("REVOKING"); + assertOriginal(prepared, held); + var revocation = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT revocation_receipt FROM account_control_ui_issuance_operations WHERE request_id = ?", + prepared.requestId), + "Durable non-authorizing issuance row must remain present"); + assertThat(revocation.get("revocation_receipt")).isNull(); + assertThat(c.tx(() -> c.operations.beginRecoveryFailure(held)).status).isEqualTo("REVOKING"); + + byte[] revoked = AccountControlUiIssuanceRepository.revokedRegistry(held); + doReturn(held.pendingRegistry, revoked).when(transport.commands).get(any(byte[].class)); + var receipt = transport.client.revoke(held); + c.tx( + () -> { + c.operations.finishRecoveryFailure(held, receipt); + return null; + }); + assertThat(c.tx(() -> c.operations.findRequest(prepared.requestId)).status) + .isEqualTo("REVOKED"); + assertThatThrownBy(() -> c.tx(() -> c.operations.requireCommitted(committed.stored))) + .isInstanceOf(IllegalStateException.class); + } + + private static void assertOriginal( + AccountControlUiIssuanceRepository.Stored original, + AccountControlUiIssuanceRepository.Stored observed) { + assertThat(observed.operationId).isEqualTo(original.operationId); + assertThat(observed.requestId).isEqualTo(original.requestId); + assertThat(observed.jti).isEqualTo(original.jti); + assertThat(observed.claims).isEqualTo(original.claims); + assertThat(observed.sources).isEqualTo(original.sources); + assertThat(observed.bundle).isEqualTo(original.bundle); + assertThat(observed.signerReceipt).isEqualTo(original.signerReceipt); + assertThat(observed.issuedAt).isEqualTo(original.issuedAt); + assertThat(observed.expiresAt).isEqualTo(original.expiresAt); + assertThat(observed.recoveryExpiry).isEqualTo(original.recoveryExpiry); + } + + private static void assertLegacyFieldsUnchanged( + org.jooq.Record original, org.jooq.Record observed) { + for (String field : + List.of( + "request_id", + "operation_id", + "token_jti", + "account_uuid", + "tenant_uuid", + "caller_workload", + "caller_context_id", + "request_mac_key_id", + "request_digest", + "claims_payload", + "source_payload", + "bundle_payload", + "signer_receipt", + "issued_at_epoch_second", + "expires_at_epoch_second", + "recovery_expires_at", + "status", + "token_hash", + "pending_registry", + "active_registry", + "pending_receipt", + "committed_at", + "recovery_failed_at", + "revocation_receipt", + "created_at")) { + Object originalValue = original.get(field); + Object observedValue = observed.get(field); + if (originalValue instanceof byte[] originalBytes) { + assertThat((byte[]) observedValue).containsExactly(originalBytes); + } else { + assertThat(observedValue).isEqualTo(originalValue); + } + } + } + + private static final class Fixture { + final Context c; + final UUID actor, tenant = UUID.randomUUID(), request = UUID.randomUUID(); + final ControlUiPrimaryIdentity primary = mock(ControlUiPrimaryIdentity.class); + final AccountControlUiAuthority.Snapshot authority = + mock(AccountControlUiAuthority.Snapshot.class); + final AccountControlUiSignerOwner.Capture signer = + mock(AccountControlUiSignerOwner.Capture.class); + final byte[] encryptedResponse = bytes("test-only-opaque-encrypted-response-double"); + final byte[] ownerBinding = bytes("test-only-exact-envelope-owner-binding"); + + Fixture(Context c) { + this.c = c; + actor = + c.tx( + () -> { + Account account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername("control-ui-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("test-only-primary-hash"); + return new AccountRepository(c.dsl).save(account).getAccountUuid(); + }); + // Stipulated external creation evidence only; real source/claim triggers still execute. + c.tx( + () -> + c.dsl.execute( + "INSERT INTO account_fresh_tenant_identity_associations" + + " (schema_version, target_namespace, creation_request_id, operation_id, request_digest," + + " canonical_tenant_id, source_game_row_id, source_game_tenant_key, provenance_kind, evidence_digest)" + + " VALUES (1, 'test-control', ?, ?, ?, ?, 1, ?, 'NEW_GAME_ROW', ?)", + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + tenant, + tenant.toString(), + "sha256:" + "b".repeat(64))); + when(primary.accountId()).thenReturn(actor); + when(authority.actor()).thenReturn(actor); + when(authority.tenant()).thenReturn(tenant); + when(authority.authorityTuple()) + .thenReturn( + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 1L, + "tenantAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "membershipAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "privateRealmGrantVersions", + List.of())); + when(authority.membershipVersion()).thenReturn(Map.of(tenant.toString(), 1L)); + when(authority.issuanceFence()).thenReturn(1L); + when(authority.evidence()).thenReturn(bytes("test-only-source-evidence-double")); + when(authority.sources()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + bytes("test-only-account-source")))); + when(authority.accountIdentitySource()).thenReturn(Map.of("testOnly", true)); + when(authority.outboxCheckpoints()).thenReturn(List.of()); + when(signer.receipt()).thenReturn(bytes("test-only-signer-receipt-double")); + when(signer.kid()).thenReturn("test-control-kid"); + when(signer.generation()).thenReturn("1"); + } + + AccountControlUiIssuanceRepository.Stored prepare() { + return prepare(300_000L); + } + + AccountControlUiIssuanceRepository.Stored prepare(long sessionSafetyMarginMillis) { + return c.tx( + () -> + c.operations.prepare( + request, + "spiffe://test-only/control-ui", + UUID.randomUUID(), + "test-mac1", + "c".repeat(64), + primary, + authority, + signer, + Instant.ofEpochSecond(Instant.now().getEpochSecond()), + sessionSafetyMarginMillis)); + } + + AccountControlUiIssuanceRepository.Stored candidate( + AccountControlUiIssuanceRepository.Stored original) { + return c.tx( + () -> + c.operations.bindCandidate( + original, "d".repeat(64), encryptedResponse, ownerBinding, signer)); + } + } + + /** No Redis process or TLS proof: only actual owner adapter/receipt construction with doubles. */ + private static final class Transport { + @SuppressWarnings("unchecked") + final RedisCommands commands = mock(RedisCommands.class); + + @SuppressWarnings("unchecked") + final StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + + final AccountControlUiCoordination client; + + Transport(AccountControlUiIssuanceRepository.Stored original) { + var descriptor = AccountControlUiRegistryContract.descriptor(); + var catalog = mock(RedisScriptCatalog.class); + when(catalog.require(AccountControlUiRegistryContract.SCRIPT_ID)).thenReturn(descriptor); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn("account_coord_app"); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> + AccountControlUiCoordination.digest("SHA-1", invocation.getArgument(0))); + doReturn(1L) + .when(commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + doReturn(List.of(1L, 1L)).when(commands).dispatch(any(), any(), any()); + when(commands.pexpiretime(any(byte[].class))).thenReturn(original.expiryMillis()); + when(commands.get(any(byte[].class))).thenReturn(original.pendingRegistry); + client = + new AccountControlUiCoordination( + () -> connection, new AcknowledgementRequirements(1, 1, 1000), catalog); + } + } + + private static Context context() { + return contextAt(null); + } + + private static Context contextAt(String targetVersion) { + String schema = "control_ui_storage_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var migration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + migration.target(org.flywaydb.core.api.MigrationVersion.fromVersion(targetVersion)); + } + migration.load().migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return new Context( + dsl, new AccountControlUiIssuanceRepository(dsl), transaction, source, schema); + } + + private static void migrateToLatest(Context c) { + Flyway.configure() + .dataSource(c.dataSource) + .schemas(c.schema) + .defaultSchema(c.schema) + .placeholders(Map.of("serviceSchema", c.schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + } + + private record Context( + DSLContext dsl, + AccountControlUiIssuanceRepository operations, + TransactionTemplate transaction, + DriverManagerDataSource dataSource, + String schema) { + T tx(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java new file mode 100644 index 0000000000..b8bf61186c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java @@ -0,0 +1,187 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Composed negative boundary, NOT successful issuer/end-to-end proof. Actual primary auth, + * canonical source composition/currentness, issuance service/repository and PostgreSQL transactions + * execute together. External creation/bootstrap, party verification, legal action/publication, + * environment observations, and the isolated materializer/API deployment identity are explicitly + * stipulated test-only fixtures. The real signer lifecycle reaches only receipt-backed initial + * public prepublication; no committed signer, private Capture, registry receipt or successful + * issuance is manufactured. Missing committed signer/custody/signing/Redis never become authority. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiOwnerWorkflowPostgresIntegrationTest { + static final String CALLER = + "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + static final String OTP = "test-only-original-creator-otp"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @TempDir Path temporary; + + @Test + void realSourceAndPrimaryCompositionQuarantinesMismatchedCommittedSignerFences() + throws Exception { + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), temporary, true); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + var source = f.tx(() -> f.authority.captureInitial(f.tenant, environment)); + assertThat(source.actor()).isEqualTo(f.account.getAccountUuid()); + assertThat(source.tenant()).isEqualTo(f.tenant); + assertThat(source.sources()).hasSize(8); + var originalOtp = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); + try (var ignored = withPeer(CALLER)) { + assertThatThrownBy(() -> f.service.issue(f.request(OTP), environment)) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) + .hasMessage("Account durable and published active signer fences disagree"); + assertThat(f.challenges.findByAccountId(f.account.getId())).contains(originalOtp); + // The same exact request can retry its original OTP after owner rollback, but cannot mint. + assertThatThrownBy(() -> f.service.issue(f.request(OTP), environment)) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) + .hasMessage("Account durable and published active signer fences disagree"); + assertThatThrownBy(() -> f.service.issue(f.request("changed-secret"), environment)) + .isInstanceOf(AuthenticationException.class); + } + var afterDenial = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); + assertThat(afterDenial.getId()).isEqualTo(originalOtp.getId()); + assertThat(afterDenial.getCodeHash()).isEqualTo(originalOtp.getCodeHash()); + assertThat(afterDenial.getInvalidAttemptCount()).isEqualTo(1); + f.assertNoIssuance(); + } + + @Test + void invalidOtpBudgetPersistsThroughProxiedPrimaryDenialAndExhaustsExistingFiveAttemptLimit() + throws Exception { + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), temporary, true); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + var original = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); + try (var ignored = withPeer(CALLER)) { + for (int attempt = 1; attempt <= 5; attempt++) { + assertThatThrownBy(() -> f.service.issue(f.request("wrong-otp"), environment)) + .isInstanceOf(AuthenticationException.class); + if (attempt < 5) { + var retained = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); + assertThat(retained.getId()).isEqualTo(original.getId()); + assertThat(retained.getCodeHash()).isEqualTo(original.getCodeHash()); + assertThat(retained.getInvalidAttemptCount()).isEqualTo(attempt); + } else { + assertThat(f.challenges.findByAccountId(f.account.getId())).isEmpty(); + } + } + assertThatThrownBy(() -> f.service.issue(f.request(OTP), environment)) + .isInstanceOf(AuthenticationException.class); + } + f.assertNoIssuance(); + } + + @Test + void concurrentInvalidAttemptsBothCommitTheirOwnAccountingWithoutMinting() throws Exception { + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), temporary, true); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + java.util.concurrent.Callable attempt = + () -> { + try (var ignored = withPeer(CALLER)) { + ready.countDown(); + awaitLatch(start); + try { + f.service.issue(f.request("concurrent-wrong-otp"), environment); + throw new AssertionError("Invalid credential must not authenticate"); + } catch (AuthenticationException expected) { + return expected; + } + } + }; + var first = executor.submit(attempt); + var second = executor.submit(attempt); + awaitLatch(ready); + start.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS)).isNotNull(); + assertThat(second.get(10, TimeUnit.SECONDS)).isNotNull(); + assertThat( + f.challenges + .findByAccountId(f.account.getId()) + .orElseThrow() + .getInvalidAttemptCount()) + .isEqualTo(2); + f.assertNoIssuance(); + } finally { + start.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + + private static void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Expected concurrent credential attempt boundary"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted concurrent credential attempt boundary"); + } + } + + @Test + void changedProtectedCallerAndUnboundCurrentEnvironmentDenyWithoutConsumingOtp() + throws Exception { + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), temporary, true); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + var originalOtp = f.challenges.findByAccountId(f.account.getId()).orElseThrow(); + try (var ignored = + withPeer("spiffe://firemud/ns/control-ui-owner-proof/sa/game-design-service")) { + assertThatThrownBy(() -> f.service.issue(f.request(OTP), environment)) + .isInstanceOf(IllegalStateException.class); + } + // Explicit test-only protected environment observation now identifies a different scope. + // The actual current owner binding repository has no matching publication; no fallback exists. + f.boundary.set(testBoundary("test-withdrawn")); + CapturedEnvironmentBoundary changed = f.terms.captureCurrentEnvironmentBoundary(); + try (var ignored = withPeer(CALLER)) { + assertThatThrownBy(() -> f.service.issue(f.request(OTP), changed)) + .isInstanceOf(RuntimeException.class); + } + assertThat(f.challenges.findByAccountId(f.account.getId())).contains(originalOtp); + f.assertNoIssuance(); + } + + private static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary testBoundary( + String name) { + return AccountControlUiOwnerSourcesFixture.testBoundary(name); + } + + static AccountControlUiOwnerSourcesFixture.PeerScope withPeer(String uri) { + return AccountControlUiOwnerSourcesFixture.withPeer(uri); + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java new file mode 100644 index 0000000000..840d8eb920 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -0,0 +1,1204 @@ +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.mock; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.ManagedChannel; +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.StatusRuntimeException; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.codec.ByteArrayCodec; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.config.AccountStartSessionOperatorAuthorizationConfiguration; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +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.grpc.GrpcPeerCertificateEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.loggingadmin.StartSessionReservationMutationTestFixtures; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceGrpcService; +import net.firedevops.firemud.loggingadmin.service.impl.StartSessionReservationEvidenceLeafApproval; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.boot.convert.ApplicationConversionService; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.env.MapPropertySource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Isolated positive Account storage/producer proof with explicitly stipulated upstream trust, + * materializer Secret observations, validator inventory/acceptance and external creator/legal + * evidence. Generated ephemeral key custody and test-only ConfigMap CAS replace platform delivery. + * Real Account repositories, transactions, coordinator, materialization RPC owner, mounted signer, + * issuance, physical Coordination Redis and actor/order owners execute. No production trust, + * deployed Pod attribution, World APPLIED, public wiring or runtime activation is established. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountControlUiPositiveOwnerPostgresIntegrationTest { + private static final Network NETWORK = Network.newNetwork(); + private static final String PASSWORD = UUID.randomUUID().toString(); + + @Container + static final PostgreSQLContainer postgres = + AccountControlUiOwnerWorkflowPostgresIntegrationTest.postgres; + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("positive-control-ui-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "positive-control-ui-primary", + "6379"); + + @TempDir Path temporary; + + private InProcessLoggingTransport loggingTransport; + + @AfterEach + void clearLoggingTransport() throws Exception { + SessionContext.clear(); + if (loggingTransport != null) { + loggingTransport.close(); + loggingTransport = null; + } + } + + @Test + void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() throws Exception { + var f = + new AccountControlUiOwnerSourcesFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + temporary, + false); + var lifecycle = new AccountControlUiSignerFixture(f, temporary); + lifecycle.commit(); + // This is the actual private lifecycle-derived signer receipt, never a handcrafted Capture. + var originalSigner = f.tx(lifecycle.signer::captureCurrent); + assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) + .isEqualTo(originalSigner.receipt()); + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 29); + try (var connections = new RedisFixture()) { + var admin = connections.admin; + var accountClient = connections.account; + try (var connection = admin.connect(ByteArrayCodec.INSTANCE)) { + connection + .sync() + .aclSetuser( + "account_coord_app", + new io.lettuce.core.AclSetuserArgs() + .reset() + .on() + .addPassword(PASSWORD) + .keyPattern("session:auth:token:*") + .addCommand(io.lettuce.core.protocol.CommandType.HELLO) + .addCommand(io.lettuce.core.protocol.CommandType.PING) + .addCommand( + io.lettuce.core.protocol.CommandType.CLIENT, + io.lettuce.core.protocol.CommandKeyword.SETINFO) + .addCommand( + io.lettuce.core.protocol.CommandType.ACL, + io.lettuce.core.protocol.CommandKeyword.WHOAMI) + .addCommand( + io.lettuce.core.protocol.CommandType.SCRIPT, + io.lettuce.core.protocol.CommandKeyword.LOAD) + .addCommand(io.lettuce.core.protocol.CommandType.EVALSHA) + .addCommand(io.lettuce.core.protocol.CommandType.GET) + .addCommand(io.lettuce.core.protocol.CommandType.SET) + .addCommand(io.lettuce.core.protocol.CommandType.PEXPIRETIME) + .addCommand(io.lettuce.core.protocol.CommandType.TIME)); + connection + .sync() + .dispatch( + TestAclCommand.INSTANCE, + new io.lettuce.core.output.StatusOutput<>(ByteArrayCodec.INSTANCE), + new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) + .add("SETUSER") + .add("account_coord_app") + .add("+waitaof")); + awaitLocalAndReplicaAof(connection.sync()); + } + var registry = + new AccountControlUiCoordination( + () -> accountClient.connect(ByteArrayCodec.INSTANCE), + new AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements( + 1, 1, 5000), + testCatalog()); + var operations = new AccountControlUiIssuanceRepository(f.dsl); + var publicSource = + new AccountJwtJwksTrustedSource( + lifecycle.client, + lifecycle.trust, + lifecycle.desired, + lifecycle.publication, + f.manager); + var actors = + new AccountControlUiActorService( + operations, + f.authority, + lifecycle.signer, + registry, + publicSource, + f.fences, + f.manager, + Clock.systemUTC()); + var issuance = + new AccountControlUiIssuanceService( + f.primary, + operations, + f.authority, + f.fences, + lifecycle.signer, + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary.resolve("custody")), Clock.systemUTC()), + registry, + actors, + f.manager, + Clock.systemUTC(), + 300_000L, + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER); + var environment = f.terms.captureCurrentEnvironmentBoundary(); + String compact; + byte[] originalCompact; + Instant originalExpiry, originalRecoveryExpiry; + try (var peer = + AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer( + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER); + var issued = + issuance.issue( + f.request(AccountControlUiOwnerWorkflowPostgresIntegrationTest.OTP), + environment)) { + originalCompact = issued.compactBytes(); + compact = new String(originalCompact, StandardCharsets.US_ASCII); + originalExpiry = issued.expiresAt(); + originalRecoveryExpiry = issued.recoveryExpiresAt(); + } + assertThat(f.challenges.findByAccountId(f.account.getId())).isEmpty(); + var originalOperation = f.tx(() -> operations.findRequest(f.request)); + var originalEnvelope = f.tx(() -> operations.envelope(originalOperation)); + // Simulate loss of the completed response: recover with the original, now-consumed OTP. + // No new challenge or primary-auth credential is installed before the exact retry. + try (var peer = + AccountControlUiOwnerWorkflowPostgresIntegrationTest.withPeer( + AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER); + var recovered = + issuance.issue( + f.request(AccountControlUiOwnerWorkflowPostgresIntegrationTest.OTP), + environment)) { + assertThat(recovered.compactBytes()).isEqualTo(originalCompact); + assertThat(recovered.expiresAt()).isEqualTo(originalExpiry); + assertThat(recovered.recoveryExpiresAt()).isEqualTo(originalRecoveryExpiry); + assertThatThrownBy(() -> issuance.issue(f.request("changed-original-otp"), environment)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Control-ui issuance idempotency conflict"); + } + assertThat(f.challenges.findByAccountId(f.account.getId())).isEmpty(); + var recoveredOperation = f.tx(() -> operations.findRequest(f.request)); + assertThat(recoveredOperation.operationId).isEqualTo(originalOperation.operationId); + assertThat(recoveredOperation.status).isEqualTo("COMMITTED"); + assertThat(recoveredOperation.tokenHash).isEqualTo(originalOperation.tokenHash); + assertThat(recoveredOperation.claims).isEqualTo(originalOperation.claims); + var recoveredEnvelope = f.tx(() -> operations.envelope(recoveredOperation)); + assertThat(recoveredEnvelope.encrypted()).isEqualTo(originalEnvelope.encrypted()); + assertThat(recoveredEnvelope.binding()).isEqualTo(originalEnvelope.binding()); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))) + .isEqualTo(1); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); + var actor = actors.authenticate(compact, f.tenant, environment); + assertThat(actor.accountId()).isEqualTo(f.account.getAccountUuid()); + var snapshot = f.tx(() -> f.authority.captureInitial(f.tenant, environment)); + var binding = originalBinding(f, snapshot.sources()); + var claimed = actors.claimOriginalDraft(compact, binding, environment); + assertThat(claimed.ordering().name()).isEqualTo("COMMIT_ORDER"); + assertOrder(actors.claimOriginalDraft(compact, binding, environment), binding); + assertOrder(f.tx(() -> f.fences.read(binding)), binding); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))) + .isEqualTo(1); + assertThat(f.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isEqualTo(1); + String tokenHash = + AccountControlUiIssuanceRepository.hash(compact.getBytes(StandardCharsets.US_ASCII)); + var retained = f.tx(() -> operations.findToken(tokenHash)); + assertThat(retained.status).isEqualTo("COMMITTED"); + assertThat(retained.signerReceipt).isEqualTo(originalSigner.receipt()); + var active = registry.readActive(tokenHash); + assertThat(active).isNotEmpty(); + var committed = f.tx(() -> operations.requireCommitted(operations.findToken(tokenHash))); + var insufficientAck = + new AccountControlUiCoordination( + () -> accountClient.connect(ByteArrayCodec.INSTANCE), + new AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements( + 1, 2, 1000), + testCatalog()); + assertThatThrownBy(() -> insufficientAck.activate(committed)) + .isInstanceOf(IllegalStateException.class); + assertThat(registry.readActive(tokenHash)).isEqualTo(active); + // An exact actor cannot claim an original binding whose retained Account source is changed. + var changed = new ArrayList<>(snapshot.sources()); + var first = changed.getFirst(); + changed.set( + 0, + new DraftAuthorizationFenceBinding.SourceEvidence( + first.kind(), + first.scopeId(), + first.generation(), + first.sourceVersion(), + first.checkpointStream(), + first.checkpointSequence(), + new byte[] {99})); + var changedBinding = originalBinding(f, changed); + assertThatThrownBy(() -> actors.claimOriginalDraft(compact, changedBinding, environment)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact current authenticated initial creator required"); + assertOrder(f.tx(() -> f.fences.read(binding)), binding); + + var startSessionAction = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(f.tenant, "control-ui-owner-proof"), + new StartSessionOperatorAction.Target(17L, actor.accountId()), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "test-only Account operator composition"); + assertThat(actor.tenantId()).isEqualTo(f.tenant); + Map> verifiedScopedRoles = + actors.withCurrent( + compact, + f.tenant, + environment, + current -> { + if (!current.stored().accountId.equals(actor.accountId()) + || !current.stored().tenantId.equals(actor.tenantId())) { + throw new IllegalStateException( + "Current Account actor differs from the authenticated operator"); + } + return verifiedScopedRoles( + AccountControlUiIssuanceRepository.object(current.stored().claims), + actor.tenantId()); + }); + assertThat(verifiedScopedRoles) + .containsEntry(actor.tenantId().toString(), List.of("tenantAdmin")); + SessionContext.setContext(actor.accountId().toString(), List.of(), verifiedScopedRoles); + net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationTuple + loggingTuple; + try { + loggingTuple = + net.firedevops.firemud.loggingadmin.operator + .StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-" + UUID.randomUUID(), startSessionAction); + } finally { + SessionContext.clear(); + } + assertThat(loggingTuple.isAuthorityDerived()).isTrue(); + assertThat(loggingTuple.actor().accountId()).isEqualTo(actor.accountId()); + var tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + loggingTuple.canonicalJson()); + byte[] tupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + // Controlled test-only Game Session owner-attempt binding; no GS mutation workflow runs here. + UUID ownerAttemptId = UUID.randomUUID(); + long ownerFence = 7L; + String loggingSchema = "start_session_" + UUID.randomUUID().toString().replace("-", ""); + var loggingDataSource = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + loggingDataSource.setSchema(loggingSchema); + Flyway.configure() + .dataSource(loggingDataSource) + .schemas(loggingSchema) + .defaultSchema(loggingSchema) + .placeholders(Map.of("serviceSchema", loggingSchema)) + .locations("filesystem:" + loggingMigrations()) + .load() + .migrate(); + var reservationFixture = + StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(postgres, loggingSchema); + var reservationService = reservationFixture.service(); + var approvedAccountLeaf = testAccountLeafEvidence(); + Path approvedLeafFile = + temporary.resolve("account-reservation-evidence-approved-test-leaf.txt"); + Files.writeString( + approvedLeafFile, + "active=" + approvedAccountLeaf.leafSha256() + "\n", + StandardCharsets.US_ASCII); + loggingTransport = + inProcessLoggingTransport( + new StartSessionReservationEvidenceGrpcService( + reservationService, + new StartSessionReservationEvidenceLeafApproval(approvedLeafFile.toString()), + "control-ui-owner-proof"), + "spiffe://firemud/ns/control-ui-owner-proof/sa/account-service", + approvedAccountLeaf); + + var acquisition = reservationService.acquire(loggingTuple); + assertThat(acquisition.newlyAcquired()).isTrue(); + var claim = acquisition.claim(); + var pending = reservationService.markAuthorizationPending(claim); + assertThat(pending.mayDispatchAccountAuthorization()).isTrue(); + assertThat(pending.snapshot().tuple().canonicalJson()) + .isEqualTo(loggingTuple.canonicalJson()); + assertThat(pending.snapshot().mutationDigest()).isEqualTo(loggingTuple.mutationDigest()); + assertThat(pending.snapshot().phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(pending.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + ClaimEvidence claimEvidence = claim.claimEvidence(); + assertThat(claimEvidence.reservationOwnerId()).isNotEqualTo(new UUID(0L, 0L)); + assertThat(claimEvidence.currentClaimOwnerId()).isEqualTo(claimEvidence.reservationOwnerId()); + assertThat(claimEvidence.currentClaimFence()).isEqualTo(pending.snapshot().claimFence()); + + ReadCurrentClaimEvidenceResponse currentClaim = + loggingTransport + .accountClient() + .readCurrentClaimEvidence( + tuple, + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence(), + StartSessionReservationEvidenceClient.Purpose.ISSUE); + assertThat(currentClaim.getControlPlaneRequestId()).isEqualTo(tuple.controlPlaneRequestId()); + assertThat(currentClaim.getPreAuthorizationTupleJson().toByteArray()).isEqualTo(tupleBytes); + assertThat(currentClaim.getMutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(currentClaim.getReservationOwnerId()) + .isEqualTo(claimEvidence.reservationOwnerId().toString()); + assertThat(currentClaim.getReservationClaimFence()) + .isEqualTo(claimEvidence.reservationClaimFence()); + assertThat(currentClaim.getClaimOwnerId()) + .isEqualTo(claimEvidence.currentClaimOwnerId().toString()); + assertThat(currentClaim.getClaimFence()).isEqualTo(claimEvidence.currentClaimFence()); + assertThat(currentClaim.getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(currentClaim.getClaimExpiresAtEpochMillis()) + .isGreaterThan(currentClaim.getObservedAtEpochMillis()); + assertThat(currentClaim.getClaimExpiresAtEpochMillis()) + .isEqualTo(pending.snapshot().claimExpiresAtEpochMillis()); + + ReadCurrentClaimEvidenceRequest substitutedClaim = + currentClaimRequest(tuple, claimEvidence, claimEvidence.currentClaimFence() + 1L); + assertThatThrownBy( + () -> loggingTransport.receiverStub().readCurrentClaimEvidence(substitutedClaim)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + var storedPending = reservationService.find(tuple.controlPlaneRequestId()).orElseThrow(); + assertThat(storedPending.tuple().canonicalJson()).isEqualTo(loggingTuple.canonicalJson()); + assertThat(storedPending.state()).isEqualTo(State.AUTHORIZATION_PENDING); + + byte[] operatorFingerprintKey = new byte[32]; + Arrays.fill(operatorFingerprintKey, (byte) 0x5a); + var fingerprintKey = + new AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial( + "test-operator-key", new SecretKeySpec(operatorFingerprintKey, "HmacSHA256")); + Arrays.fill(operatorFingerprintKey, (byte) 0); + custody("operator-response-envelope", "test-envelope-key", 53); + var operatorRepository = new AccountStartSessionOperatorAuthorizationRepository(f.dsl); + String gameDesignPeer = "spiffe://firemud/ns/control-ui-owner-proof/sa/game-design-service"; + String gameSessionPeer = "spiffe://firemud/ns/control-ui-owner-proof/sa/game-session-service"; + try (var operatorContext = + operatorAuthorizationContext( + actors, + operations, + loggingTransport.accountClient(), + operatorRepository, + () -> + new AccountOperatorAuthorizationFingerprintKeyring.Snapshot( + fingerprintKey, List.of()), + f.terms, + f.manager, + temporary.resolve("custody/operator-response-envelope"))) { + var operatorAuthorization = + operatorContext.getBean(AccountStartSessionOperatorAuthorizationService.class); + var accountReceiver = + new StartSessionOperatorAuthorizationGrpcService( + operatorAuthorization, "control-ui-owner-proof"); + try (var accountTransport = + inProcessAccountTransport(accountReceiver, "control-ui-owner-proof")) { + var issueRequest = + IssueHumanOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setControlUiJwt(compact) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setCurrentClaimOwnerId(claimEvidence.currentClaimOwnerId().toString()) + .setCurrentClaimFence(claimEvidence.currentClaimFence()) + .build(); + + assertThatThrownBy( + () -> + accountTransport + .gameDesign() + .issueHumanOperatorAuthorizationReference(issueRequest)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + f.tx( + () -> + operatorRepository.findByControlPlaneRequestId( + tuple.controlPlaneRequestId()))) + .isEmpty(); + + var issuedOperator = + accountTransport.logging().issueHumanOperatorAuthorizationReference(issueRequest); + assertThat(issuedOperator.getAuthenticatedLoggingWorkloadIdentity()) + .isEqualTo(AccountControlUiOwnerWorkflowPostgresIntegrationTest.CALLER); + + var staleRecoveryRequest = + RecoverOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setCurrentClaimOwnerId(claimEvidence.currentClaimOwnerId().toString()) + .setCurrentClaimFence(claimEvidence.currentClaimFence()) + .build(); + + assertThatThrownBy( + () -> + accountTransport + .logging() + .recoverOperatorAuthorizationReference(staleRecoveryRequest)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + long originalClaimExpiresAt = pending.snapshot().claimExpiresAtEpochMillis(); + long remainingClaimMillis = originalClaimExpiresAt - System.currentTimeMillis(); + if (remainingClaimMillis >= 0L) { + Thread.sleep(remainingClaimMillis + 5L); + } + var expiredClaim = + reservationService.expireClaim( + claim, Phase.ACCOUNT_AUTHORIZATION, State.AUTHORIZATION_PENDING); + assertThat(expiredClaim.phase()).isEqualTo(Phase.ACCOUNT_AUTHORIZATION); + assertThat(expiredClaim.state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(expiredClaim.claimState()).isEqualTo(ClaimState.EXPIRED); + assertThat(expiredClaim.reservationClaimFence()) + .isEqualTo(claimEvidence.reservationClaimFence()); + assertThat(expiredClaim.claimFence()).isEqualTo(claimEvidence.currentClaimFence() + 1L); + + var recovery = + reservationService.acquireAuthorizationRecoveryClaim(loggingTuple).orElseThrow(); + var recoveryEvidence = recovery.claim().claimEvidence(); + assertThat(recovery.snapshot().claimPurpose()) + .isEqualTo(ClaimPurpose.AUTHORIZATION_RECOVERY); + assertThat(recovery.snapshot().claimState()).isEqualTo(ClaimState.ACTIVE); + assertThat(recoveryEvidence.reservationOwnerId()) + .isEqualTo(claimEvidence.reservationOwnerId()); + assertThat(recoveryEvidence.reservationClaimFence()) + .isEqualTo(claimEvidence.reservationClaimFence()); + assertThat(recoveryEvidence.currentClaimOwnerId()) + .isNotEqualTo(recoveryEvidence.reservationOwnerId()); + assertThat(recoveryEvidence.currentClaimFence()) + .isEqualTo(expiredClaim.claimFence() + 1L); + + var recoverRequest = + RecoverOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setReservationOwnerId(recoveryEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(recoveryEvidence.reservationClaimFence()) + .setCurrentClaimOwnerId(recoveryEvidence.currentClaimOwnerId().toString()) + .setCurrentClaimFence(recoveryEvidence.currentClaimFence()) + .build(); + var recoveredOperator = + accountTransport.logging().recoverOperatorAuthorizationReference(recoverRequest); + assertThat(recoveredOperator.getOperatorAuthorizationReference()) + .isEqualTo(issuedOperator.getOperatorAuthorizationReference()); + assertThat(recoveredOperator.getAuthorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); + assertThat(recoveredOperator.getExpiresAt()).isEqualTo(issuedOperator.getExpiresAt()); + assertThat(recoveredOperator.getAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); + assertThat(recoveredOperator.getBundleReference()) + .isEqualTo(issuedOperator.getBundleReference()); + assertThat(recoveredOperator.getAuthenticatedLoggingWorkloadIdentity()) + .isEqualTo(issuedOperator.getAuthenticatedLoggingWorkloadIdentity()); + + var issuedBundle = + AccountStartSessionOperatorAuthorityBundle.decode( + issuedOperator.getAuthorityEvidenceBundle().toByteArray()); + assertThat(issuedBundle.jsonValue()).containsEntry("issuanceKind", "human_operator"); + assertThat(issuedBundle.jsonValue().get("issuanceEvidence")) + .isInstanceOf(java.util.Map.class); + var humanEvidence = + (java.util.Map) issuedBundle.jsonValue().get("issuanceEvidence"); + assertThat(humanEvidence.get("evidenceType")).isEqualTo("HumanAuthorityEvidence/v1"); + assertThat(humanEvidence.get("role")).isEqualTo("tenantAdmin"); + assertThat(humanEvidence.containsKey("assurance")).isFalse(); + + var redeemRequest = + RedeemOperatorAuthorizationRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setOperatorAuthorizationReference( + issuedOperator.getOperatorAuthorizationReference()) + .setAuthorizationReferenceFingerprint( + issuedOperator.getAuthorizationReferenceFingerprint()) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setOwnerAttemptId(ownerAttemptId.toString()) + .setOwnerFence(ownerFence) + .build(); + var redeemed = accountTransport.gameSession().redeemOperatorAuthorization(redeemRequest); + assertThat(redeemed.getReplay()).isFalse(); + assertThat(redeemed.getAuthorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); + assertThat(redeemed.getAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); + + var projectionRequest = + ReadRedeemedOperationProjectionRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setAuthorizationReferenceFingerprint( + issuedOperator.getAuthorizationReferenceFingerprint()) + .setReservationOwnerId(claimEvidence.reservationOwnerId().toString()) + .setReservationClaimFence(claimEvidence.reservationClaimFence()) + .setOwnerAttemptId(ownerAttemptId.toString()) + .setOwnerFence(ownerFence) + .build(); + var projection = + accountTransport.gameDesign().readRedeemedOperationProjection(projectionRequest); + var exactRetry = + accountTransport.gameDesign().readRedeemedOperationProjection(projectionRequest); + + var changedAction = + new StartSessionOperatorAction( + startSessionAction.actionFamilySchemaId(), + startSessionAction.actionFamilySchemaVersion(), + startSessionAction.scope(), + new StartSessionOperatorAction.Target( + startSessionAction.target().gameTemplateId() + 1L, + startSessionAction.target().ownerAccountId()), + startSessionAction.expectedVersion(), + startSessionAction.mutation(), + "test-only changed StartSession operation"); + var changedTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + tuple.controlPlaneRequestId(), tuple.actor().accountId(), changedAction); + var wrongOperationRead = + projectionRequest.toBuilder() + .setCanonicalPreAuthorizationTupleBytes( + ByteString.copyFrom( + changedTuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .build(); + assertThatThrownBy( + () -> + accountTransport + .gameDesign() + .readRedeemedOperationProjection(wrongOperationRead)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + + var storedAfterDeniedRead = + f.tx( + () -> + operatorRepository + .findByControlPlaneRequestId(tuple.controlPlaneRequestId()) + .orElseThrow()); + assertThat(storedAfterDeniedRead.status()) + .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); + assertThat(storedAfterDeniedRead.redemptionRedeemerWorkloadUri()) + .isEqualTo(gameSessionPeer); + assertThat(storedAfterDeniedRead.redemptionOwnerAttemptId()).isEqualTo(ownerAttemptId); + assertThat(storedAfterDeniedRead.redemptionOwnerFence()).isEqualTo(ownerFence); + assertThat(storedAfterDeniedRead.redemptionAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle().toByteArray()); + + assertThat(projection.getControlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + assertThat(projection.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .isEqualTo(tupleBytes); + assertThat(projection.getMutationDigest()).isEqualTo(tuple.mutationDigest()); + assertThat(projection.getAuthorizationReferenceFingerprint()) + .isEqualTo(issuedOperator.getAuthorizationReferenceFingerprint()); + assertThat(projection.getAuthenticatedRedeemerWorkloadIdentity()) + .isEqualTo(gameSessionPeer); + assertThat(projection.getOwnerAttemptId()).isEqualTo(ownerAttemptId.toString()); + assertThat(projection.getOwnerFence()).isEqualTo(ownerFence); + assertThat(projection.getReferenceExpiresAt()).isEqualTo(issuedOperator.getExpiresAt()); + assertThat(projection.getIssuanceOperationId()) + .isEqualTo(redeemed.getIssuanceOperationId()); + assertThat(projection.getIssuanceFence()).isEqualTo(redeemed.getIssuanceFence()); + assertThat(projection.getBundleReference()) + .isEqualTo(issuedOperator.getBundleReference()); + assertThat(projection.getAuthorityEvidenceBundle()) + .isEqualTo(issuedOperator.getAuthorityEvidenceBundle()); + assertThat(exactRetry).isEqualTo(projection); + } + } + } + } + + private AnnotationConfigApplicationContext operatorAuthorizationContext( + AccountControlUiActorService actors, + AccountControlUiIssuanceRepository issuanceOperations, + StartSessionReservationEvidenceClient reservationEvidence, + AccountStartSessionOperatorAuthorizationRepository repository, + OwnerKeySource ownerKeySource, + AccountHostedTermsService hostedTerms, + PlatformTransactionManager transactions, + Path operatorEnvelopeMount) { + var context = new AnnotationConfigApplicationContext(); + context.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance()); + context + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "positive-owner-test-operator-authorization", + Map.of( + "firemud.account.start-session-operator-authorization.enabled", + "true", + "firemud.grpc.workload-namespace", + "control-ui-owner-proof", + "firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention", + "PT2M", + "firemud.account.start-session-operator-authorization.response-envelope.keyring-path", + operatorEnvelopeMount.toAbsolutePath().toString(), + "firemud.account.start-session-operator-authorization.reference-lifetime", + "PT5M", + "firemud.account.start-session-operator-authorization.response-recovery-window", + "PT1M"))); + context.registerBean(AccountControlUiActorService.class, () -> actors); + context.registerBean(AccountControlUiIssuanceRepository.class, () -> issuanceOperations); + context.registerBean(StartSessionReservationEvidenceClient.class, () -> reservationEvidence); + context.registerBean( + AccountStartSessionOperatorAuthorizationRepository.class, () -> repository); + context.registerBean(OwnerKeySource.class, () -> ownerKeySource); + context.registerBean(AccountHostedTermsService.class, () -> hostedTerms); + context.registerBean(PlatformTransactionManager.class, () -> transactions); + context.register(AccountStartSessionOperatorAuthorizationConfiguration.class); + context.refresh(); + return context; + } + + private static DraftAuthorizationFenceBinding originalBinding( + AccountControlUiOwnerSourcesFixture f, + List sources) { + var complete = + DraftCommitBinding.create( + new DraftCommitBinding.TargetProof( + f.tenant, + UUID.randomUUID(), + 1, + "test-game-key", + 2, + "test-game-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "test-only-base", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "test-only-world-input")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "0"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "0", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + sources); + } + + private static Map> verifiedScopedRoles( + Map currentClaims, UUID tenantId) { + Object rawRoles = currentClaims.get("scopedRoles"); + Map> exactRoles = Map.of(tenantId.toString(), List.of("tenantAdmin")); + if (!(rawRoles instanceof Map roles) || !roles.equals(exactRoles)) { + throw new IllegalStateException("Exact current tenant-admin Account role evidence required"); + } + return exactRoles; + } + + private static ReadCurrentClaimEvidenceRequest currentClaimRequest( + StartSessionPreAuthorizationReservationTuple tuple, + ClaimEvidence claim, + long observedClaimFence) { + return ReadCurrentClaimEvidenceRequest.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson(), StandardCharsets.UTF_8)) + .setReservationOwnerId(claim.reservationOwnerId().toString()) + .setReservationClaimFence(claim.reservationClaimFence()) + .setClaimOwnerId(claim.currentClaimOwnerId().toString()) + .setClaimFence(observedClaimFence) + .setPurpose( + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE) + .build(); + } + + private static Path loggingMigrations() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + Path migrations = + current.resolve("services/logging-admin-service/src/main/resources/db/migration"); + if (Files.isDirectory(migrations)) { + return migrations; + } + current = current.getParent(); + } + throw new IllegalStateException("Exact Logging/Admin migration directory is required"); + } + + /** + * Test-only in-process composition supplies the Account URI and a run-owned approved leaf; it + * exercises receiver authorization, not a TLS handshake or mTLS certificate binding. + */ + private static InProcessLoggingTransport inProcessLoggingTransport( + StartSessionReservationEvidenceGrpcService receiver, + String accountPeerUri, + GrpcPeerCertificateEvidence accountLeafEvidence) + throws Exception { + String serverName = InProcessServerBuilder.generateName(); + var peer = GrpcPeerIdentity.parseUri(accountPeerUri).orElseThrow(); + Server server = + InProcessServerBuilder.forName(serverName) + .directExecutor() + .addService( + ServerInterceptors.intercept( + receiver, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + Context peerContext = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .withValue( + GrpcPeerCertificateEvidence.CONTEXT_KEY, accountLeafEvidence); + return Contexts.interceptCall(peerContext, call, headers, next); + } + })) + .build() + .start(); + ManagedChannel receiverChannel = + InProcessChannelBuilder.forName(serverName).directExecutor().build(); + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService(serverName); + CommonGrpcClientProperties testTransport = new CommonGrpcClientProperties(); + testTransport.setPlaintext(true); + GrpcChannelFactory channelFactory = + new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive) { + if (!serverName.equals(target) || !properties.isPlaintext()) { + throw new IllegalArgumentException( + "Only the named in-process test transport is valid"); + } + return InProcessChannelBuilder.forName(serverName).directExecutor().build(); + } + }; + StartSessionReservationEvidenceClient accountClient = + new StartSessionReservationEvidenceClient( + endpoints, testTransport, channelFactory, BlockingGrpcStubCustomizer.noop()); + try { + ReflectionTestUtils.invokeMethod(accountClient, "init"); + return new InProcessLoggingTransport( + server, + receiverChannel, + accountClient, + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(receiverChannel)); + } catch (RuntimeException | Error failure) { + accountClient.close(); + receiverChannel.shutdownNow(); + server.shutdownNow(); + throw failure; + } + } + + private static GrpcPeerCertificateEvidence testAccountLeafEvidence() { + X509Certificate leaf = mock(X509Certificate.class); + try { + when(leaf.getEncoded()) + .thenReturn( + "run-owned Account test leaf certificate".getBytes(StandardCharsets.US_ASCII)); + } catch (CertificateEncodingException exception) { + throw new AssertionError(exception); + } + return GrpcPeerCertificateEvidence.fromCertificate(leaf).orElseThrow(); + } + + private static InProcessAccountTransport inProcessAccountTransport( + StartSessionOperatorAuthorizationGrpcService receiver, String namespace) throws Exception { + return new InProcessAccountTransport( + inProcessAccountEndpoint( + receiver, "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service"), + inProcessAccountEndpoint( + receiver, "spiffe://firemud/ns/" + namespace + "/sa/game-session-service"), + inProcessAccountEndpoint( + receiver, "spiffe://firemud/ns/" + namespace + "/sa/game-design-service")); + } + + private static InProcessAccountEndpoint inProcessAccountEndpoint( + StartSessionOperatorAuthorizationGrpcService receiver, String peerUri) throws Exception { + String serverName = InProcessServerBuilder.generateName(); + var peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Server server = + InProcessServerBuilder.forName(serverName) + .directExecutor() + .addService( + ServerInterceptors.intercept( + receiver, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata headers, + ServerCallHandler next) { + Context peerContext = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + return Contexts.interceptCall(peerContext, call, headers, next); + } + })) + .build() + .start(); + ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); + return new InProcessAccountEndpoint( + server, channel, StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel)); + } + + /** + * Test-only peer-context composition. Each server injects one fixed expected workload identity; + * this deliberately proves receiver authorization only, not transport TLS or mTLS. + */ + private static final class InProcessAccountTransport implements AutoCloseable { + private final InProcessAccountEndpoint logging; + private final InProcessAccountEndpoint gameSession; + private final InProcessAccountEndpoint gameDesign; + + private InProcessAccountTransport( + InProcessAccountEndpoint logging, + InProcessAccountEndpoint gameSession, + InProcessAccountEndpoint gameDesign) { + this.logging = logging; + this.gameSession = gameSession; + this.gameDesign = gameDesign; + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + logging() { + return logging.stub(); + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + gameSession() { + return gameSession.stub(); + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + gameDesign() { + return gameDesign.stub(); + } + + @Override + public void close() { + logging.close(); + gameSession.close(); + gameDesign.close(); + } + } + + private static final class InProcessAccountEndpoint implements AutoCloseable { + private final Server server; + private final ManagedChannel channel; + private final StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub; + + private InProcessAccountEndpoint( + Server server, + ManagedChannel channel, + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub) { + this.server = server; + this.channel = channel; + this.stub = stub; + } + + private StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub + stub() { + return stub; + } + + @Override + public void close() { + channel.shutdownNow(); + server.shutdownNow(); + } + } + + /** + * Test-only in-process composition. Its injected peer context exercises receiver authorization; + * it is deliberately not a TLS or mTLS proof. + */ + private static final class InProcessLoggingTransport implements AutoCloseable { + private final Server server; + private final ManagedChannel receiverChannel; + private final StartSessionReservationEvidenceClient accountClient; + private final StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + receiverStub; + + private InProcessLoggingTransport( + Server server, + ManagedChannel receiverChannel, + StartSessionReservationEvidenceClient accountClient, + StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + receiverStub) { + this.server = server; + this.receiverChannel = receiverChannel; + this.accountClient = accountClient; + this.receiverStub = receiverStub; + } + + private StartSessionReservationEvidenceClient accountClient() { + return accountClient; + } + + private StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + receiverStub() { + return receiverStub; + } + + @Override + public void close() throws Exception { + accountClient.close(); + receiverChannel.shutdownNow(); + server.shutdownNow(); + } + } + + private static RedisClient redisClient(boolean application) { + var uri = RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)); + if (application) uri.withAuthentication("account_coord_app", PASSWORD); + var result = RedisClient.create(uri.build()); + result.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return result; + } + + private static RedisScriptCatalog testCatalog() { + return RedisScriptCatalog.fromContributions( + List.of( + new RedisScriptContribution() { + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + return List.of(AccountControlUiRegistryContract.descriptor()); + } + })); + } + + private void custody(String purpose, String id, int value) throws Exception { + byte[] key = new byte[32]; + java.util.Arrays.fill(key, (byte) value); + var directory = Files.createDirectories(temporary.resolve("custody").resolve(purpose)); + Files.writeString( + directory.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive " + + id + + " " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n"); + } + + private static void assertOrder( + net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository + .FenceSnapshot + observed, + DraftAuthorizationFenceBinding binding) { + assertThat(observed.ordering().name()).isEqualTo("COMMIT_ORDER"); + assertThat(observed.binding()).isEqualTo(binding.canonicalBytes()); + assertThat(observed.orderedAt()).isNotNull(); + } + + private static final class RedisFixture implements AutoCloseable { + final RedisClient admin = redisClient(false), account = redisClient(true); + + @Override + public void close() { + account.shutdown(); + admin.shutdown(); + } + } + + private static void awaitLocalAndReplicaAof( + io.lettuce.core.api.sync.RedisCommands commands) throws InterruptedException { + byte[] probeKey = + ("test-only:positive-account-coordination-aof-probe:" + UUID.randomUUID()) + .getBytes(StandardCharsets.US_ASCII); + commands.set(probeKey, "test-only-replication-probe".getBytes(StandardCharsets.US_ASCII)); + long deadline = System.nanoTime() + java.time.Duration.ofSeconds(30).toNanos(); + while (System.nanoTime() < deadline) { + List counts = + commands.dispatch( + TestWaitAof.INSTANCE, + new io.lettuce.core.output.ArrayOutput<>(ByteArrayCodec.INSTANCE), + new io.lettuce.core.protocol.CommandArgs<>(ByteArrayCodec.INSTANCE) + .add(1) + .add(1) + .add(500)); + if (counts != null + && counts.size() == 2 + && counts.get(0) instanceof Long local + && counts.get(1) instanceof Long replicas + && local >= 1 + && replicas >= 1) { + return; + } + Thread.sleep(50); + } + throw new IllegalStateException("Test Coordination Redis replica did not acknowledge AOF"); + } + + private enum TestWaitAof implements io.lettuce.core.protocol.ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + private enum TestAclCommand implements io.lettuce.core.protocol.ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "ACL".getBytes(StandardCharsets.US_ASCII); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java new file mode 100644 index 0000000000..381e07787e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java @@ -0,0 +1,389 @@ +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.mock; + +import de.mkammerer.argon2.Argon2Factory; +import java.time.LocalDateTime; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.mapper.AccountMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +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.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.service.AccountPasswordResetDraftSourceChangeRepository; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.mapstruct.factory.Mappers; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Actual primary authentication, persisted canonical identity and source mapping, OTP repositories, + * and PostgreSQL transactions/locks. Unused required owner collaborators are unstubbed mocks with + * no positive authority behavior; unrelated optional collaborators remain absent. Secrets and + * Accounts are test-only fixtures; this is not creator-source, signer, protected caller, original + * Draft or runtime issuance proof. + */ +@Testcontainers(disabledWithoutDocker = true) +class AccountControlUiPrimaryAuthenticationPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static final String PASSWORD = "test-only-primary-password"; + private static final String OTP = "test-only-email-otp"; + + @Test + void passwordAuthenticatesPersistedCanonicalUuidAndWrongSecretDoesNotMutate() { + Context c = context(); + Account account = c.account("PASSWORD"); + String before = c.accountBytes(account.getAccountUuid()); + UUID authenticated = + c.tx( + () -> + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD) + .accountId()); + assertThat(authenticated).isEqualTo(account.getAccountUuid()); + assertThat(account.getAccountUuidSourceNumericId()).isEqualTo(account.getId()); + assertThat(c.accountBytes(account.getAccountUuid())).isEqualTo(before); + assertThatThrownBy( + () -> + c.tx( + () -> + c.primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "wrong-secret"))) + .isInstanceOf(AuthenticationException.class); + assertThat(c.accountBytes(account.getAccountUuid())).isEqualTo(before); + } + + @Test + void freshAccountCannotBeCreatedInSecurityLockedStateAndLeavesNoRows() { + Context c = context(); + Account lockedAccount = c.accountCandidate("PASSWORD", AccountLifecycleState.SECURITY_LOCKED); + assertThatThrownBy( + () -> + c.tx( + () -> { + c.accounts.save(lockedAccount); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Fresh Accounts must be created in the ACTIVE lifecycle state"); + + UUID accountUuid = lockedAccount.getAccountUuid(); + assertThat(accountUuid).isNull(); + assertThat(c.accountRowCount()).isZero(); + assertThat(c.accountSourceRowCount()).isZero(); + assertThat(c.accountGenerationRowCount()).isZero(); + assertThat(c.restrictionBirthRowCount()).isZero(); + } + + @Test + void exactOtpConsumptionParticipatesInOwnerRollbackAndCannotBeReplayedAfterCommit() { + Context c = context(); + Account account = c.account("EMAIL_OTP"); + AccountEmailLoginChallenge original = c.challenge(account); + assertThatThrownBy( + () -> + c.tx( + () -> + c.primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "wrong-otp"))) + .isInstanceOf(AuthenticationException.class); + assertThat(c.challenges.findByAccountId(account.getId())).contains(original); + c.transaction.executeWithoutResult( + status -> { + assertThat( + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId()) + .isEqualTo(account.getAccountUuid()); + assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + status.setRollbackOnly(); + }); + assertThat(c.challenges.findByAccountId(account.getId())).contains(original); + assertThat( + c.tx( + () -> + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId())) + .isEqualTo(account.getAccountUuid()); + assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + assertThatThrownBy( + () -> + c.tx(() -> c.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), OTP))) + .isInstanceOf(AuthenticationException.class); + assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + } + + @Test + void concurrentOtpAttemptsSerializeOnActualPostgresOwnerLockAndOnlyOneAuthenticates() + throws Exception { + Context c = context(); + Account account = c.account("EMAIL_OTP"); + c.challenge(account); + var firstAuthenticated = new CountDownLatch(1); + var secondEntered = new CountDownLatch(1); + var releaseFirst = new CountDownLatch(1); + var firstPid = new AtomicInteger(); + var secondPid = new AtomicInteger(); + var executor = Executors.newFixedThreadPool(2); + try { + var first = + executor.submit( + () -> + c.tx( + () -> { + firstPid.set(c.pid()); + UUID actor = + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId(); + firstAuthenticated.countDown(); + awaitLatch(releaseFirst); + return actor; + })); + awaitLatch(firstAuthenticated); + var second = + executor.submit( + () -> + c.tx( + () -> { + secondPid.set(c.pid()); + secondEntered.countDown(); + return c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId(); + })); + awaitLatch(secondEntered); + awaitBlocked(c, secondPid.get(), firstPid.get()); + assertThat(first.isDone()).isFalse(); + assertThat(second.isDone()).isFalse(); + releaseFirst.countDown(); + assertThat(first.get(10, TimeUnit.SECONDS)).isEqualTo(account.getAccountUuid()); + assertThatThrownBy(() -> second.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(AuthenticationException.class); + assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + } finally { + releaseFirst.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + + private static void awaitLatch(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Expected primary-auth transaction boundary"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted primary-auth transaction boundary"); + } + } + + private static void awaitBlocked(Context c, int waitingPid, int blockerPid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + var observed = + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT ? = ANY(pg_blocking_pids(?)) AS blocked", blockerPid, waitingPid), + "Exact PostgreSQL blocking identity readback required"); + if (Boolean.TRUE.equals(observed.get("blocked", Boolean.class))) { + return; + } + Thread.onSpinWait(); + } + throw new IllegalStateException( + "Second OTP attempt did not block on first primary-auth transaction"); + } + + private static Context context() { + String schema = "control_ui_primary_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + var manager = new DataSourceTransactionManager(source); + var transaction = new TransactionTemplate(manager); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + var accounts = new AccountRepository(dsl, sourceEvidence); + var challenges = new AccountEmailLoginChallengeRepository(dsl); + var primary = + new AccountServiceImpl( + accounts, + generations, + sourceEvidence, + outbox, + mock(AccountPasswordResetOperationRepository.class), + mock(AccountLogoutAllOperationRepository.class), + mock(AccountSecurityStateOperationRepository.class), + mock(AccountPasswordResetDraftSourceChangeRepository.class), + mock(AccountAuditOutboxRepository.class), + mock(AccountConnectScopeRepository.class), + mock(AccountJoinOperationRepository.class), + challenges, + null, // Realm grants are not used by primary authentication. + null, // Tenant memberships are not used by primary authentication. + Mappers.getMapper(AccountMapper.class), + null, // Profiles are not used by primary authentication. + null, // Profile mapper is not used by primary authentication. + null, // Payment transactions are not used by primary authentication. + null, // Subscriptions are not used by primary authentication. + null, // External identities are not used by primary authentication. + null, // Password reset tokens are not used by primary authentication. + null, // Email verification tokens are not used by primary authentication. + null, // Notifications are not used by primary authentication. + null, // Email delivery is not used by primary authentication. + null, // Mail properties are not used by primary authentication. + null, // Token properties are not used by primary authentication. + null, // JWT auth properties are not used by primary authentication. + null, // Game Session client is not used by primary authentication. + null, // Entity Management client is not used by primary authentication. + null, // JWT utility is not used by primary authentication. + null, // Session service is not used by primary authentication. + manager); + return new Context(dsl, accounts, challenges, primary, transaction); + } + + private record Context( + DSLContext dsl, + AccountRepository accounts, + AccountEmailLoginChallengeRepository challenges, + AccountServiceImpl primary, + TransactionTemplate transaction) { + T tx(Supplier action) { + return transaction.execute(ignored -> action.get()); + } + + Account account(String modes) { + return account(modes, AccountLifecycleState.ACTIVE); + } + + Account account(String modes, AccountLifecycleState lifecycleState) { + Account account = accountCandidate(modes, lifecycleState); + return tx(() -> accounts.save(account)); + } + + Account accountCandidate(String modes, AccountLifecycleState lifecycleState) { + Account account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername("primary-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash(hash(PASSWORD)); + account.setLoginAuthModes(modes); + account.setLifecycleState(lifecycleState); + return account; + } + + long accountRowCount() { + return count("SELECT COUNT(*) FROM accounts"); + } + + long accountSourceRowCount() { + return count("SELECT COUNT(*) FROM account_authority_source_records"); + } + + long accountGenerationRowCount() { + return count( + "SELECT COUNT(*) FROM account_authority_generations " + "WHERE scope_kind = 'ACCOUNT'"); + } + + long restrictionBirthRowCount() { + return count("SELECT COUNT(*) FROM account_platform_restriction_births"); + } + + private long count(String query) { + return Objects.requireNonNull(dsl.fetchOne(query)).get(0, Long.class); + } + + AccountEmailLoginChallenge challenge(Account account) { + return tx( + () -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); + } + + int pid() { + return Objects.requireNonNull( + dsl.fetchOne("SELECT pg_backend_pid() AS pid"), + "Exact owner transaction backend required") + .get("pid", Integer.class); + } + + String accountBytes(UUID account) { + return Objects.requireNonNull( + dsl.fetchOne( + "SELECT to_jsonb(a)::TEXT AS exact FROM accounts a WHERE account_uuid = ?", + account), + "Persisted canonical Account readback required") + .get("exact", String.class); + } + } + + private static String hash(String secret) { + char[] chars = secret.toCharArray(); + var argon = Argon2Factory.create(); + try { + return argon.hash(2, 4096, 1, chars); + } finally { + argon.wipeArray(chars); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryRedisIntegrationTest.java new file mode 100644 index 0000000000..8ec0039acb --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryRedisIntegrationTest.java @@ -0,0 +1,518 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.lettuce.core.AclSetuserArgs; +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.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.output.ArrayOutput; +import io.lettuce.core.output.StatusOutput; +import io.lettuce.core.protocol.CommandArgs; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import io.lettuce.core.protocol.ProtocolKeyword; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Physical Coordination Redis proof for Account's pending token-registry CAS only. Inputs and any + * directly seeded active read fixture are synthetic and non-authorizing; this does not prove + * Account issuance, committed signer provenance, or the Account-owned activation transition. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountControlUiRegistryRedisIntegrationTest { + private static final int REDIS_PORT = 6379; + private static final String ACCOUNT_USER = "account_coord_app"; + private static final String ACCOUNT_PASSWORD = UUID.randomUUID().toString().replace("-", ""); + private static final String WRONG_USER = "account_coord_wrong"; + private static final String WRONG_PASSWORD = UUID.randomUUID().toString().replace("-", ""); + private static final Network REDIS_NETWORK = Network.newNetwork(); + + @Container + static final GenericContainer primary = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(REDIS_NETWORK) + .withNetworkAliases("control-ui-coordination-primary") + .withExposedPorts(REDIS_PORT) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(REDIS_NETWORK) + .dependsOn(primary) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "control-ui-coordination-primary", + Integer.toString(REDIS_PORT)); + + private static final RedisScriptCatalog TEST_CATALOG = testCatalog(); + private static RedisClient adminClient; + + @BeforeAll + static void configureIsolatedRedis() throws InterruptedException { + adminClient = client(null, null); + try (var connection = adminClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = connection.sync(); + configureApplicationUser(commands, ACCOUNT_USER, ACCOUNT_PASSWORD, true); + configureApplicationUser(commands, WRONG_USER, WRONG_PASSWORD, false); + awaitLocalAndReplicaAof(commands); + } + } + + @AfterAll + static void stopClients() { + if (adminClient != null) { + adminClient.shutdown(); + } + } + + @Test + void pendingRegistrationRequiresRealAofAckExactRetryAndImmutableCas() { + String tokenHash = tokenHash(); + long expiryMillis = (Instant.now().getEpochSecond() + 300) * 1000L; + byte[] pending = syntheticRecord(tokenHash, "pending", expiryMillis / 1000, "request-a"); + byte[] key = key(tokenHash); + + try (var pinned = new PinnedAccountConnection(ACCOUNT_USER, ACCOUNT_PASSWORD)) { + AccountControlUiCoordination underDurabilityThreshold = + coordination(pinned, new AcknowledgementRequirements(1, 2, 1000)); + assertThatThrownBy( + () -> underDurabilityThreshold.registerPending(tokenHash, pending, expiryMillis)) + .isInstanceOf(IllegalStateException.class); + // The Redis write occurred, but the under-threshold WAITAOF result created no owner receipt. + assertThat(adminGet(key)).isEqualTo(pending); + + AccountControlUiCoordination owner = + coordination(pinned, new AcknowledgementRequirements(1, 1, 1000)); + var created = owner.registerPending(tokenHash, pending, expiryMillis); + assertThat(created.tokenHash).isEqualTo(tokenHash); + assertThat(created.recordDigest).isEqualTo(AccountControlUiIssuanceRepository.hash(pending)); + assertThat(created.expiryMillis).isEqualTo(expiryMillis); + assertThat(created.localAof).isEqualTo(1); + assertThat(created.replicas).isEqualTo(1); + assertThat(adminGet(key)).isEqualTo(pending); + + // Exact retry reasserts the bytes, obtains a fresh same-connection WAITAOF, and reads back. + var retried = owner.registerPending(tokenHash, pending, expiryMillis); + assertThat(retried.tokenHash).isEqualTo(created.tokenHash); + assertThat(retried.recordDigest).isEqualTo(created.recordDigest); + assertThat(retried.expiryMillis).isEqualTo(created.expiryMillis); + assertThat(retried.localAof).isEqualTo(1); + assertThat(retried.replicas).isEqualTo(1); + + byte[] changedBinding = + syntheticRecord(tokenHash, "pending", expiryMillis / 1000, "request-b"); + assertThatThrownBy(() -> owner.registerPending(tokenHash, changedBinding, expiryMillis)) + .isInstanceOf(IllegalStateException.class); + assertThat(adminGet(key)).isEqualTo(pending); + + // PENDING is deliberately not accepted as an active actor registry record. + assertThatThrownBy(() -> owner.readActive(tokenHash)) + .isInstanceOf(IllegalStateException.class); + assertThat(pinned.openedConnections()).isGreaterThan(0); + } + } + + @Test + void luaRejectsMalformedExpiryTypesWithoutRedisErrorsOrKeyMutation() throws Exception { + var descriptor = AccountControlUiRegistryContract.descriptor(); + byte[] source; + try (var stream = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(stream).isNotNull(); + source = stream.readAllBytes(); + } + assertThat(AccountControlUiCoordination.digest("SHA-256", source)) + .isEqualTo(descriptor.sha256()); + + try (var connection = adminClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = connection.sync(); + String sha = commands.scriptLoad(source); + assertThat(sha).isEqualTo(AccountControlUiCoordination.digest("SHA-1", source)); + + long expiryMillis = (Instant.now().getEpochSecond() + 300) * 1000L; + long expiryEpochSecond = expiryMillis / 1000L; + for (String malformedExpiry : List.of("missing", "string", "object", "null")) { + String tokenHash = tokenHash(); + byte[] redisKey = key(tokenHash); + byte[] replacement = candidateWithExpiry(tokenHash, expiryEpochSecond, malformedExpiry); + Long result = + commands.evalsha( + sha, + io.lettuce.core.ScriptOutputType.INTEGER, + new byte[][] {redisKey}, + bytes(""), + replacement, + bytes(Long.toString(expiryMillis))); + + assertThat(result).as("Lua result for %s exp", malformedExpiry).isEqualTo(-1L); + assertThat(commands.get(redisKey)).as("key for %s exp", malformedExpiry).isNull(); + assertThat(commands.pexpiretime(redisKey)) + .as("physical expiry for %s exp", malformedExpiry) + .isEqualTo(-2L); + } + + String validTokenHash = tokenHash(); + byte[] validKey = key(validTokenHash); + byte[] validReplacement = candidateWithExpiry(validTokenHash, expiryEpochSecond, "number"); + Long validResult = + commands.evalsha( + sha, + io.lettuce.core.ScriptOutputType.INTEGER, + new byte[][] {validKey}, + bytes(""), + validReplacement, + bytes(Long.toString(expiryMillis))); + assertThat(validResult).isEqualTo(1L); + assertThat(commands.get(validKey)).isEqualTo(validReplacement); + assertThat(commands.pexpiretime(validKey)).isEqualTo(expiryMillis); + } + } + + @Test + void wrongAuthenticatedPrincipalCannotReadEvenASyntheticActiveProjection() { + String tokenHash = tokenHash(); + long expiryMillis = (Instant.now().getEpochSecond() + 300) * 1000L; + byte[] active = syntheticRecord(tokenHash, "active", expiryMillis / 1000, "read-only-fixture"); + adminSetWithExpiry(key(tokenHash), active, expiryMillis); + + try (var wrongPrincipal = new PinnedAccountConnection(WRONG_USER, WRONG_PASSWORD)) { + // Prove this authenticated test-only principal can reach the same synthetic key and + // physical-expiry commands before the production identity guard rejects it. + try (var connection = wrongPrincipal.openPinnedConnection()) { + RedisCommands commands = connection.sync(); + assertThat(commands.aclWhoami()).isEqualTo(WRONG_USER); + assertThat(commands.get(key(tokenHash))).isEqualTo(active); + assertThat(commands.pexpiretime(key(tokenHash))).isEqualTo(expiryMillis); + } + + AccountControlUiCoordination client = + coordination(wrongPrincipal, new AcknowledgementRequirements(1, 1, 1000)); + assertThatThrownBy(() -> client.readActive(tokenHash)) + .isInstanceOf(IllegalStateException.class); + assertThat(wrongPrincipal.openedConnections()).isEqualTo(2); + } + } + + @Test + void activeReadRequiresExactPhysicalExpiryAndExpiredProjectionDenies() { + String tokenHash = tokenHash(); + long expiryMillis = (Instant.now().getEpochSecond() + 300) * 1000L; + byte[] active = syntheticRecord(tokenHash, "active", expiryMillis / 1000, "read-only-fixture"); + byte[] key = key(tokenHash); + adminSetWithExpiry(key, active, expiryMillis); + + try (var pinned = new PinnedAccountConnection(ACCOUNT_USER, ACCOUNT_PASSWORD)) { + AccountControlUiCoordination client = + coordination(pinned, new AcknowledgementRequirements(1, 1, 1000)); + // Direct seeding exists only to exercise the actual read predicate; it is not activation. + assertThat(client.readActive(tokenHash)).isEqualTo(active); + + adminSetExpiry(key, expiryMillis - 1000L); + assertThatThrownBy(() -> client.readActive(tokenHash)) + .isInstanceOf(IllegalStateException.class); + + String expiredHash = tokenHash(); + long expiredMillis = (Instant.now().getEpochSecond() - 30) * 1000L; + adminSetWithExpiry( + key(expiredHash), + syntheticRecord(expiredHash, "active", expiredMillis / 1000, "expired-fixture"), + expiredMillis); + assertThatThrownBy(() -> client.readActive(expiredHash)) + .isInstanceOf(IllegalStateException.class); + } + } + + private static AccountControlUiCoordination coordination( + AccountCoordinationPinnedConnectionProvider provider, + AcknowledgementRequirements acknowledgements) { + return new AccountControlUiCoordination(provider, acknowledgements, TEST_CATALOG); + } + + private static RedisScriptCatalog testCatalog() { + // The isolated fixture contributes the production descriptor as-is; it does not register it + // in Account's runtime ServiceLoader catalog or claim deployment/ACL registration. + RedisScriptContribution contribution = + new RedisScriptContribution() { + @Override + public String ownerId() { + return "account-service"; + } + + @Override + public Collection descriptors() { + return List.of(AccountControlUiRegistryContract.descriptor()); + } + }; + RedisScriptCatalog catalog = RedisScriptCatalog.fromContributions(List.of(contribution)); + if (!AccountControlUiRegistryContract.descriptor() + .equals(catalog.require(AccountControlUiRegistryContract.SCRIPT_ID))) { + throw new IllegalStateException("Exact Account Control UI registry descriptor required"); + } + return catalog; + } + + private static void configureApplicationUser( + RedisCommands commands, String username, String password, boolean registry) { + if (registry) { + commands.aclSetuser( + username, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:auth:token:*") + // Narrow transport permissions required by this test's authenticated Lettuce client. + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.GET) + .addCommand(CommandType.SET) + .addCommand(CommandType.PEXPIRETIME) + .addCommand(CommandType.TIME)); + // WAITAOF is newer than this Lettuce version's CommandType catalog, so use its supported + // low-level command dispatch to add only that exact top-level ACL command. + commands.dispatch( + TestAclSetuser.INSTANCE, + new StatusOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE).add("SETUSER").add(username).add("+waitaof")); + } else { + // The isolated Redis contains only synthetic test records. The wrong principal receives + // read/physical-expiry access to that key family, but no registry-write or script rights. + commands.aclSetuser( + username, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:auth:token:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.GET) + .addCommand(CommandType.PEXPIRETIME)); + } + } + + private static void awaitLocalAndReplicaAof(RedisCommands commands) + throws InterruptedException { + byte[] probeKey = bytes("test-only:account-coordination-aof-probe:" + UUID.randomUUID()); + commands.set(probeKey, bytes("test-only-replication-probe")); + long deadline = System.nanoTime() + java.time.Duration.ofSeconds(30).toNanos(); + while (System.nanoTime() < deadline) { + List counts = + commands.dispatch( + TestWaitAof.INSTANCE, + new ArrayOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE).add(1).add(1).add(500)); + if (hasAofCounts(counts, 1, 1)) { + return; + } + Thread.sleep(50); + } + throw new IllegalStateException("Test Coordination Redis replica did not acknowledge AOF"); + } + + private static boolean hasAofCounts(List counts, long local, long replicas) { + return counts != null + && counts.size() == 2 + && counts.get(0) instanceof Long observedLocal + && counts.get(1) instanceof Long observedReplicas + && observedLocal >= local + && observedReplicas >= replicas; + } + + private static byte[] adminGet(byte[] key) { + try (var connection = adminClient.connect(ByteArrayCodec.INSTANCE)) { + return connection.sync().get(key); + } + } + + private static void adminSetWithExpiry(byte[] key, byte[] value, long expiryMillis) { + try (var connection = adminClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = connection.sync(); + commands.set(key, value); + commands.pexpireat(key, expiryMillis); + } + } + + private static void adminSetExpiry(byte[] key, long expiryMillis) { + try (var connection = adminClient.connect(ByteArrayCodec.INSTANCE)) { + connection.sync().pexpireat(key, expiryMillis); + } + } + + private static RedisClient client(String username, String password) { + RedisURI.Builder uri = + RedisURI.Builder.redis(primary.getHost(), primary.getMappedPort(REDIS_PORT)); + if (username != null) { + uri.withAuthentication(username, password); + } + RedisClient client = RedisClient.create(uri.build()); + client.setOptions(ClientOptions.builder().autoReconnect(false).build()); + return client; + } + + private static byte[] syntheticRecord( + String tokenHash, String state, long expiryEpochSecond, String testOnlyBinding) { + return AccountControlUiAuthority.canonical( + registryFields(tokenHash, state, expiryEpochSecond, testOnlyBinding)); + } + + private static byte[] candidateWithExpiry( + String tokenHash, long expiryEpochSecond, String expiryShape) { + Map fields = registryFields(tokenHash, "pending", expiryEpochSecond, "lua"); + switch (expiryShape) { + case "missing" -> fields.remove("exp"); + case "string" -> fields.put("exp", Long.toString(expiryEpochSecond)); + case "object" -> fields.put("exp", Map.of("seconds", expiryEpochSecond)); + case "null" -> fields.put("exp", null); + case "number" -> { + // Keep the canonical numeric expiry created by registryFields. + } + default -> throw new IllegalArgumentException("Unknown test expiry shape"); + } + return AccountControlUiAuthority.canonical(fields); + } + + private static Map registryFields( + String tokenHash, String state, long expiryEpochSecond, String testOnlyBinding) { + Map fields = + new HashMap<>( + Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("registryVersion", "active".equals(state) ? 2 : 1), + Map.entry("tokenHash", tokenHash), + Map.entry("kid", "key-1"), + Map.entry("signerGeneration", "1"), + Map.entry("issuer", "firemud-account-service"), + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("accountId", "10000000-0000-4000-8000-000000000001"), + Map.entry("jti", "30000000-0000-4000-8000-000000000003"), + Map.entry("iat", expiryEpochSecond - 300), + Map.entry("nbf", expiryEpochSecond - 300), + Map.entry("exp", expiryEpochSecond), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", Map.of("accountAuthorityGeneration", 1)), + Map.entry("membershipVersion", Map.of("20000000-0000-4000-8000-000000000002", 1)), + Map.entry("issuanceFence", 1), + Map.entry("operationId", "40000000-0000-4000-8000-000000000004"), + Map.entry("requestId", UUID.nameUUIDFromBytes(bytes(testOnlyBinding)).toString()), + Map.entry( + "requestDigest", + AccountControlUiIssuanceRepository.hash(bytes(testOnlyBinding))), + Map.entry("registryCleanupDeadlineEpochMillis", expiryEpochSecond * 1000L), + Map.entry("state", state), + Map.entry( + "authoritySourceVersions", + Map.of("ACCOUNT:10000000-0000-4000-8000-000000000001", 1)), + Map.entry("authEvidenceBundle", Map.of("bundleVersion", "1")), + Map.entry("originalSignerReceiptDigest", "c".repeat(64)))); + return fields; + } + + private static String tokenHash() { + return AccountControlUiIssuanceRepository.hash( + bytes("test-only-control-ui-registry/" + UUID.randomUUID())); + } + + private static byte[] key(String tokenHash) { + return bytes("session:auth:token:" + tokenHash); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static final class PinnedAccountConnection + implements AccountCoordinationPinnedConnectionProvider, AutoCloseable { + private final RedisClient client; + private final AtomicInteger openedConnections = new AtomicInteger(); + + PinnedAccountConnection(String username, String password) { + client = client(username, password); + } + + @Override + public StatefulRedisConnection openPinnedConnection() { + openedConnections.incrementAndGet(); + return client.connect(ByteArrayCodec.INSTANCE); + } + + int openedConnections() { + return openedConnections.get(); + } + + @Override + public void close() { + client.shutdown(); + } + } + + private enum TestWaitAof implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "WAITAOF".getBytes(StandardCharsets.US_ASCII); + } + } + + private enum TestAclSetuser implements ProtocolKeyword { + INSTANCE; + + @Override + public byte[] getBytes() { + return "ACL".getBytes(StandardCharsets.US_ASCII); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java new file mode 100644 index 0000000000..fbdffb7bb8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java @@ -0,0 +1,478 @@ +package net.firedevops.firemud.accountservice.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.stub.StreamObserver; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; +import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class StartSessionReservationEvidenceClientTest { + private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; + private static final String REQUEST_ID = "start-session-βeta"; + private static final UUID ACTOR_ID = UUID.fromString("1ea6eb2c-e211-4f4f-a812-14909b9a72b8"); + private static final UUID TENANT_ID = UUID.fromString("5212125e-7d89-4c51-b3a0-bef10e04ccda"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("b2a1a560-5e62-4f61-98bf-dae49ba37a38"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("44997fae-a4c4-45de-8d4f-5e75ad233f0f"); + private static final UUID RECOVERY_OWNER_ID = + UUID.fromString("c8190808-e325-4d8a-9702-fbf5a53d436d"); + private static final Clock CLOCK = + Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC); + private static final String LOGGING_ADMIN_TARGET = "logging-admin.internal:6565"; + + @Test + void repeatedInProcessReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + List requests = new ArrayList<>(); + try (InProcessFixture fixture = + inProcessFixture( + request -> { + requests.add(request); + assertThat(io.grpc.Context.current().getDeadline()).isNotNull(); + return validResponse(request, tuple.mutationDigest()); + })) { + StartSessionReservationEvidenceClient client = client(fixture.stub()); + + ReadCurrentClaimEvidenceResponse issueFirst = + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE); + ReadCurrentClaimEvidenceResponse issueRetry = + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE); + ReadCurrentClaimEvidenceResponse recoveryFirst = + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RECOVERY_OWNER_ID, + 3L, + StartSessionReservationEvidenceClient.Purpose.RECOVER); + ReadCurrentClaimEvidenceResponse recoveryRetry = + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RECOVERY_OWNER_ID, + 3L, + StartSessionReservationEvidenceClient.Purpose.RECOVER); + + assertThat(issueFirst).isEqualTo(issueRetry); + assertThat(recoveryFirst).isEqualTo(recoveryRetry); + assertThat(requests).hasSize(4); + assertThat(requests) + .allSatisfy( + request -> { + assertThat(request.getControlPlaneRequestId()).isEqualTo(REQUEST_ID); + assertThat(request.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(request.getReservationOwnerId()) + .isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(request.getReservationClaimFence()).isEqualTo(1L); + }); + assertThat(requests.get(0).getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE); + assertThat(requests.get(1)).isEqualTo(requests.get(0)); + assertThat(requests.get(2).getClaimOwnerId()).isEqualTo(RECOVERY_OWNER_ID.toString()); + assertThat(requests.get(2).getClaimFence()).isEqualTo(3L); + assertThat(requests.get(2).getPurpose()) + .isEqualTo( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER); + assertThat(requests.get(3)).isEqualTo(requests.get(2)); + } + } + + @Test + void rejectsEveryResponseIdentityFieldUnknownFieldsAndStaleTimes() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + AtomicReference response = new AtomicReference<>(); + try (InProcessFixture fixture = inProcessFixture(request -> response.get())) { + StartSessionReservationEvidenceClient client = client(fixture.stub()); + ReadCurrentClaimEvidenceResponse valid = + validResponse( + request(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE), + tuple.mutationDigest()); + List invalid = + List.of( + valid.toBuilder().setControlPlaneRequestId(UUID.randomUUID().toString()).build(), + valid.toBuilder() + .setPreAuthorizationTupleJson(ByteString.copyFromUtf8("different tuple")) + .build(), + valid.toBuilder().setMutationDigest("sha256:" + "0".repeat(64)).build(), + valid.toBuilder().setReservationOwnerId(UUID.randomUUID().toString()).build(), + valid.toBuilder().setReservationClaimFence(2L).build(), + valid.toBuilder().setClaimOwnerId(UUID.randomUUID().toString()).build(), + valid.toBuilder().setClaimFence(2L).build(), + valid.toBuilder() + .setPurpose( + StartSessionReservationEvidencePurpose + .START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER) + .build(), + valid.toBuilder().setObservedAtEpochMillis(0L).build(), + valid.toBuilder().setObservedAtEpochMillis(NOW_EPOCH_MILLIS + 1L).build(), + valid.toBuilder() + .setClaimExpiresAtEpochMillis(valid.getObservedAtEpochMillis()) + .build(), + valid.toBuilder().setClaimExpiresAtEpochMillis(NOW_EPOCH_MILLIS).build(), + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build()); + + for (ReadCurrentClaimEvidenceResponse invalidResponse : invalid) { + response.set(invalidResponse); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("stale or mismatched"); + } + } + } + + @Test + void invalidInputIsRejectedBeforeAnyRpc() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + AtomicInteger calls = new AtomicInteger(); + try (InProcessFixture fixture = + inProcessFixture( + request -> { + calls.incrementAndGet(); + return validResponse(request, tuple.mutationDigest()); + })) { + StartSessionReservationEvidenceClient client = client(fixture.stub()); + + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + null, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 0L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RECOVERY_OWNER_ID, + 3L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.RECOVER)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(calls).hasValue(0); + } + } + + @Test + void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence() + throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + AtomicReference status = new AtomicReference<>(Status.UNAVAILABLE); + try (InProcessFixture fixture = + inProcessFixture( + request -> { + throw status.get().asRuntimeException(); + })) { + StartSessionReservationEvidenceClient client = client(fixture.stub()); + + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE); + + status.set(Status.FAILED_PRECONDITION); + assertThatThrownBy( + () -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + } + } + + @Test + void usesConfiguredLoggingEndpointTlsChannelAndStubCustomizer(@TempDir Path directory) + throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService(LOGGING_ADMIN_TARGET); + CommonGrpcClientProperties tls = tlsProperties(directory); + GrpcChannelFactory channelFactory = spy(new GrpcChannelFactory()); + AtomicInteger customizerCalls = new AtomicInteger(); + BlockingGrpcStubCustomizer customizer = + new BlockingGrpcStubCustomizer() { + @Override + public > T customize(T stub) { + customizerCalls.incrementAndGet(); + return stub; + } + }; + StartSessionReservationEvidenceClient client = + new StartSessionReservationEvidenceClient( + endpoints, tls, channelFactory, customizer, CLOCK); + + try { + client.init(); + + verify(channelFactory) + .buildChannel( + eq(LOGGING_ADMIN_TARGET), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); + assertThat(customizerCalls).hasValue(1); + } finally { + client.close(); + } + } + + private static StartSessionReservationEvidenceClient client( + StartSessionReservationEvidenceServiceGrpc.StartSessionReservationEvidenceServiceBlockingStub + stub) + throws Exception { + StartSessionReservationClientTestAccess client = newClient(); + client.installStub(stub); + return client.client(); + } + + private static StartSessionReservationClientTestAccess newClient() { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setPlaintext(true); + StartSessionReservationEvidenceClient client = + new StartSessionReservationEvidenceClient( + endpoints, + tls, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + CLOCK); + return new StartSessionReservationClientTestAccess(client); + } + + private static InProcessFixture inProcessFixture(EvidenceHandler handler) throws Exception { + String serverName = InProcessServerBuilder.generateName(); + Server server = + InProcessServerBuilder.forName(serverName) + .directExecutor() + .addService( + new StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceImplBase() { + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver responseObserver) { + try { + responseObserver.onNext(handler.read(request)); + responseObserver.onCompleted(); + } catch (StatusRuntimeException exception) { + responseObserver.onError(exception); + } + } + }) + .build() + .start(); + ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); + return new InProcessFixture(server, channel); + } + + private static ReadCurrentClaimEvidenceRequest request( + StartSessionPreAuthorizationReservationTuple tuple, + StartSessionReservationEvidenceClient.Purpose purpose) { + return ReadCurrentClaimEvidenceRequest.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(1L) + .setClaimOwnerId( + purpose == StartSessionReservationEvidenceClient.Purpose.ISSUE + ? RESERVATION_OWNER_ID.toString() + : RECOVERY_OWNER_ID.toString()) + .setClaimFence(purpose == StartSessionReservationEvidenceClient.Purpose.ISSUE ? 1L : 3L) + .setPurpose(toWirePurpose(purpose)) + .build(); + } + + private static ReadCurrentClaimEvidenceResponse validResponse( + ReadCurrentClaimEvidenceRequest request, String mutationDigest) { + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(request.getControlPlaneRequestId()) + .setPreAuthorizationTupleJson(request.getPreAuthorizationTupleJson()) + .setMutationDigest(mutationDigest) + .setReservationOwnerId(request.getReservationOwnerId()) + .setReservationClaimFence(request.getReservationClaimFence()) + .setClaimOwnerId(request.getClaimOwnerId()) + .setClaimFence(request.getClaimFence()) + .setClaimExpiresAtEpochMillis(NOW_EPOCH_MILLIS + 30_000L) + .setObservedAtEpochMillis(NOW_EPOCH_MILLIS - 1_000L) + .setPurpose(request.getPurpose()) + .build(); + } + + private static StartSessionReservationEvidencePurpose toWirePurpose( + StartSessionReservationEvidenceClient.Purpose purpose) { + return switch (purpose) { + case ISSUE -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE; + case RECOVER -> + StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER; + }; + } + + private static StartSessionPreAuthorizationReservationTuple tuple() { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "reservation evidence client test"); + return StartSessionPreAuthorizationReservationTuple.createHuman(REQUEST_ID, ACTOR_ID, action); + } + + private static CommonGrpcClientProperties tlsProperties(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setCertChain(copyCertificateResource("dev-cert.pem", directory).toString()); + tls.setPrivateKey(copyCertificateResource("dev-key.pem", directory).toString()); + tls.setCaCert(copyCertificateResource("dev-ca.pem", directory).toString()); + return tls; + } + + private static Path copyCertificateResource(String fileName, Path directory) throws Exception { + Path destination = directory.resolve(fileName); + try (InputStream source = + StartSessionReservationEvidenceClientTest.class.getResourceAsStream("/certs/" + fileName)) { + if (source == null) { + throw new IllegalStateException("Missing shared TLS test resource: " + fileName); + } + Files.copy(source, destination); + } + return destination; + } + + @FunctionalInterface + private interface EvidenceHandler { + ReadCurrentClaimEvidenceResponse read(ReadCurrentClaimEvidenceRequest request); + } + + private record InProcessFixture(Server server, ManagedChannel channel) implements AutoCloseable { + private StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + stub() { + return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel); + } + + @Override + public void close() throws Exception { + channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + } + } + + private record StartSessionReservationClientTestAccess( + StartSessionReservationEvidenceClient client) { + private void installStub( + StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceBlockingStub + stub) + throws Exception { + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java new file mode 100644 index 0000000000..65aa053af9 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java @@ -0,0 +1,783 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.sun.net.httpserver.Headers; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpsConfigurator; +import com.sun.net.httpserver.HttpsServer; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.security.KeyStore; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiOperation; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.BindingRejectedException; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ValidatorExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical loopback HTTPS proof for Account's production pinned-CA JWKS API transport only. */ +class AccountJwtJwksApiTransportTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String API_USERNAME = "system:serviceaccount:firemud-prod:account-service"; + private static final String KUBE_SYSTEM_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 TEST_BEARER = "test-only-loopback-bearer"; + private static final char[] KEYSTORE_PASSWORD = "firemud-test".toCharArray(); + private static final Duration NORMAL_TIMEOUT = Duration.ofSeconds(3); + private static final Duration STALL_TIMEOUT = Duration.ofMillis(350); + private static final byte[] SELF_REVIEW = + (""" + {"apiVersion":"authentication.k8s.io/v1","kind":"SelfSubjectReview",%n\ + "status":{"userInfo":{"username":"%s"}}}%n""" + .formatted(API_USERNAME)) + .getBytes(StandardCharsets.UTF_8); + private static final byte[] KUBE_SYSTEM_NAMESPACE = + namespaceJson("kube-system", KUBE_SYSTEM_UID).getBytes(StandardCharsets.UTF_8); + private static final byte[] TARGET_NAMESPACE = + namespaceJson(NAMESPACE, NAMESPACE_UID).getBytes(StandardCharsets.UTF_8); + private static final byte[] CONFIG_MAP = + (""" + {"apiVersion":"v1","kind":"ConfigMap","metadata":{%n\ + "name":"jwt-jwks","namespace":"%s","uid":"%s","resourceVersion":"7"},"data":{}}%n""" + .formatted(NAMESPACE, CONFIG_MAP_UID)) + .getBytes(StandardCharsets.UTF_8); + + @TempDir private static Path temporaryDirectory; + + private static TestPki pki; + + private final List servers = new ArrayList<>(); + + @BeforeAll + static void createEphemeralPki() throws Exception { + Path trustedDirectory = Files.createDirectories(temporaryDirectory.resolve("trusted")); + TestAuthority trustedAuthority = createAuthority(trustedDirectory, "account-jwks-test-ca"); + TestServerCertificate trustedServer = + issueServerCertificate( + trustedDirectory, trustedAuthority, "account-jwks-localhost", "localhost"); + + Path untrustedDirectory = Files.createDirectories(temporaryDirectory.resolve("untrusted")); + TestAuthority untrustedAuthority = + createAuthority(untrustedDirectory, "account-jwks-untrusted-ca"); + + TestServerCertificate wrongHostnameServer = + issueServerCertificate( + trustedDirectory, trustedAuthority, "account-jwks-wrong-host", "wrong.example"); + pki = + new TestPki( + Files.readAllBytes(trustedAuthority.certificate()), + Files.readAllBytes(untrustedAuthority.certificate()), + trustedServer, + wrongHostnameServer); + } + + @AfterEach + void stopLocalServers() { + servers.forEach(server -> server.stop(0)); + } + + @Test + void pinnedCaAndHostnameReachTheFixedKubernetesPathsOverRealHttps() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + AtomicInteger authorizationHeaders = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + requests.add( + exchange.getRequestMethod() + " " + exchange.getRequestURI().getRawPath()); + if (("Bearer " + TEST_BEARER) + .equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + authorizationHeaders.incrementAndGet(); + } + respondForKubernetesRequest(exchange); + }); + AccountJwtJwksConfigMapClient client = + new AccountJwtJwksConfigMapClient( + transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT)); + + ConfigMapSnapshot observed = client.observe(); + + assertThat(observed.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(observed.resourceVersion()).isEqualTo("7"); + assertThat(requests) + .containsExactly( + "POST /apis/authentication.k8s.io/v1/selfsubjectreviews", + "GET /api/v1/namespaces/kube-system", + "GET /api/v1/namespaces/" + NAMESPACE, + "GET /api/v1/namespaces/" + NAMESPACE + "/configmaps/jwt-jwks"); + assertThat(authorizationHeaders).hasValue(4); + } + + @Test + void protectedInventoryOperationsUseOnlyFixedNamespaceGetPathsOverPinnedHttps() throws Exception { + List requests = new CopyOnWriteArrayList<>(); + AtomicInteger authorizationHeaders = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + String query = exchange.getRequestURI().getRawQuery(); + requests.add( + exchange.getRequestMethod() + + " " + + exchange.getRequestURI().getRawPath() + + (query == null ? "" : "?" + query)); + if (("Bearer " + TEST_BEARER) + .equals(exchange.getRequestHeaders().getFirst("Authorization"))) { + authorizationHeaders.incrementAndGet(); + } + respond(exchange, 200, "{}".getBytes(StandardCharsets.UTF_8)); + }); + AccountJwtJwksApiBinding client = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + ProtectedInventory inventory = validatorInventoryForTransport(); + ValidatorExpectation validator = inventory.validators().get(0); + + try (ApiOperation operation = client.beginOperation()) { + ApiResponse deployment = operation.readValidatorDeployment(inventory, validator); + ApiResponse pods = operation.listValidatorPods(inventory, validator, "page/+token="); + ApiResponse replicaSet = + operation.readValidatorReplicaSet(inventory, validator, "player-service-abcde"); + assertThat(deployment.statusCode()).isEqualTo(200); + assertThat(pods.statusCode()).isEqualTo(200); + assertThat(replicaSet.statusCode()).isEqualTo(200); + } + + assertThat(requests) + .containsExactly( + "GET /apis/apps/v1/namespaces/" + NAMESPACE + "/deployments/player-service", + "GET /api/v1/namespaces/" + + NAMESPACE + + "/pods?labelSelector=app%3Dplayer-service%2Cfiremud.io%2Fcomponent%3Djwt-validator" + + "&limit=250&continue=page%2F%2Btoken%3D", + "GET /apis/apps/v1/namespaces/" + NAMESPACE + "/replicasets/player-service-abcde"); + assertThat(authorizationHeaders).hasValue(3); + } + + @Test + void replicaSetReadRejectsCallerSuppliedPathCharacters() throws Exception { + AccountJwtJwksApiBinding client = + transportBinding( + startServer(pki.trustedServer(), exchange -> respond(exchange, 200, new byte[0])), + pki.trustedCa(), + NORMAL_TIMEOUT); + ProtectedInventory inventory = validatorInventoryForTransport(); + ValidatorExpectation validator = inventory.validators().get(0); + + try (ApiOperation operation = client.beginOperation()) { + assertThatThrownBy( + () -> operation.readValidatorReplicaSet(inventory, validator, "../secrets")) + .isInstanceOf(BindingRejectedException.class) + .hasNoCause(); + } + } + + @Test + void serverCertificateFromAnUnpinnedCaIsRejectedByTheProductionTransport() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.untrustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(handlerCalls).hasValue(0); + } + + @Test + void wrongHostnameIsRejectedEvenWhenTheServingCertificateChainsToThePinnedCa() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + HttpsServer server = + startServer( + pki.wrongHostnameServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(handlerCalls).hasValue(0); + } + + @Test + void redirectIsReturnedButNeverFollowed() throws Exception { + AtomicInteger redirectTargetCalls = new AtomicInteger(); + HttpsServer redirectTarget = + startServer( + pki.trustedServer(), + exchange -> { + redirectTargetCalls.incrementAndGet(); + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + }); + List sourceRequests = new CopyOnWriteArrayList<>(); + HttpsServer source = + startServer( + pki.trustedServer(), + exchange -> { + sourceRequests.add(exchange.getRequestURI().getRawPath()); + Headers headers = exchange.getResponseHeaders(); + headers.set( + "Location", + "https://localhost:" + redirectTarget.getAddress().getPort() + "/target"); + respond(exchange, 302, new byte[0]); + }); + AccountJwtJwksApiBinding binding = transportBinding(source, pki.trustedCa(), NORMAL_TIMEOUT); + + ApiResponse response = send(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + assertThat(response.statusCode()).isEqualTo(302); + assertThat(sourceRequests).containsExactly("/api/v1/namespaces/kube-system"); + assertThat(redirectTargetCalls).hasValue(0); + } + + @Test + void stalledPostHeaderBodyIsBoundedByTheWholeResponseDeadline() throws Exception { + CountDownLatch bodyStarted = new CountDownLatch(1); + CountDownLatch releaseBody = new CountDownLatch(1); + CountDownLatch bodyHandlerCompleted = new CountDownLatch(1); + AtomicBoolean releaseBodyTimedOut = new AtomicBoolean(); + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, 0); + try (OutputStream body = exchange.getResponseBody()) { + body.write('{'); + body.flush(); + bodyStarted.countDown(); + releaseBodyTimedOut.set(!releaseBody.await(3, TimeUnit.SECONDS)); + } catch (IOException ignored) { + // The client closes the response stream when its absolute deadline expires. + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } finally { + bodyHandlerCompleted.countDown(); + } + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), STALL_TIMEOUT); + long startedAt = System.nanoTime(); + + try { + assertTransportFailure(binding, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + assertThat(bodyStarted.await(1, TimeUnit.SECONDS)).isTrue(); + assertThat(Duration.ofNanos(System.nanoTime() - startedAt)).isLessThan(Duration.ofSeconds(2)); + } finally { + releaseBody.countDown(); + } + assertThat(bodyHandlerCompleted.await(1, TimeUnit.SECONDS)) + .as("stalled response handler should finish after the test releases its body") + .isTrue(); + assertThat(releaseBodyTimedOut.get()) + .as("test must release the stalled response body before the handler timeout") + .isFalse(); + } + + @Test + void oversizedHttpsResponseIsRejectedWithoutAcceptingPartialBytes() throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + byte[] oversized = new byte[1024 * 1024 + 1]; + HttpsServer server = + startServer( + pki.trustedServer(), + exchange -> { + handlerCalls.incrementAndGet(); + respond(exchange, 200, oversized); + }); + AccountJwtJwksApiBinding binding = transportBinding(server, pki.trustedCa(), NORMAL_TIMEOUT); + + assertTransportFailure(binding, ApiCall.READ_JWKS_CONFIG_MAP); + + assertThat(handlerCalls).hasValue(1); + } + + @Test + void rootOwnedReadOnlyProjectionAllowsRootWritableParentsAndSafeBearerRenewal() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("renewal"); + AccountJwtJwksApiBinding binding = fixture.binding(); + + assertThat(binding.current().namespace()).isEqualTo(NAMESPACE); + ApiOperation inFlight = binding.beginOperation(); + fixture.projectToken("..0002", "renewed-test-bearer", "token"); + + assertThatThrownBy(() -> inFlight.send(ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null)) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + inFlight.close(); + assertThat(binding.current().namespace()).isEqualTo(NAMESPACE); + } + + @Test + void credentialModeAndFrozenTrustFileIdentityDriftAreRejected() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("drift"); + AccountJwtJwksApiBinding binding = fixture.binding(); + binding.current(); + + Files.setPosixFilePermissions(fixture.currentToken(), Set.of(PosixFilePermission.OWNER_READ)); + assertThatThrownBy(binding::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles ownerFixture = protectedFiles("owner-drift"); + ownerFixture.binding().current(); + Files.setAttribute(ownerFixture.currentToken(), "unix:uid", 65534, LinkOption.NOFOLLOW_LINKS); + assertThatThrownBy(ownerFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles groupFixture = protectedFiles("group-drift"); + groupFixture.binding().current(); + int gid = + (Integer) + Files.getAttribute(groupFixture.currentToken(), "unix:gid", LinkOption.NOFOLLOW_LINKS); + Files.setAttribute( + groupFixture.currentToken(), "unix:gid", gid == 0 ? 1 : 0, LinkOption.NOFOLLOW_LINKS); + assertThatThrownBy(groupFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles trustFixture = protectedFiles("trust-drift"); + trustFixture.binding().current(); + Path replacementCa = trustFixture.caPath().resolveSibling("replacement-serving-ca.pem"); + Files.writeString(replacementCa, "test-only-public-serving-ca", StandardCharsets.UTF_8); + Files.setPosixFilePermissions( + replacementCa, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + Files.move(replacementCa, trustFixture.caPath(), StandardCopyOption.REPLACE_EXISTING); + assertThatThrownBy(trustFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + + ProtectedFiles bindingFixture = protectedFiles("binding-drift"); + bindingFixture.binding().current(); + Path replacementBinding = + bindingFixture.bindingPath().resolveSibling("replacement-binding.json"); + Files.write(replacementBinding, Files.readAllBytes(bindingFixture.bindingPath())); + Files.setPosixFilePermissions(replacementBinding, PosixFilePermissions.fromString("r--r-----")); + Files.move( + replacementBinding, bindingFixture.bindingPath(), StandardCopyOption.REPLACE_EXISTING); + assertThatThrownBy(bindingFixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + } + + @Test + void groupOrOtherWritableProtectedProjectionDirectoryIsRejected() throws Exception { + assumeRootCanCreateRootOwnedFixtures(); + ProtectedFiles fixture = protectedFiles("writable-directory"); + Files.setPosixFilePermissions( + fixture.trustRoot(), + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_WRITE, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE)); + + assertThatThrownBy(fixture.binding()::current) + .isInstanceOf(AccountJwtJwksApiBinding.BindingRejectedException.class); + } + + private static void assertTransportFailure(AccountJwtJwksApiBinding binding, ApiCall call) { + assertThatThrownBy(() -> send(binding, call)) + .isInstanceOf(AccountJwtJwksApiBinding.ApiTransportException.class) + .hasMessage("Account JWT JWKS Kubernetes API request failed"); + } + + private static ApiResponse send(AccountJwtJwksApiBinding binding, ApiCall call) { + try (ApiOperation operation = binding.beginOperation()) { + return operation.send(call, null); + } + } + + private static void assumeRootCanCreateRootOwnedFixtures() throws Exception { + Object uid = Files.getAttribute(temporaryDirectory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Assumptions.assumeTrue(uid instanceof Number number && number.longValue() == 0L); + } + + private ProtectedFiles protectedFiles(String label) throws Exception { + Path root = Files.createDirectories(temporaryDirectory.resolve(label)); + Path trustRoot = Files.createDirectory(root.resolve("account-jwt-api")); + Path tokenRoot = Files.createDirectory(root.resolve("account-jwt-api-token")); + Path bindingPath = trustRoot.resolve("binding.json"); + Path caPath = trustRoot.resolve("serving-ca.pem"); + Path tokenPath = tokenRoot.resolve("token"); + byte[] caBytes = "test-only-public-serving-ca".getBytes(StandardCharsets.UTF_8); + Files.write(caPath, caBytes); + Path firstVersion = Files.createDirectory(tokenRoot.resolve("..0001")); + Path firstToken = firstVersion.resolve("token"); + Files.writeString(firstToken, "initial-test-bearer"); + Files.createSymbolicLink(tokenRoot.resolve("..data"), Path.of("..0001")); + Files.createSymbolicLink(tokenPath, Path.of("..data/token")); + applyPermissions(trustRoot, "rwxr-xr-x"); + applyPermissions(tokenRoot, "rwxr-xr-x"); + applyPermissions(firstVersion, "rwxr-xr-x"); + Files.createFile(bindingPath); + applyPermissions(bindingPath, "r--r-----"); + applyPermissions(caPath, "r--r-----"); + applyPermissions(firstToken, "r--r-----"); + writeBinding(bindingPath, caPath, tokenPath, caBytes); + return new ProtectedFiles( + bindingPath, + trustRoot, + caPath, + tokenRoot, + tokenPath, + firstToken, + AccountJwtJwksApiBinding.forProtectedFilesTest( + bindingPath, trustRoot, caPath, tokenRoot, tokenPath)); + } + + private static void writeBinding(Path bindingPath, Path caPath, Path tokenPath, byte[] caBytes) + throws Exception { + Map values = new LinkedHashMap<>(); + values.put("version", "account-jwt-jwks-api-binding/v1"); + values.put("enabled", "true"); + values.put("configRevision", "physical-file-test-1"); + values.put("environmentId", "prod"); + values.put("clusterId", "loopback-cluster"); + values.put("apiServerUrl", "https://localhost:6443"); + values.put("tlsServerName", "localhost"); + values.put("servingCaPath", caPath.toString()); + values.put("servingCaSha256", sha256(caBytes)); + values.put("bearerTokenPath", tokenPath.toString()); + values.put("namespace", NAMESPACE); + values.put("expectedClusterIncarnationUid", KUBE_SYSTEM_UID); + values.put("expectedNamespaceUid", NAMESPACE_UID); + values.put("expectedApiUsername", API_USERNAME); + values.put("bindingDigest", "0".repeat(64)); + tools.jackson.databind.json.JsonMapper mapper = + tools.jackson.databind.json.JsonMapper.builder().build(); + String placeholder = mapper.writeValueAsString(values); + tools.jackson.databind.JsonNode binding = mapper.readTree(placeholder); + values.put("bindingDigest", AccountJwtJwksApiBinding.computeBindingDigest(binding)); + Files.writeString(bindingPath, mapper.writeValueAsString(values), StandardCharsets.UTF_8); + } + + private static void applyPermissions(Path path, String mode) throws IOException { + Files.setPosixFilePermissions(path, PosixFilePermissions.fromString(mode)); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "These fixed nonexistent paths stand in for protected trust inputs in the transport-only fixture and are never read.") + private AccountJwtJwksApiBinding transportBinding( + HttpsServer server, byte[] trustedCa, Duration timeout) throws Exception { + ParsedBinding binding = + new ParsedBinding( + "transport-test-1", + "prod", + "loopback-cluster", + java.net.URI.create("https://localhost:" + server.getAddress().getPort() + "/"), + "localhost", + Path.of("/not-read-by-transport-test/trusted-ca.pem"), + sha256(trustedCa), + Path.of("/not-read-by-transport-test/bearer-token"), + NAMESPACE, + KUBE_SYSTEM_UID, + NAMESPACE_UID, + API_USERNAME, + "f".repeat(64)); + return AccountJwtJwksApiBinding.forTransportTest(binding, trustedCa, TEST_BEARER, timeout); + } + + private static ProtectedInventory validatorInventoryForTransport() throws Exception { + Map validator = new LinkedHashMap<>(); + validator.put("validatorId", "player-service"); + validator.put("deploymentName", "player-service"); + validator.put("deploymentUid", "44444444-4444-4444-8444-444444444444"); + validator.put( + "selector", Map.of("app", "player-service", "firemud.io/component", "jwt-validator")); + validator.put("replicas", 1); + validator.put("containerName", "player-service"); + validator.put("image", "registry.example/firemud/player@sha256:" + "a".repeat(64)); + validator.put("jwksUri", "https://account-api.test/.well-known/jwks.json"); + validator.put("maxCacheAgeSeconds", 60); + validator.put( + "profiles", + List.of( + Map.of( + "tokenProfile", "game-session-account-delegation", + "audience", "account-service"))); + validator.put("receiverServiceUri", "spiffe://firemud/ns/firemud-prod/sa/player-service"); + validator.put("receiverPort", 8443); + validator.put( + "receiverPods", + List.of( + Map.of( + "podUid", "55555555-5555-4555-8555-555555555555", + "podIp", "10.0.0.10", + "leafSpkiSha256", "b".repeat(64)))); + Map root = new LinkedHashMap<>(); + root.put("version", "account-jwt-validator-inventory-binding/v2"); + root.put("enabled", "true"); + root.put("configRevision", "inventory-r1"); + root.put("environmentId", "prod"); + root.put("clusterId", "loopback-cluster"); + root.put("namespace", NAMESPACE); + root.put("expectedClusterIncarnationUid", KUBE_SYSTEM_UID); + root.put("expectedNamespaceUid", NAMESPACE_UID); + root.put("apiBindingRevision", "transport-test-1"); + root.put("apiBindingDigest", "f".repeat(64)); + root.put("validators", List.of(validator)); + root.put("bindingDigest", "0".repeat(64)); + tools.jackson.databind.json.JsonMapper mapper = + tools.jackson.databind.json.JsonMapper.builder().build(); + var unsigned = mapper.readTree(mapper.writeValueAsBytes(root)); + root.put("bindingDigest", AccountJwtValidatorInventoryBinding.computeBindingDigest(unsigned)); + return AccountJwtValidatorInventoryBinding.parseProtectedBytes(mapper.writeValueAsBytes(root)); + } + + private HttpsServer startServer(TestServerCertificate certificate, HttpHandler handler) + throws Exception { + SSLContext sslContext = serverSslContext(certificate.pkcs12()); + InetAddress loopback = InetAddress.getByName("localhost"); + HttpsServer server = HttpsServer.create(new InetSocketAddress(loopback, 0), 0); + server.setHttpsConfigurator(new HttpsConfigurator(sslContext)); + server.createContext("/", handler); + server.start(); + servers.add(server); + return server; + } + + private static SSLContext serverSslContext(Path pkcs12Path) throws Exception { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream input = Files.newInputStream(pkcs12Path)) { + keyStore.load(input, KEYSTORE_PASSWORD); + } + KeyManagerFactory keyManagers = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagers.init(keyStore, KEYSTORE_PASSWORD); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(keyManagers.getKeyManagers(), null, null); + return context; + } + + private static void respondForKubernetesRequest(HttpExchange exchange) throws IOException { + String path = exchange.getRequestURI().getRawPath(); + if ("/apis/authentication.k8s.io/v1/selfsubjectreviews".equals(path)) { + exchange.getRequestBody().readAllBytes(); + respond(exchange, 201, SELF_REVIEW); + } else if ("/api/v1/namespaces/kube-system".equals(path)) { + respond(exchange, 200, KUBE_SYSTEM_NAMESPACE); + } else if (("/api/v1/namespaces/" + NAMESPACE).equals(path)) { + respond(exchange, 200, TARGET_NAMESPACE); + } else if (("/api/v1/namespaces/" + NAMESPACE + "/configmaps/jwt-jwks").equals(path)) { + respond(exchange, 200, CONFIG_MAP); + } else { + respond(exchange, 404, new byte[0]); + } + } + + private static void respond(HttpExchange exchange, int statusCode, byte[] body) + throws IOException { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + if (body.length == 0) { + exchange.sendResponseHeaders(statusCode, -1); + exchange.close(); + return; + } + exchange.sendResponseHeaders(statusCode, body.length); + try (OutputStream output = exchange.getResponseBody()) { + output.write(body); + } + } + + private static TestAuthority createAuthority(Path directory, String commonName) throws Exception { + Path key = directory.resolve(commonName + ".key"); + Path certificate = directory.resolve(commonName + ".crt"); + runOpenSsl( + directory, + "req", + "-x509", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + key.toString(), + "-out", + certificate.toString(), + "-subj", + "/CN=" + commonName, + "-days", + "2", + "-sha256", + "-addext", + "basicConstraints=critical,CA:TRUE", + "-addext", + "keyUsage=critical,keyCertSign,cRLSign"); + return new TestAuthority(key, certificate); + } + + private static TestServerCertificate issueServerCertificate( + Path directory, TestAuthority authority, String commonName, String dnsName) throws Exception { + Path key = directory.resolve(commonName + ".key"); + Path request = directory.resolve(commonName + ".csr"); + Path certificate = directory.resolve(commonName + ".crt"); + Path extensions = directory.resolve(commonName + ".ext"); + Path pkcs12 = directory.resolve(commonName + ".p12"); + Files.writeString( + extensions, + "basicConstraints=critical,CA:FALSE\n" + + "keyUsage=critical,digitalSignature,keyEncipherment\n" + + "extendedKeyUsage=serverAuth\n" + + "subjectAltName=DNS:" + + dnsName + + "\n"); + runOpenSsl( + directory, + "req", + "-new", + "-newkey", + "rsa:2048", + "-nodes", + "-keyout", + key.toString(), + "-out", + request.toString(), + "-subj", + "/CN=" + commonName); + runOpenSsl( + directory, + "x509", + "-req", + "-in", + request.toString(), + "-CA", + authority.certificate().toString(), + "-CAkey", + authority.privateKey().toString(), + "-CAcreateserial", + "-out", + certificate.toString(), + "-days", + "2", + "-sha256", + "-extfile", + extensions.toString()); + runOpenSsl( + directory, + "pkcs12", + "-export", + "-out", + pkcs12.toString(), + "-inkey", + key.toString(), + "-in", + certificate.toString(), + "-certfile", + authority.certificate().toString(), + "-passout", + "pass:firemud-test"); + return new TestServerCertificate(pkcs12); + } + + private static void runOpenSsl(Path workingDirectory, String... arguments) throws Exception { + List command = new ArrayList<>(); + command.add("openssl"); + command.addAll(List.of(arguments)); + Process process; + try { + process = + new ProcessBuilder(command) + .directory(workingDirectory.toFile()) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + } catch (IOException failure) { + throw new IllegalStateException("OpenSSL is required for this ephemeral HTTPS test", failure); + } + if (!process.waitFor(20, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + throw new IllegalStateException("Ephemeral HTTPS certificate generation timed out"); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("Ephemeral HTTPS certificate generation failed"); + } + } + + private static String namespaceJson(String name, String uid) { + return """ + {"apiVersion":"v1","kind":"Namespace","metadata":{"name":"%s","uid":"%s"},%n\ + "status":{"phase":"Active"}}%n""" + .formatted(name, uid); + } + + private static String sha256(byte[] bytes) throws Exception { + return java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private record ProtectedFiles( + Path bindingPath, + Path trustRoot, + Path caPath, + Path tokenRoot, + Path tokenPath, + Path currentToken, + AccountJwtJwksApiBinding binding) { + void projectToken(String version, String value, String fileName) throws IOException { + Path versionDirectory = Files.createDirectory(tokenRoot.resolve(version)); + Path nextToken = versionDirectory.resolve(fileName); + Files.writeString(nextToken, value, StandardCharsets.UTF_8); + applyPermissions(versionDirectory, "rwxr-xr-x"); + applyPermissions(nextToken, "r--r-----"); + Path dataLink = tokenRoot.resolve("..data"); + Files.delete(dataLink); + Files.createSymbolicLink(dataLink, Path.of(version)); + } + } + + private record TestAuthority(Path privateKey, Path certificate) {} + + private record TestServerCertificate(Path pkcs12) {} + + private record TestPki( + byte[] trustedCa, + byte[] untrustedCa, + TestServerCertificate trustedServer, + TestServerCertificate wrongHostnameServer) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventorySourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventorySourceTest.java index 58ac45e7dc..534d36a8c1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventorySourceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventorySourceTest.java @@ -114,6 +114,114 @@ void rejectsPrivateSignerMaterialInInitAndEphemeralContainersAndProjectedVolumes assertUnavailable(projectedSecret); } + @Test + void rejectsSigningSecretAccessAcrossEveryPodContainerFamily() throws Exception { + List families = List.of("containers", "initContainers", "ephemeralContainers"); + List accessForms = List.of("envFrom", "secretKeyRef", "volumeMount"); + + for (String family : families) { + for (String accessForm : accessForms) { + Fixture fixture = new Fixture(); + ObjectNode podSpec; + ObjectNode container; + ObjectNode observedResource; + boolean podObservation = "ephemeralContainers".equals(family); + if (podObservation) { + ObjectNode podList = (ObjectNode) JSON.readTree(podListJson()); + podSpec = (ObjectNode) podList.path("items").get(0).path("spec"); + container = JSON.createObjectNode(); + container.put("name", "debug"); + container.put("image", IMAGE); + container.put("targetContainerName", "player-service"); + podSpec.withArray(family).add(container); + observedResource = podList; + } else { + ObjectNode deployment = (ObjectNode) JSON.readTree(deploymentJson("10", 1, 1, 1, false)); + podSpec = (ObjectNode) deployment.path("spec").path("template").path("spec"); + if ("containers".equals(family)) { + container = (ObjectNode) podSpec.path("containers").get(0); + } else { + container = JSON.createObjectNode(); + container.put("name", "setup"); + container.put("image", IMAGE); + podSpec.withArray(family).add(container); + } + observedResource = deployment; + } + + if ("containers".equals(family) && "envFrom".equals(accessForm)) { + // The selected validator has an independent blanket envFrom prohibition, so this case + // preserves the original matrix input but is not evidence of a signing-name-only guard. + addSigningSecretAccess(podSpec, container, accessForm, "jwt-signing-keys"); + stubObservation(fixture, podObservation, observedResource); + assertThatThrownBy(fixture.source::observe) + .as("selected validator envFrom is rejected by its blanket rule") + .isInstanceOf(InventoryUnavailableException.class) + .hasNoCause(); + continue; + } + + ObjectNode secretSource = + addSigningSecretAccess(podSpec, container, accessForm, "runtime-secrets"); + stubObservation(fixture, podObservation, observedResource); + assertThat(fixture.source.observe()) + .as("accept non-signing %s through %s", accessForm, family) + .isNotNull(); + + // Keep the pod shape and access path valid; change only the referenced Secret name. + secretSource.put( + "volumeMount".equals(accessForm) ? "secretName" : "name", "jwt-signing-keys"); + stubObservation(fixture, podObservation, observedResource); + assertThatThrownBy(fixture.source::observe) + .as("reject signing %s through %s", accessForm, family) + .isInstanceOf(InventoryUnavailableException.class) + .hasNoCause(); + } + } + } + + private static ObjectNode addSigningSecretAccess( + ObjectNode podSpec, ObjectNode container, String accessForm, String secretName) { + return switch (accessForm) { + case "envFrom" -> + container.withArray("envFrom").addObject().putObject("secretRef").put("name", secretName); + case "secretKeyRef" -> + container + .withArray("env") + .addObject() + .put("name", "CREDENTIAL") + .putObject("valueFrom") + .putObject("secretKeyRef") + .put("name", secretName) + .put("key", "signing-key"); + case "volumeMount" -> { + container + .withArray("volumeMounts") + .addObject() + .put("name", "runtime-secrets") + .put("mountPath", "/var/run/secrets/firemud/credentials") + .put("readOnly", true); + yield podSpec + .withArray("volumes") + .addObject() + .put("name", "runtime-secrets") + .putObject("secret") + .put("secretName", secretName); + } + default -> throw new AssertionError("Unexpected signer access form: " + accessForm); + }; + } + + private static void stubObservation( + Fixture fixture, boolean podObservation, ObjectNode observedResource) throws Exception { + ApiResponse response = new ApiResponse(200, JSON.writeValueAsBytes(observedResource)); + if (podObservation) { + fixture.stubPods(response); + } else { + fixture.stubDeployment(response); + } + } + @Test void rejectsSelectedValidatorEnvFromConfigMapAndSecretReferencesAndMalformedValues() throws Exception { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java new file mode 100644 index 0000000000..591d17a77f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java @@ -0,0 +1,354 @@ +package unit.net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import java.util.List; +import java.util.Map; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.config.AccountStartSessionOperatorAuthorizationConfiguration; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.Snapshot; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.convert.ApplicationConversionService; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.MapPropertySource; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Wiring-only test: the supplied mocks and fixed test key do not prove authority or runtime use. + */ +class AccountStartSessionOperatorAuthorizationConfigurationTest { + private static final String OPT_IN = + "firemud.account.start-session-operator-authorization.enabled"; + private static final String RESERVATION_EVIDENCE_CLIENT_BEAN = + "startSessionReservationEvidenceClient"; + private static final String OPERATOR_KEYRING_PATH = + "firemud.account.start-session-operator-authorization.response-envelope.keyring-path"; + private static final String GENERAL_KEYRING_PATH = + "firemud.account.response-envelope.keyring-path"; + private static final String REFERENCE_LIFETIME = + "firemud.account.start-session-operator-authorization.reference-lifetime"; + private static final String RESPONSE_RECOVERY_WINDOW = + "firemud.account.start-session-operator-authorization.response-recovery-window"; + private static final String OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN = + "startSessionOperatorResponseEnvelopeCryptography"; + + @Test + void ownerCompositionIsAbsentWhenTheOptInIsMissingOrFalse() { + contextRunner() + .withUserConfiguration(AccountStartSessionOperatorAuthorizationConfiguration.class) + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context) + .doesNotHaveBean(AccountOperatorAuthorizationFingerprintKeyring.class); + assertThat(context).doesNotHaveBean(AccountResponseEnvelopeCryptography.class); + }); + + contextRunner() + .withUserConfiguration(AccountStartSessionOperatorAuthorizationConfiguration.class) + .withPropertyValues(OPT_IN + "=false") + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.class); + }); + } + + @Test + void reservationEvidenceClientBeanDefinitionRequiresExplicitOptIn() { + assertThat(reservationEvidenceClientBeanDefinition(null)).isFalse(); + assertThat(reservationEvidenceClientBeanDefinition("false")).isFalse(); + assertThat(reservationEvidenceClientBeanDefinition("true")).isTrue(); + } + + private static boolean reservationEvidenceClientBeanDefinition(String enabled) { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + if (enabled != null) { + context + .getEnvironment() + .getPropertySources() + .addFirst(new MapPropertySource("test", Map.of(OPT_IN, enabled))); + } + new AnnotatedBeanDefinitionReader(context) + .register(StartSessionReservationEvidenceClient.class); + return context.getBeanFactory().containsBeanDefinition(RESERVATION_EVIDENCE_CLIENT_BEAN); + } + } + + @Test + void explicitOptInFailsForTheMissingOwnerDependency() { + contextRunner() + .withUserConfiguration( + AccountStartSessionOperatorAuthorizationConfiguration.class, + OwnerDependenciesWithoutActors.class, + GeneralResponseCryptography.class) + .withPropertyValues( + OPT_IN + "=true", + "firemud.grpc.workload-namespace=gameplay", + REFERENCE_LIFETIME + "=PT2M", + RESPONSE_RECOVERY_WINDOW + "=PT30S", + "firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention=PT24H", + OPERATOR_KEYRING_PATH + "=/run/test/operator-response", + GENERAL_KEYRING_PATH + "=/run/test/general-response") + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(rootCause(context.getStartupFailure())) + .hasMessageContaining(AccountControlUiActorService.class.getName()); + }); + } + + @Test + void explicitOptInUsesSuppliedCollaboratorsAndQualifiedOperatorCryptography() { + enabledContext() + .run( + context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .hasSingleBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context) + .hasSingleBean(AccountOperatorAuthorizationFingerprintKeyring.class); + assertThat(context.getBeansOfType(AccountResponseEnvelopeCryptography.class)) + .hasSize(2) + .containsKeys( + "genericAccountResponseEnvelopeCryptography", + OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN); + + AccountResponseEnvelopeCryptography genericCryptography = + context.getBean( + "genericAccountResponseEnvelopeCryptography", + AccountResponseEnvelopeCryptography.class); + AccountResponseEnvelopeCryptography operatorCryptography = + context.getBean( + OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN, + AccountResponseEnvelopeCryptography.class); + assertThat(operatorCryptography).isNotSameAs(genericCryptography); + assertThat(ReflectionTestUtils.getField(operatorCryptography, "keyring")) + .isNotSameAs(ReflectionTestUtils.getField(genericCryptography, "keyring")); + assertThat( + ReflectionTestUtils.getField( + context.getBean(AccountStartSessionOperatorAuthorizationService.class), + "responseCryptography")) + .isSameAs(operatorCryptography); + }); + } + + @Test + void invalidNamespaceAndUnboundedTimingFailForTheirOwnReasons() { + assertStartupFailure( + enabledContext( + "", "PT2M", "PT30S", "/run/test/operator-response", "/run/test/general-response"), + "A valid configured workload namespace is required"); + + assertStartupFailure( + enabledContext( + "gameplay", + "PT6M", + "PT30S", + "/run/test/operator-response", + "/run/test/general-response"), + "reference lifetime must be an explicit bounded millisecond duration"); + + assertStartupFailure( + enabledContext( + "gameplay", + "PT2M", + "PT61S", + "/run/test/operator-response", + "/run/test/general-response"), + "response recovery window must be an explicit bounded millisecond duration"); + } + + @Test + void missingOrReusedOperatorResponseMountPreventsOwnerComposition() { + contextRunner() + .withUserConfiguration( + AccountStartSessionOperatorAuthorizationConfiguration.class, + OwnerDependencies.class, + GeneralResponseCryptography.class) + .withPropertyValues( + OPT_IN + "=true", + "firemud.grpc.workload-namespace=gameplay", + REFERENCE_LIFETIME + "=PT2M", + RESPONSE_RECOVERY_WINDOW + "=PT30S", + "firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention=PT24H", + GENERAL_KEYRING_PATH + "=/run/test/general-response") + .run( + context -> { + assertThat(context).hasFailed(); + assertThat(rootCause(context.getStartupFailure())) + .hasMessageContaining("Absolute operator response keyring mount is required"); + }); + + assertStartupFailure( + enabledContext( + "gameplay", "PT2M", "PT30S", "/run/test/shared-response", "/run/test/shared-response"), + "Operator response keyring must use its separately supplied mount"); + } + + private static void assertStartupFailure( + ApplicationContextRunner runner, String expectedRootCause) { + runner.run( + context -> { + assertThat(context).hasFailed(); + assertThat(rootCause(context.getStartupFailure())) + .hasMessageContaining(expectedRootCause); + }); + } + + private static Throwable rootCause(Throwable failure) { + assertThat(failure).isNotNull(); + Throwable root = failure; + while (root.getCause() != null) { + root = root.getCause(); + } + return root; + } + + private static ApplicationContextRunner enabledContext() { + return enabledContext( + "gameplay", "PT2M", "PT30S", "/run/test/operator-response", "/run/test/general-response"); + } + + private static ApplicationContextRunner enabledContext( + String namespace, + String referenceLifetime, + String responseRecoveryWindow, + String operatorKeyringPath, + String generalKeyringPath) { + return contextRunner() + .withUserConfiguration( + AccountStartSessionOperatorAuthorizationConfiguration.class, + OwnerDependencies.class, + GeneralResponseCryptography.class) + .withPropertyValues( + OPT_IN + "=true", + "firemud.grpc.workload-namespace=" + namespace, + REFERENCE_LIFETIME + "=" + referenceLifetime, + RESPONSE_RECOVERY_WINDOW + "=" + responseRecoveryWindow, + "firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention=PT24H", + OPERATOR_KEYRING_PATH + "=" + operatorKeyringPath, + GENERAL_KEYRING_PATH + "=" + generalKeyringPath); + } + + private static ApplicationContextRunner contextRunner() { + return new ApplicationContextRunner() + .withInitializer( + context -> + context.getBeanFactory().setConversionService(new ApplicationConversionService())); + } + + @TestConfiguration(proxyBeanMethods = false) + static class OwnerDependencies { + @Bean + AccountControlUiActorService actors() { + return mock(AccountControlUiActorService.class); + } + + @Bean + AccountControlUiIssuanceRepository issuanceOperations() { + return mock(AccountControlUiIssuanceRepository.class); + } + + @Bean + StartSessionReservationEvidenceClient reservationEvidence() { + return mock(StartSessionReservationEvidenceClient.class); + } + + @Bean + AccountStartSessionOperatorAuthorizationRepository repository() { + return mock(AccountStartSessionOperatorAuthorizationRepository.class); + } + + @Bean + OwnerKeySource fingerprintOwnerKeySource() { + // Fixed synthetic test bytes; no production or runtime key material is read or provisioned. + return () -> + new Snapshot( + new KeyMaterial("test-active", new SecretKeySpec(new byte[32], "HmacSHA256")), + List.of()); + } + + @Bean + AccountHostedTermsService hostedTerms() { + return mock(AccountHostedTermsService.class); + } + + @Bean + PlatformTransactionManager transactions() { + return mock(PlatformTransactionManager.class); + } + } + + @TestConfiguration(proxyBeanMethods = false) + static class OwnerDependenciesWithoutActors { + @Bean + AccountControlUiIssuanceRepository issuanceOperations() { + return mock(AccountControlUiIssuanceRepository.class); + } + + @Bean + StartSessionReservationEvidenceClient reservationEvidence() { + return mock(StartSessionReservationEvidenceClient.class); + } + + @Bean + AccountStartSessionOperatorAuthorizationRepository repository() { + return mock(AccountStartSessionOperatorAuthorizationRepository.class); + } + + @Bean + OwnerKeySource fingerprintOwnerKeySource() { + return () -> + new Snapshot( + new KeyMaterial("test-active", new SecretKeySpec(new byte[32], "HmacSHA256")), + List.of()); + } + + @Bean + AccountHostedTermsService hostedTerms() { + return mock(AccountHostedTermsService.class); + } + + @Bean + PlatformTransactionManager transactions() { + return mock(PlatformTransactionManager.class); + } + } + + @TestConfiguration(proxyBeanMethods = false) + static class GeneralResponseCryptography { + @Bean + AccountResponseEnvelopeKeyring generalAccountResponseEnvelopeKeyring( + @Value("${firemud.account.response-envelope.keyring-path:}") String keyringPath) { + return new AccountResponseEnvelopeKeyring(keyringPath); + } + + @Bean(name = "genericAccountResponseEnvelopeCryptography") + AccountResponseEnvelopeCryptography genericAccountResponseEnvelopeCryptography( + AccountResponseEnvelopeKeyring generalAccountResponseEnvelopeKeyring) { + return new AccountResponseEnvelopeCryptography(generalAccountResponseEnvelopeKeyring); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java index 4d90039bab..4366dd2a40 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRepositoryTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.util.UUID; import net.firedevops.firemud.accountservice.entity.Account; import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; import net.firedevops.firemud.accountservice.jooq.Tables; @@ -23,6 +24,108 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; class AccountRepositoryTest { + @Test + void numericLockRejectsNonPositiveIdentityBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountRepository repository = new AccountRepository(dsl, sourceEvidence); + + assertThatThrownBy(() -> repository.findByIdForUpdate(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A positive persisted Account ID is required"); + assertThatThrownBy(() -> repository.findByIdForUpdate(0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A positive persisted Account ID is required"); + assertThatThrownBy(() -> repository.findByIdForUpdate(-1L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A positive persisted Account ID is required"); + + verifyNoInteractions(dsl, sourceEvidence); + } + + @Test + void uuidLockRejectsNullAndNilIdentityBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountRepository repository = new AccountRepository(dsl, sourceEvidence); + + assertThatThrownBy(() -> repository.findByAccountUuidForUpdate(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-nil Account UUID is required"); + assertThatThrownBy(() -> repository.findByAccountUuidForUpdate(new UUID(0L, 0L))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A non-nil Account UUID is required"); + + verifyNoInteractions(dsl, sourceEvidence); + } + + @Test + void uuidLockRequiresWritableOwnerTransactionBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountRepository repository = new AccountRepository(dsl, sourceEvidence); + UUID accountUuid = UUID.randomUUID(); + boolean priorActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean priorReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + try { + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + assertThatThrownBy(() -> repository.findByAccountUuidForUpdate(accountUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account authority mutation requires an active writable owner transaction"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> repository.findByAccountUuidForUpdate(accountUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account authority mutation requires an active writable owner transaction"); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(priorReadOnly); + TransactionSynchronizationManager.setActualTransactionActive(priorActive); + } + + verifyNoInteractions(dsl, sourceEvidence); + } + + @Test + void uuidLockRequiresMandatoryOwnerTransactionPropagation() throws NoSuchMethodException { + Transactional transactional = + AccountRepository.class + .getMethod("findByAccountUuidForUpdate", UUID.class) + .getAnnotation(Transactional.class); + + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + } + + @Test + void validLockReadsUseForUpdateOnTheExactAccountSelector() { + DSLContext dsl = mock(DSLContext.class, RETURNS_DEEP_STUBS); + AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + AccountRepository repository = new AccountRepository(dsl, sourceEvidence); + UUID accountUuid = UUID.randomUUID(); + boolean priorActive = TransactionSynchronizationManager.isActualTransactionActive(); + boolean priorReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly(); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThat(repository.findByIdForUpdate(42L)).isEmpty(); + assertThat(repository.findByAccountUuidForUpdate(accountUuid)).isEmpty(); + + verify(dsl.selectFrom(Tables.ACCOUNTS).where(Tables.ACCOUNTS.ID.eq(42L))).forUpdate(); + verify(dsl.selectFrom(Tables.ACCOUNTS).where(Tables.ACCOUNTS.ACCOUNT_UUID.eq(accountUuid))) + .forUpdate(); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(priorReadOnly); + TransactionSynchronizationManager.setActualTransactionActive(priorActive); + } + } + @Test void hardDeletionFailsClosedWithoutSqlOrSourceEvidenceMutation() { DSLContext dsl = mock(DSLContext.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java new file mode 100644 index 0000000000..3881ebc725 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java @@ -0,0 +1,871 @@ +package unit.net.firedevops.firemud.accountservice.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.SQLException; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.Status; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.tools.jdbc.MockConnection; +import org.jooq.tools.jdbc.MockDataProvider; +import org.jooq.tools.jdbc.MockExecuteContext; +import org.jooq.tools.jdbc.MockResult; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountStartSessionOperatorAuthorizationRepositoryTest { + private static final String REQUEST_ID = + "start-session/operator/2355f292-ab9c-458c-8d52-aef18b9254e8"; + private static final UUID ACTOR_ID = UUID.fromString("d888ddc4-4a62-4b25-9bab-c4f94860c2ca"); + private static final UUID TENANT_ID = UUID.fromString("6d1e5ce5-6127-4d35-88b8-7a6f40692038"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("1df91ae6-5125-4e47-9f1d-2e45eab8a4a0"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ca1b63bf-f09f-4a55-96bf-a1fd2e22349e"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("37b1f37d-05d2-4aab-8ed9-c01acbf6606e"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("c0df9691-cba5-4274-a49d-0bc7b2158ef7"); + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final String ISSUER_URI = "spiffe://firemud/ns/prod/sa/logging-admin-service"; + private static final String OWNER_URI = "spiffe://firemud/ns/prod/sa/game-session-service"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactDuplicateReturnsOriginalOutputAndNeverReplacesIt() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate first = candidate(tuple()); + IssuanceCandidate changedOutput = + new IssuanceCandidate( + first.controlPlaneRequestId(), + first.preAuthorizationTuple(), + first.mutationDigest(), + first.issuanceWorkloadUri(), + first.reservationOwnerId(), + first.reservationClaimFence(), + UUID.randomUUID(), + first.issuanceFence() + 1, + bundleReference(first.issuanceFence() + 1), + bytes("different bundle"), + fingerprint("e"), + bytes("different encrypted envelope"), + first.issuedAt().plusSeconds(1), + first.referenceExpiresAt().plusSeconds(1), + first.responseEnvelopeExpiresAt().plusSeconds(1)); + + AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult created = + inTransaction(() -> repository.createOrReadExact(first)); + AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult duplicate = + inTransaction(() -> repository.createOrReadExact(changedOutput)); + + assertThat(created.created()).isTrue(); + assertThat(duplicate.created()).isFalse(); + assertThat(duplicate.issuance().issuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID); + assertThat(duplicate.issuance().issuanceFence()).isEqualTo(4L); + assertThat(duplicate.issuance().bundleReference()).isEqualTo(first.bundleReference()); + assertThat(duplicate.issuance().authorizationReferenceFingerprint()) + .isEqualTo(fingerprint("a")); + assertThat(duplicate.issuance().authorityEvidenceBundle()).containsExactly(bytes("bundle-v1")); + assertThat(duplicate.issuance().encryptedResponseEnvelope()) + .containsExactly(bytes("ciphertext-envelope")); + assertThat(store.insertCount.get()).isEqualTo(1); + assertThat(store.lastInsertSql) + .contains("cast(? as timestamptz), cast(? as timestamptz), cast(? as timestamptz)"); + assertThat(store.lastLockSql).contains("for update"); + + byte[] exposedTuple = duplicate.issuance().preAuthorizationTuple(); + exposedTuple[0] ^= 0x01; + assertThat(duplicate.issuance().preAuthorizationTuple()) + .containsExactly(first.preAuthorizationTuple()); + assertThat(duplicate.issuance().toString()) + .doesNotContain("tuple-v1", "bundle-v1", "ciphertext-envelope"); + } + + @Test + void expiredEnvelopeErasureIsBoundedIdempotentAndRetainsCompactEvidence() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate expired = expiredCandidate(tuple()); + inTransaction(() -> repository.createOrReadExact(expired)); + + var first = + inTransaction( + () -> repository.eraseExpiredResponseEnvelope(expired.controlPlaneRequestId())); + var retry = + inTransaction( + () -> repository.eraseExpiredResponseEnvelope(expired.controlPlaneRequestId())); + + assertThat(first.erasedNow()).isTrue(); + assertThat(retry.erasedNow()).isFalse(); + assertThat(first.issuance().encryptedResponseEnvelope()).isNull(); + assertThat(first.issuance().responseEnvelopeErasedAt()).isEqualTo(NOW); + assertThat(first.issuance().controlPlaneRequestId()).isEqualTo(expired.controlPlaneRequestId()); + assertThat(first.issuance().preAuthorizationTuple()) + .containsExactly(expired.preAuthorizationTuple()); + assertThat(first.issuance().authorizationReferenceFingerprint()) + .isEqualTo(expired.authorizationReferenceFingerprint()); + assertThat(first.issuance().authorityEvidenceBundle()) + .containsExactly(expired.authorityEvidenceBundle()); + assertThat(first.issuance().status()).isEqualTo(Status.ISSUED); + assertThat(store.erasureUpdateCount.get()).isEqualTo(1); + assertThat(store.lastErasureSql) + .contains("response_envelope_expires_at <= clock_timestamp()") + .doesNotContain("set response_envelope_erased_at") + .doesNotContain("delete from", "truncate"); + } + + @Test + void preExpiryAndUnprovedMissingEnvelopeFailClosed() { + MockStore earlyStore = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository earlyRepository = repository(earlyStore); + IssuanceCandidate future = candidate(tuple()); + inTransaction(() -> earlyRepository.createOrReadExact(future)); + + assertThatThrownBy( + () -> + inTransaction( + () -> + earlyRepository.eraseExpiredResponseEnvelope( + future.controlPlaneRequestId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("evidence unavailable"); + assertThat(earlyStore.row.envelope).containsExactly(future.encryptedResponseEnvelope()); + assertThat(earlyStore.erasureUpdateCount.get()).isZero(); + + MockStore unprovedStore = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository unprovedRepository = + repository(unprovedStore); + IssuanceCandidate expired = expiredCandidate(tuple()); + inTransaction(() -> unprovedRepository.createOrReadExact(expired)); + unprovedStore.row.envelope = null; + assertThatThrownBy( + () -> + inTransaction( + () -> + unprovedRepository.findByControlPlaneRequestId( + expired.controlPlaneRequestId()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("evidence unavailable"); + } + + @Test + void fingerprintKeyIdUsesCanonicalAlphabetAndAllowsMaximumLength() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + String maximumKeyId = "k".repeat(64); + String maximumFingerprint = "arfp/v1/" + maximumKeyId + "/" + "a".repeat(64); + IssuanceCandidate maximumKeyIdCandidate = + withFingerprint(candidate(tuple()), maximumFingerprint); + + assertThat(maximumKeyIdCandidate.authorizationReferenceFingerprint()).hasSize(137); + assertThat(inTransaction(() -> repository.createOrReadExact(maximumKeyIdCandidate)).created()) + .isTrue(); + + int callsBeforeMalformed = store.databaseCallCount.get(); + String dottedFingerprint = "arfp/v1/key.with.dot/" + "a".repeat(64); + IssuanceCandidate dottedKeyIdCandidate = withFingerprint(candidate(tuple()), dottedFingerprint); + assertThatThrownBy( + () -> inTransaction(() -> repository.createOrReadExact(dottedKeyIdCandidate))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("fingerprint is malformed"); + assertThat(store.databaseCallCount.get()).isEqualTo(callsBeforeMalformed); + } + + @Test + void bundleReferenceFenceMustMatchTheDurableIssuanceFenceBeforeSql() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate valid = candidate(tuple()); + IssuanceCandidate mismatchedReference = + new IssuanceCandidate( + valid.controlPlaneRequestId(), + valid.preAuthorizationTuple(), + valid.mutationDigest(), + valid.issuanceWorkloadUri(), + valid.reservationOwnerId(), + valid.reservationClaimFence(), + valid.issuanceOperationId(), + valid.issuanceFence(), + bundleReference(valid.issuanceFence() + 1L), + valid.authorityEvidenceBundle(), + valid.authorizationReferenceFingerprint(), + valid.encryptedResponseEnvelope(), + valid.issuedAt(), + valid.referenceExpiresAt(), + valid.responseEnvelopeExpiresAt()); + + assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(mismatchedReference))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("source fence"); + assertThat(store.databaseCallCount.get()).isZero(); + } + + @Test + void changedCanonicalTupleConflictsWithoutReplacingTheOriginal() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate original = candidate(tuple()); + inTransaction(() -> repository.createOrReadExact(original)); + + StartSessionPreAuthorizationReservationTuple changedTuple = tuple("different reason"); + IssuanceCandidate changedBinding = + new IssuanceCandidate( + original.controlPlaneRequestId(), + canonicalBytes(changedTuple), + changedTuple.mutationDigest(), + original.issuanceWorkloadUri(), + original.reservationOwnerId(), + original.reservationClaimFence(), + UUID.randomUUID(), + original.issuanceFence(), + original.bundleReference(), + original.authorityEvidenceBundle(), + original.authorizationReferenceFingerprint(), + original.encryptedResponseEnvelope(), + original.issuedAt(), + original.referenceExpiresAt(), + original.responseEnvelopeExpiresAt()); + + assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(changedBinding))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + assertThat(store.insertCount.get()).isEqualTo(1); + assertThat(store.row.tuple).containsExactly(original.preAuthorizationTuple()); + } + + @Test + void acceptsSharedRaw64DigestAndRejectsPrefixedMalformedOrChangedDigestsBeforeSql() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + StartSessionPreAuthorizationReservationTuple tuple = tuple(); + IssuanceCandidate canonical = candidate(tuple); + + assertThat(canonical.mutationDigest()).matches("[0-9a-f]{64}"); + assertThat(canonical.mutationDigest()).doesNotStartWith("sha256:"); + var created = inTransaction(() -> repository.createOrReadExact(canonical)); + assertThat(created.created()).isTrue(); + assertThat(created.issuance().mutationDigest()).isEqualTo(tuple.mutationDigest()); + + String digest = canonical.mutationDigest(); + String changedDigest = (digest.charAt(0) == '0' ? "1" : "0") + digest.substring(1); + for (String invalidDigest : new String[] {"sha256:" + digest, "not-a-digest", changedDigest}) { + IssuanceCandidate invalid = + candidate( + canonical.controlPlaneRequestId(), canonical.preAuthorizationTuple(), invalidDigest); + int callsBeforeInvalidDigest = store.databaseCallCount.get(); + + assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(invalid))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(store.databaseCallCount.get()).isEqualTo(callsBeforeInvalidDigest); + } + assertThat(store.insertCount.get()).isEqualTo(1); + } + + @Test + void canonicalNonUuidRequestIdRetriesAtExactMultibyteUtf8Bound() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + String boundedRequestId = "é".repeat(64); + StartSessionPreAuthorizationReservationTuple boundaryTuple = + tuple(boundedRequestId, "128-byte NFC request ID boundary"); + IssuanceCandidate candidate = candidate(boundaryTuple, boundedRequestId); + + AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult created = + inTransaction(() -> repository.createOrReadExact(candidate)); + AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult retry = + inTransaction(() -> repository.createOrReadExact(candidate)); + java.util.Optional read = + inTransaction(() -> repository.findByControlPlaneRequestId(boundedRequestId)); + + assertThat(created.created()).isTrue(); + assertThat(retry.created()).isFalse(); + assertThat(read).isPresent(); + assertThat(read.orElseThrow().controlPlaneRequestId()).isEqualTo(boundedRequestId); + assertThat(store.insertCount.get()).isEqualTo(1); + + String oversizedRequestId = "é".repeat(65); + String malformedTupleJson = + boundaryTuple + .canonicalJson() + .replace( + "\"requestId\":\"" + boundedRequestId + "\"", + "\"requestId\":\"" + oversizedRequestId + "\""); + assertThat(malformedTupleJson).contains(oversizedRequestId); + IssuanceCandidate oversized = + candidate(boundedRequestId, bytes(malformedTupleJson), boundaryTuple.mutationDigest()); + int callsBeforeMalformedTuple = store.databaseCallCount.get(); + assertThatThrownBy(() -> inTransaction(() -> repository.createOrReadExact(oversized))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(store.databaseCallCount.get()).isEqualTo(callsBeforeMalformedTuple); + } + + @Test + void redemptionConsumesOnceAndExactRetryReturnsSameAuthorityOnlyResult() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate candidate = candidate(tuple()); + inTransaction(() -> repository.createOrReadExact(candidate)); + RedemptionRequest request = redemption(candidate, OWNER_ATTEMPT_ID, 8L, OWNER_URI); + + var first = inTransaction(() -> repository.redeemExact(request)); + var retry = inTransaction(() -> repository.redeemExact(request)); + + assertThat(first.replay()).isFalse(); + assertThat(retry.replay()).isTrue(); + assertThat(first.authorizationReferenceFingerprint()).isEqualTo(fingerprint("a")); + assertThat(retry.authorizationReferenceFingerprint()) + .isEqualTo(first.authorizationReferenceFingerprint()); + assertThat(first.authorityEvidenceBundle()).containsExactly(bytes("bundle-v1")); + assertThat(retry.authorityEvidenceBundle()).containsExactly(first.authorityEvidenceBundle()); + assertThat(first.issuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID); + assertThat(store.redemptionUpdateCount.get()).isEqualTo(1); + assertThat(store.lastRedemptionSql) + .contains( + "redeemed_at = cast(? as timestamptz)", + "reference_expires_at > cast(? as timestamptz)"); + assertThat(first.toString()).doesNotContain("bundle-v1", "ciphertext-envelope"); + } + + @Test + void aDifferentAttemptFenceOrRedeemerCannotReplayConsumedReference() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate candidate = candidate(tuple()); + inTransaction(() -> repository.createOrReadExact(candidate)); + RedemptionRequest first = redemption(candidate, OWNER_ATTEMPT_ID, 8L, OWNER_URI); + inTransaction(() -> repository.redeemExact(first)); + + RedemptionRequest changedAttempt = redemption(candidate, UUID.randomUUID(), 8L, OWNER_URI); + RedemptionRequest changedFence = redemption(candidate, OWNER_ATTEMPT_ID, 9L, OWNER_URI); + RedemptionRequest changedRedeemer = + redemption( + candidate, OWNER_ATTEMPT_ID, 8L, "spiffe://firemud/ns/staging/sa/game-session-service"); + + for (RedemptionRequest changed : + new RedemptionRequest[] {changedAttempt, changedFence, changedRedeemer}) { + assertThatThrownBy(() -> inTransaction(() -> repository.redeemExact(changed))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("conflicts"); + } + assertThat(store.redemptionUpdateCount.get()).isEqualTo(1); + } + + @Test + void expiredReferenceIsNotConsumedAndMalformedTupleOrFencesFailBeforeSql() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + IssuanceCandidate candidate = candidate(tuple()); + inTransaction(() -> repository.createOrReadExact(candidate)); + + RedemptionRequest expired = + new RedemptionRequest( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.authorizationReferenceFingerprint(), + RESERVATION_OWNER_ID, + 2L, + OWNER_URI, + OWNER_ATTEMPT_ID, + 8L, + candidate.authorityEvidenceBundle(), + candidate.referenceExpiresAt()); + assertThatThrownBy(() -> inTransaction(() -> repository.redeemExact(expired))) + .isInstanceOf( + AccountStartSessionOperatorAuthorizationRepository.ReferenceExpiredException.class); + assertThat(store.row.status).isEqualTo("ISSUED"); + + int operationsBeforeInvalidInput = store.databaseCallCount.get(); + RedemptionRequest invalidFence = + new RedemptionRequest( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.authorizationReferenceFingerprint(), + RESERVATION_OWNER_ID, + 0L, + OWNER_URI, + OWNER_ATTEMPT_ID, + 8L, + candidate.authorityEvidenceBundle(), + NOW); + assertThatThrownBy(() -> inTransaction(() -> repository.redeemExact(invalidFence))) + .isInstanceOf(IllegalArgumentException.class); + + byte[] malformedTuple = bytes("not canonical tuple"); + RedemptionRequest invalidTuple = + new RedemptionRequest( + candidate.controlPlaneRequestId(), + malformedTuple, + candidate.authorizationReferenceFingerprint(), + RESERVATION_OWNER_ID, + 2L, + OWNER_URI, + OWNER_ATTEMPT_ID, + 8L, + candidate.authorityEvidenceBundle(), + NOW); + assertThatThrownBy(() -> inTransaction(() -> repository.redeemExact(invalidTuple))) + .isInstanceOf(IllegalArgumentException.class); + + String unsupportedTupleJson = + new String(candidate.preAuthorizationTuple(), java.nio.charset.StandardCharsets.UTF_8) + .replace("\"tupleSchemaVersion\":\"1\"", "\"tupleSchemaVersion\":\"2\""); + RedemptionRequest unsupportedTuple = + new RedemptionRequest( + candidate.controlPlaneRequestId(), + bytes(unsupportedTupleJson), + candidate.authorizationReferenceFingerprint(), + RESERVATION_OWNER_ID, + 2L, + OWNER_URI, + OWNER_ATTEMPT_ID, + 8L, + candidate.authorityEvidenceBundle(), + NOW); + assertThatThrownBy(() -> inTransaction(() -> repository.redeemExact(unsupportedTuple))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(store.databaseCallCount.get()).isEqualTo(operationsBeforeInvalidInput); + } + + @Test + void ownerTransactionIsMandatoryBeforeAnySql() { + MockStore store = new MockStore(); + AccountStartSessionOperatorAuthorizationRepository repository = repository(store); + + assertThatThrownBy(() -> repository.createOrReadExact(candidate(tuple()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("active Account transaction"); + assertThat(store.databaseCallCount.get()).isZero(); + } + + private static AccountStartSessionOperatorAuthorizationRepository repository(MockStore store) { + return new AccountStartSessionOperatorAuthorizationRepository( + DSL.using(new MockConnection(store), SQLDialect.POSTGRES)); + } + + private static IssuanceCandidate candidate(StartSessionPreAuthorizationReservationTuple tuple) { + return candidate(tuple, REQUEST_ID); + } + + private static IssuanceCandidate candidate( + StartSessionPreAuthorizationReservationTuple tuple, String requestId) { + return candidate(requestId, canonicalBytes(tuple), tuple.mutationDigest()); + } + + private static IssuanceCandidate candidate(String requestId, byte[] tupleBytes, String digest) { + return new IssuanceCandidate( + requestId, + tupleBytes, + digest, + ISSUER_URI, + RESERVATION_OWNER_ID, + 2L, + ISSUANCE_OPERATION_ID, + 4L, + bundleReference(4L), + bytes("bundle-v1"), + fingerprint("a"), + bytes("ciphertext-envelope"), + NOW, + NOW.plusSeconds(180), + NOW.plusSeconds(210)); + } + + private static IssuanceCandidate expiredCandidate( + StartSessionPreAuthorizationReservationTuple tuple) { + return new IssuanceCandidate( + tuple.controlPlaneRequestId(), + canonicalBytes(tuple), + tuple.mutationDigest(), + ISSUER_URI, + RESERVATION_OWNER_ID, + 2L, + ISSUANCE_OPERATION_ID, + 4L, + bundleReference(4L), + bytes("bundle-v1"), + fingerprint("a"), + bytes("expired-ciphertext-envelope"), + NOW.minusSeconds(240), + NOW.minusSeconds(60), + NOW.minusSeconds(30)); + } + + private static IssuanceCandidate withFingerprint(IssuanceCandidate original, String fingerprint) { + return new IssuanceCandidate( + original.controlPlaneRequestId(), + original.preAuthorizationTuple(), + original.mutationDigest(), + original.issuanceWorkloadUri(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.issuanceOperationId(), + original.issuanceFence(), + original.bundleReference(), + original.authorityEvidenceBundle(), + fingerprint, + original.encryptedResponseEnvelope(), + original.issuedAt(), + original.referenceExpiresAt(), + original.responseEnvelopeExpiresAt()); + } + + private static RedemptionRequest redemption( + IssuanceCandidate candidate, UUID attemptId, long ownerFence, String redeemerUri) { + return new RedemptionRequest( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.authorizationReferenceFingerprint(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + redeemerUri, + attemptId, + ownerFence, + candidate.authorityEvidenceBundle(), + NOW.plusSeconds(1)); + } + + private static StartSessionPreAuthorizationReservationTuple tuple() { + return tuple("StartSession durable operator authorization test"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String auditReason) { + return tuple(REQUEST_ID, auditReason); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String controlPlaneRequestId, String auditReason) { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + auditReason); + return StartSessionPreAuthorizationReservationTuple.createHuman( + controlPlaneRequestId, ACTOR_ID, action); + } + + private static byte[] canonicalBytes(StartSessionPreAuthorizationReservationTuple tuple) { + return tuple.canonicalJson().getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + private static byte[] bytes(String value) { + return value.getBytes(java.nio.charset.StandardCharsets.UTF_8); + } + + private static String fingerprint(String hexStart) { + return "arfp/v1/key-1/" + hexStart + "0".repeat(63); + } + + private static BundleReference bundleReference(long sourceFence) { + return new BundleReference( + "authorityEvidenceBundle/v1", "12", Long.toString(sourceFence), "123456789"); + } + + private static T inTransaction(java.util.function.Supplier action) { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + return action.get(); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private static OffsetDateTime timestampBinding(Object value) { + if (!(value instanceof String timestamp)) { + throw new IllegalArgumentException("Mock SQL timestamp binding must be text"); + } + if (timestamp.length() <= 10 || timestamp.charAt(10) != ' ') { + throw new IllegalArgumentException( + "Mock SQL timestamp binding must use its date-time separator"); + } + return OffsetDateTime.parse(timestamp.substring(0, 10) + "T" + timestamp.substring(11)); + } + + private static final class MockStore implements MockDataProvider { + private static final Field REQUEST_ID = + DSL.field("control_plane_request_id", String.class); + private static final Field TUPLE = DSL.field("pre_authorization_tuple", byte[].class); + private static final Field DIGEST = DSL.field("mutation_digest", String.class); + private static final Field ISSUER = DSL.field("issuance_workload_uri", String.class); + private static final Field RESERVATION_OWNER = + DSL.field("reservation_owner_id", UUID.class); + private static final Field RESERVATION_FENCE = + DSL.field("reservation_claim_fence", Long.class); + private static final Field OPERATION_ID = DSL.field("issuance_operation_id", UUID.class); + private static final Field ISSUANCE_FENCE = DSL.field("issuance_fence", Long.class); + private static final Field BUNDLE_VERSION = DSL.field("bundle_version", String.class); + private static final Field BUNDLE_SOURCE_VERSION = + DSL.field("bundle_source_version", String.class); + private static final Field BUNDLE_SOURCE_FENCE = + DSL.field("bundle_source_fence", String.class); + private static final Field BUNDLE_LINEARIZATION = + DSL.field("bundle_linearization", String.class); + private static final Field BUNDLE = + DSL.field("authority_evidence_bundle", byte[].class); + private static final Field FINGERPRINT = + DSL.field("authorization_reference_fingerprint", String.class); + private static final Field ENVELOPE = + DSL.field("encrypted_response_envelope", byte[].class); + private static final Field ENVELOPE_ERASED_AT = + DSL.field("response_envelope_erased_at", OffsetDateTime.class); + private static final Field ISSUED_AT = + DSL.field("issued_at", OffsetDateTime.class); + private static final Field REFERENCE_EXPIRY = + DSL.field("reference_expires_at", OffsetDateTime.class); + private static final Field ENVELOPE_EXPIRY = + DSL.field("response_envelope_expires_at", OffsetDateTime.class); + private static final Field STATUS = DSL.field("status", String.class); + private static final Field REDEEMER = + DSL.field("redemption_redeemer_workload_uri", String.class); + private static final Field OWNER_ATTEMPT = + DSL.field("redemption_owner_attempt_id", UUID.class); + private static final Field OWNER_FENCE = DSL.field("redemption_owner_fence", Long.class); + private static final Field REDEEMED_AT = + DSL.field("redeemed_at", OffsetDateTime.class); + private static final Field REDEMPTION_FINGERPRINT = + DSL.field("redemption_reference_fingerprint", String.class); + private static final Field REDEMPTION_BUNDLE = + DSL.field("redemption_authority_evidence_bundle", byte[].class); + + private final AtomicInteger databaseCallCount = new AtomicInteger(); + private final AtomicInteger insertCount = new AtomicInteger(); + private final AtomicInteger redemptionUpdateCount = new AtomicInteger(); + private final AtomicInteger erasureUpdateCount = new AtomicInteger(); + private String lastInsertSql = ""; + private String lastRedemptionSql = ""; + private String lastErasureSql = ""; + private String lastLockSql = ""; + private StoredRow row; + + @Override + public MockResult[] execute(MockExecuteContext context) throws SQLException { + databaseCallCount.incrementAndGet(); + String sql = context.sql().stripLeading().toLowerCase(java.util.Locale.ROOT); + Object[] bind = context.bindings(); + if (sql.startsWith("insert into account_start_session_operator_authorizations")) { + lastInsertSql = sql; + if (row == null) { + row = StoredRow.fromInsert(bind); + insertCount.incrementAndGet(); + return new MockResult[] {new MockResult(1)}; + } + return new MockResult[] {new MockResult(0)}; + } + if (sql.startsWith("update account_start_session_operator_authorizations")) { + if (sql.contains("set encrypted_response_envelope = null")) { + lastErasureSql = sql; + if (row == null + || row.envelope == null + || row.responseEnvelopeErasedAt != null + || row.envelopeExpiresAt.toInstant().isAfter(NOW)) { + return new MockResult[] {new MockResult(0)}; + } + row.envelope = null; + row.responseEnvelopeErasedAt = OffsetDateTime.ofInstant(NOW, java.time.ZoneOffset.UTC); + erasureUpdateCount.incrementAndGet(); + return new MockResult[] {new MockResult(1)}; + } + lastRedemptionSql = sql; + if (row == null || !"ISSUED".equals(row.status)) { + return new MockResult[] {new MockResult(0)}; + } + OffsetDateTime now = timestampBinding(bind[7]); + if (!row.referenceExpiresAt.isAfter(now)) { + return new MockResult[] {new MockResult(0)}; + } + row.redeemer = (String) bind[0]; + row.ownerAttempt = (UUID) bind[1]; + row.ownerFence = (Long) bind[2]; + row.redeemedAt = timestampBinding(bind[3]); + row.redemptionFingerprint = (String) bind[4]; + row.redemptionBundle = ((byte[]) bind[5]).clone(); + row.status = "REDEEMED"; + redemptionUpdateCount.incrementAndGet(); + return new MockResult[] {new MockResult(1)}; + } + if (sql.startsWith("select ")) { + if (sql.contains("for update")) { + lastLockSql = sql; + } + return new MockResult[] {row == null ? emptyResult() : rowResult(row)}; + } + throw new SQLException("Unexpected SQL in MockStore: " + sql); + } + + private static MockResult emptyResult() { + return new MockResult(0, result(null)); + } + + private static MockResult rowResult(StoredRow row) { + return new MockResult(1, result(row)); + } + + private static Result result(StoredRow value) { + Result result = + DSL.using(SQLDialect.POSTGRES) + .newResult( + REQUEST_ID, + TUPLE, + DIGEST, + ISSUER, + RESERVATION_OWNER, + RESERVATION_FENCE, + OPERATION_ID, + ISSUANCE_FENCE, + BUNDLE_VERSION, + BUNDLE_SOURCE_VERSION, + BUNDLE_SOURCE_FENCE, + BUNDLE_LINEARIZATION, + BUNDLE, + FINGERPRINT, + ENVELOPE, + ENVELOPE_ERASED_AT, + ISSUED_AT, + REFERENCE_EXPIRY, + ENVELOPE_EXPIRY, + STATUS, + REDEEMER, + OWNER_ATTEMPT, + OWNER_FENCE, + REDEEMED_AT, + REDEMPTION_FINGERPRINT, + REDEMPTION_BUNDLE); + if (value == null) { + return result; + } + Record record = DSL.using(SQLDialect.POSTGRES).newRecord(result.fields()); + record.setValue(REQUEST_ID, value.requestId); + record.setValue(TUPLE, value.tuple.clone()); + record.setValue(DIGEST, value.digest); + record.setValue(ISSUER, value.issuer); + record.setValue(RESERVATION_OWNER, value.reservationOwner); + record.setValue(RESERVATION_FENCE, value.reservationFence); + record.setValue(OPERATION_ID, value.operationId); + record.setValue(ISSUANCE_FENCE, value.issuanceFence); + record.setValue(BUNDLE_VERSION, value.bundleReference.bundleVersion()); + record.setValue(BUNDLE_SOURCE_VERSION, value.bundleReference.sourceVersion()); + record.setValue(BUNDLE_SOURCE_FENCE, value.bundleReference.sourceFence()); + record.setValue(BUNDLE_LINEARIZATION, value.bundleReference.linearization()); + record.setValue(BUNDLE, value.bundle.clone()); + record.setValue(FINGERPRINT, value.fingerprint); + record.setValue(ENVELOPE, value.envelope == null ? null : value.envelope.clone()); + record.setValue(ENVELOPE_ERASED_AT, value.responseEnvelopeErasedAt); + record.setValue(ISSUED_AT, value.issuedAt); + record.setValue(REFERENCE_EXPIRY, value.referenceExpiresAt); + record.setValue(ENVELOPE_EXPIRY, value.envelopeExpiresAt); + record.setValue(STATUS, value.status); + record.setValue(REDEEMER, value.redeemer); + record.setValue(OWNER_ATTEMPT, value.ownerAttempt); + record.setValue(OWNER_FENCE, value.ownerFence); + record.setValue(REDEEMED_AT, value.redeemedAt); + record.setValue(REDEMPTION_FINGERPRINT, value.redemptionFingerprint); + record.setValue( + REDEMPTION_BUNDLE, + value.redemptionBundle == null ? null : value.redemptionBundle.clone()); + result.add(record); + return result; + } + } + + private static final class StoredRow { + private final String requestId; + private final byte[] tuple; + private final String digest; + private final String issuer; + private final UUID reservationOwner; + private final Long reservationFence; + private final UUID operationId; + private final Long issuanceFence; + private final BundleReference bundleReference; + private final byte[] bundle; + private final String fingerprint; + private byte[] envelope; + private final OffsetDateTime issuedAt; + private final OffsetDateTime referenceExpiresAt; + private final OffsetDateTime envelopeExpiresAt; + private OffsetDateTime responseEnvelopeErasedAt; + private String status = "ISSUED"; + private String redeemer; + private UUID ownerAttempt; + private Long ownerFence; + private OffsetDateTime redeemedAt; + private String redemptionFingerprint; + private byte[] redemptionBundle; + + private StoredRow( + String requestId, + byte[] tuple, + String digest, + String issuer, + UUID reservationOwner, + Long reservationFence, + UUID operationId, + Long issuanceFence, + BundleReference bundleReference, + byte[] bundle, + String fingerprint, + byte[] envelope, + OffsetDateTime issuedAt, + OffsetDateTime referenceExpiresAt, + OffsetDateTime envelopeExpiresAt) { + this.requestId = requestId; + this.tuple = tuple.clone(); + this.digest = digest; + this.issuer = issuer; + this.reservationOwner = reservationOwner; + this.reservationFence = reservationFence; + this.operationId = operationId; + this.issuanceFence = issuanceFence; + this.bundleReference = bundleReference; + this.bundle = bundle.clone(); + this.fingerprint = fingerprint; + this.envelope = envelope.clone(); + this.issuedAt = issuedAt; + this.referenceExpiresAt = referenceExpiresAt; + this.envelopeExpiresAt = envelopeExpiresAt; + } + + private static StoredRow fromInsert(Object[] bind) { + return new StoredRow( + (String) bind[0], + (byte[]) bind[1], + (String) bind[2], + (String) bind[3], + (UUID) bind[4], + (Long) bind[5], + (UUID) bind[6], + (Long) bind[7], + new BundleReference( + (String) bind[8], (String) bind[9], (String) bind[10], (String) bind[11]), + (byte[]) bind[12], + (String) bind[13], + (byte[]) bind[14], + timestampBinding(bind[15]), + timestampBinding(bind[16]), + timestampBinding(bind[17])); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java index e4c688060e..177df1b335 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java @@ -47,6 +47,14 @@ class RuntimeAccountIdentityGrpcAuthWiringTest { private static final String IDENTITY_METHOD = "account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity"; + private static final String START_SESSION_ISSUE_METHOD = + "account.v1.StartSessionOperatorAuthorizationService/IssueHumanOperatorAuthorizationReference"; + private static final String START_SESSION_RECOVER_METHOD = + "account.v1.StartSessionOperatorAuthorizationService/RecoverOperatorAuthorizationReference"; + private static final String START_SESSION_REDEEM_METHOD = + "account.v1.StartSessionOperatorAuthorizationService/RedeemOperatorAuthorization"; + private static final String READ_REDEEMED_OPERATION_PROJECTION_METHOD = + "account.v1.StartSessionOperatorAuthorizationService/ReadRedeemedOperationProjection"; private static final String NONPUBLIC_METHOD = "account.v1.AccountService/GetProfile"; private static final String ACCOUNT_UUID = "87426bb3-a733-43f0-9c8e-2e379cbdf7ec"; private static final String REQUEST_UUID = "11111111-1111-4111-8111-111111111111"; @@ -272,6 +280,12 @@ private static void withConfiguredInterceptor( assertThat(context).hasSingleBean(AuthTokenInterceptor.class); assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) .contains(IDENTITY_METHOD) + .contains( + START_SESSION_ISSUE_METHOD, + START_SESSION_RECOVER_METHOD, + START_SESSION_REDEEM_METHOD, + READ_REDEEMED_OPERATION_PROJECTION_METHOD) + .doesNotContain("account.v1.StartSessionOperatorAuthorizationService/*") .doesNotContain(NONPUBLIC_METHOD); action.accept( context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java new file mode 100644 index 0000000000..ebd2671644 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java @@ -0,0 +1,237 @@ +package unit.net.firedevops.firemud.accountservice.service.impl; + +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.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt; +import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtSignerMaterializationService; +import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class AccountJwtSignerMaterializationServiceTest { + private static final Binding TRUST = materializerTrustBinding(); + + private final AccountJwtSignerDesiredStateRepository repository = mock(); + private final AccountJwtReadinessProbeRepository readinessRepository = mock(); + private final AccountJwtSignerMaterializerTrustBinding trustBindingProvider = mock(); + private final AccountJwtValidatorInventorySource inventorySource = mock(); + private final PlatformTransactionManager transactionManager = mock(); + + @Test + void rejectsRetainedPreparedRecoveryBeforeDispatchWhenCoordinatorIsAbsent() { + PreparedGenerationEvidence retainedPrepared = mock(); + when(repository.readPreparedGenerationForRecovery(any(), any())).thenReturn(retainedPrepared); + when(trustBindingProvider.current()).thenReturn(Optional.of(TRUST)); + StaticListableBeanFactory beans = beanFactoryWithInventory(); + ObjectProvider coordinatorProvider = + beans.getBeanProvider(AccountJwtSignerBootstrapCoordinator.class); + ObjectProvider inventoryProvider = + beans.getBeanProvider(AccountJwtValidatorInventorySource.class); + AccountJwtSignerMaterializationService service = + new AccountJwtSignerMaterializationService( + repository, + readinessRepository, + trustBindingProvider, + transactionManager, + coordinatorProvider, + inventoryProvider); + Observer observer = new Observer<>(); + + authenticate(TRUST) + .run( + () -> + service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + observer)); + + assertFailedPrecondition(observer.failure); + verify(repository, never()).readPreparedGenerationForRecovery(any(), any()); + verify(repository, never()).readAndMarkPreparedPromotionDispatched(any(), any()); + verifyNoInteractions(readinessRepository, inventorySource, transactionManager); + verify(trustBindingProvider).current(); + } + + @Test + void rejectsPrivatePromotionResultBeforePersistingReceiptWhenCoordinatorIsAbsent() { + when(trustBindingProvider.current()).thenReturn(Optional.of(TRUST)); + StaticListableBeanFactory beans = beanFactoryWithInventory(); + ObjectProvider coordinatorProvider = + beans.getBeanProvider(AccountJwtSignerBootstrapCoordinator.class); + ObjectProvider inventoryProvider = + beans.getBeanProvider(AccountJwtValidatorInventorySource.class); + AccountJwtSignerMaterializationService service = + new AccountJwtSignerMaterializationService( + repository, + readinessRepository, + trustBindingProvider, + transactionManager, + coordinatorProvider, + inventoryProvider); + Observer observer = new Observer<>(); + RecordPrivatePromotionResultRequest request = + RecordPrivatePromotionResultRequest.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(UUID.randomUUID().toString()) + .setGenerationOperationId(UUID.randomUUID().toString()) + .setCurrent( + net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity.getDefaultInstance()) + .build(); + + authenticate(TRUST).run(() -> service.recordPrivatePromotionResult(request, observer)); + + assertFailedPrecondition(observer.failure); + verifyNoInteractions(repository, readinessRepository, inventorySource, transactionManager); + verify(trustBindingProvider).current(); + } + + @Test + void recordsPrivatePromotionResultAndReconcilesWhenCoordinatorIsConfigured() { + when(trustBindingProvider.current()).thenReturn(Optional.of(TRUST)); + when(transactionManager.getTransaction(any())).thenReturn(new SimpleTransactionStatus()); + UUID promotionOperationId = UUID.randomUUID(); + UUID generationOperationId = UUID.randomUUID(); + String digest = "b".repeat(64); + PrivatePromotionReceipt receipt = + new PrivatePromotionReceipt(promotionOperationId, generationOperationId, "2", digest); + when(repository.recordPrivatePromotionResult(any(), any(), any())).thenReturn(receipt); + AccountJwtSignerBootstrapCoordinator coordinator = mock(); + StaticListableBeanFactory beans = beanFactoryWithInventory(); + beans.addBean("jwtSignerBootstrapCoordinator", coordinator); + ObjectProvider coordinatorProvider = + beans.getBeanProvider(AccountJwtSignerBootstrapCoordinator.class); + ObjectProvider inventoryProvider = + beans.getBeanProvider(AccountJwtValidatorInventorySource.class); + AccountJwtSignerMaterializationService service = + new AccountJwtSignerMaterializationService( + repository, + readinessRepository, + trustBindingProvider, + transactionManager, + coordinatorProvider, + inventoryProvider); + Observer observer = new Observer<>(); + RecordPrivatePromotionResultRequest request = + RecordPrivatePromotionResultRequest.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(promotionOperationId.toString()) + .setPromotionRequestDigest(digest) + .setGenerationOperationId(generationOperationId.toString()) + .setGenerationOperationDigest(digest) + .setSecretUid("33333333-3333-4333-8333-333333333333") + .setExpectedPriorResourceVersion("1") + .setObservedResourceVersion("2") + .setCurrent( + net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity.newBuilder() + .setGeneration("1") + .setKid("key-1") + .setPublicKeyFingerprint(digest)) + .addResultingSlots("current") + .build(); + + authenticate(TRUST).run(() -> service.recordPrivatePromotionResult(request, observer)); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + assertThat(observer.value.getPromotionOperationId()).isEqualTo(promotionOperationId.toString()); + assertThat(observer.value.getPublicReceiptDigest()).isEqualTo(receipt.receiptDigest()); + verify(coordinator) + .reconcilePreparedPromotionOnce( + org.mockito.ArgumentMatchers.argThat( + (PrivatePromotionObservation observation) -> + observation.promotionOperationId().equals(promotionOperationId)), + org.mockito.ArgumentMatchers.eq(receipt)); + } + + private StaticListableBeanFactory beanFactoryWithInventory() { + StaticListableBeanFactory beans = new StaticListableBeanFactory(); + beans.addBean("validatorInventorySource", inventorySource); + return beans; + } + + private static Context authenticate(Binding binding) { + @SuppressWarnings("unchecked") + Context.Key authenticatedBindingKey = + (Context.Key) + ReflectionTestUtils.getField( + AccountJwtSignerMaterializerTlsInterceptor.class, "AUTHENTICATED_BINDING"); + return Context.current().withValue(authenticatedBindingKey, binding); + } + + private static Binding materializerTrustBinding() { + String environmentId = "prod"; + String clusterId = "prod-cluster-1"; + String namespace = "firemud-prod"; + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + String peerUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-signer-materializer"; + List pins = List.of("a".repeat(64)); + String revision = "materializer-r1"; + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, environmentId, clusterId, namespace, clusterUid, namespaceUid, peerUri, pins); + return new Binding( + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + peerUri, + pins, + revision, + digest); + } + + private static void assertFailedPrecondition(Status failure) { + assertThat(failure).isNotNull(); + assertThat(failure.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + } + + private static final class Observer implements StreamObserver { + private T value; + private Status failure; + private boolean completed; + + @Override + public void onNext(T value) { + this.value = value; + } + + @Override + public void onError(Throwable throwable) { + failure = Status.fromThrowable(throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java new file mode 100644 index 0000000000..43b12e5b5a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java @@ -0,0 +1,697 @@ +package unit.net.firedevops.firemud.accountservice.service.impl; + +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.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Constructor; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest; +import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; +import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorityBundle; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.AuthorizationResponse; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.IssueRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RecoverRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.core.io.FileSystemResource; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.util.StreamUtils; + +class StartSessionOperatorAuthorizationGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String LOGGING_URI = "spiffe://firemud/ns/test/sa/logging-admin-service"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String CONTROL_UI_JWT = "eyJhbGciOiJub25lIn0.eyJzdWIiOiJ0ZXN0In0.signature"; + private static final String AUTHORIZATION_REFERENCE = "A".repeat(43); + private static final String FINGERPRINT = "arfp/v1/key-1/" + "a".repeat(64); + private static final UUID ACTOR_ID = UUID.fromString("6bbab35c-06fd-41f8-b340-989305201e49"); + private static final UUID TENANT_ID = UUID.fromString("37e21e06-af7e-4241-9c24-6dff3501d242"); + private static final UUID TARGET_ACCOUNT_ID = + UUID.fromString("f806636f-792b-4a23-a736-92ea1f48340b"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("e6c28d8f-775c-4ea4-af84-fd53a03b0a32"); + private static final UUID RECOVERY_OWNER_ID = + UUID.fromString("5e377426-603e-4bfb-a1a0-3f784881aab4"); + private static final UUID OWNER_ATTEMPT_ID = + UUID.fromString("43221254-3728-47a4-b15d-37542871e685"); + private static final UUID ISSUANCE_OPERATION_ID = + UUID.fromString("4fa8b657-c6ed-4797-b61d-66083f582198"); + private final AccountStartSessionOperatorAuthorizationService ownerService = + mock(AccountStartSessionOperatorAuthorizationService.class); + private final StartSessionOperatorAuthorizationGrpcService service = + new StartSessionOperatorAuthorizationGrpcService(ownerService, NAMESPACE); + + @AfterEach + void clearAuthenticatedContext() { + SessionContext.clear(); + } + + @Test + void grpcRegistrationIsExplicitlyOptIn() throws IOException { + ConditionalOnProperty condition = + StartSessionOperatorAuthorizationGrpcService.class.getAnnotation( + ConditionalOnProperty.class); + + assertThat(condition).isNotNull(); + assertThat(condition.prefix()) + .isEqualTo("firemud.account.start-session-operator-authorization"); + assertThat(condition.name()).containsExactly("enabled"); + assertThat(condition.havingValue()).isEqualTo("true"); + assertThat(condition.matchIfMissing()).isFalse(); + + try (InputStream input = + new FileSystemResource("src/main/resources/application.yml").getInputStream()) { + String applicationConfiguration = StreamUtils.copyToString(input, StandardCharsets.UTF_8); + assertThat(applicationConfiguration) + .contains( + "start-session-operator-authorization:\n" + + " enabled: " + + "${FIREMUD_ACCOUNT_START_SESSION_OPERATOR_AUTHORIZATION_ENABLED:false}"); + } + } + + @Test + void issueRecoverAndRedeemMapExactTypedInputsAndResponses() { + byte[] tupleBytes = canonicalTupleBytes(); + AuthorizationResponse authorization = authorizationResponse(); + when(ownerService.issue(any())).thenReturn(authorization); + when(ownerService.recover(any())).thenReturn(authorization); + when(ownerService.redeem(any())) + .thenReturn( + new RedemptionResult( + FINGERPRINT, bytes("redemption-bundle"), ISSUANCE_OPERATION_ID, 9L, true)); + + TestObserver issueObserver = + callIssue(issueRequest(tupleBytes), LOGGING_URI); + assertThat(issueObserver.failure).isNull(); + assertThat(issueObserver.completed).isTrue(); + assertThat(issueObserver.value.getOperatorAuthorizationReference()) + .isEqualTo(AUTHORIZATION_REFERENCE); + assertThat(issueObserver.value.getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(issueObserver.value.getExpiresAt().getSeconds()) + .isEqualTo(Instant.parse("2026-10-09T00:03:00Z").getEpochSecond()); + assertThat(issueObserver.value.getAuthorityEvidenceBundle().toByteArray()) + .containsExactly(bytes("authority-bundle")); + assertThat(issueObserver.value.getBundleReference().getBundleVersion()) + .isEqualTo(AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION); + assertThat(issueObserver.value.getBundleReference().getSourceVersion()).isEqualTo("17"); + assertThat(issueObserver.value.getBundleReference().getSourceFence()).isEqualTo("4"); + assertThat(issueObserver.value.getBundleReference().getLinearization()).isEqualTo("3"); + assertThat(issueObserver.value.getAuthenticatedLoggingWorkloadIdentity()) + .isEqualTo(LOGGING_URI); + + var issueCaptor = org.mockito.ArgumentCaptor.forClass(IssueRequest.class); + verify(ownerService).issue(issueCaptor.capture()); + assertThat(issueCaptor.getValue().controlUiJwt()).isEqualTo(CONTROL_UI_JWT); + assertThat(issueCaptor.getValue().canonicalTupleBytes()).containsExactly(tupleBytes); + assertThat(issueCaptor.getValue().reservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID); + assertThat(issueCaptor.getValue().reservationClaimFence()).isEqualTo(3L); + assertThat(issueCaptor.getValue().claimOwnerId()).isEqualTo(RESERVATION_OWNER_ID); + assertThat(issueCaptor.getValue().claimFence()).isEqualTo(3L); + assertThat(issueCaptor.getValue().toString()).doesNotContain(CONTROL_UI_JWT); + + TestObserver recoverObserver = + callRecover(recoverRequest(tupleBytes), LOGGING_URI); + assertThat(recoverObserver.failure).isNull(); + assertThat(recoverObserver.value.getOperatorAuthorizationReference()) + .isEqualTo(AUTHORIZATION_REFERENCE); + assertThat(recoverObserver.value.getAuthenticatedLoggingWorkloadIdentity()) + .isEqualTo(LOGGING_URI); + var recoverCaptor = org.mockito.ArgumentCaptor.forClass(RecoverRequest.class); + verify(ownerService).recover(recoverCaptor.capture()); + assertThat(recoverCaptor.getValue().canonicalTupleBytes()).containsExactly(tupleBytes); + assertThat(recoverCaptor.getValue().reservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID); + assertThat(recoverCaptor.getValue().reservationClaimFence()).isEqualTo(3L); + assertThat(recoverCaptor.getValue().claimOwnerId()).isEqualTo(RECOVERY_OWNER_ID); + assertThat(recoverCaptor.getValue().claimFence()).isEqualTo(5L); + + TestObserver redeemObserver = + callRedeem(redeemRequest(tupleBytes), GAME_SESSION_URI); + assertThat(redeemObserver.failure).isNull(); + assertThat(redeemObserver.value.getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(redeemObserver.value.getAuthorityEvidenceBundle().toByteArray()) + .containsExactly(bytes("redemption-bundle")); + assertThat(redeemObserver.value.getIssuanceOperationId()) + .isEqualTo(ISSUANCE_OPERATION_ID.toString()); + assertThat(redeemObserver.value.getIssuanceFence()).isEqualTo(9L); + assertThat(redeemObserver.value.getReplay()).isTrue(); + var redeemCaptor = org.mockito.ArgumentCaptor.forClass(RedeemRequest.class); + verify(ownerService).redeem(redeemCaptor.capture()); + assertThat(redeemCaptor.getValue().canonicalTupleBytes()).containsExactly(tupleBytes); + assertThat(redeemCaptor.getValue().operatorAuthorizationReference()) + .isEqualTo(AUTHORIZATION_REFERENCE); + assertThat(redeemCaptor.getValue().authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(redeemCaptor.getValue().reservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID); + assertThat(redeemCaptor.getValue().reservationClaimFence()).isEqualTo(3L); + assertThat(redeemCaptor.getValue().ownerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID); + assertThat(redeemCaptor.getValue().ownerFence()).isEqualTo(11L); + assertThat(redeemCaptor.getValue().toString()) + .doesNotContain(AUTHORIZATION_REFERENCE, FINGERPRINT); + } + + @Test + void readsExactRedeemedOperationProjectionWithoutCredentialMaterial() { + byte[] tupleBytes = canonicalTupleBytes(); + when(ownerService.readRedeemedOperationProjection(any())) + .thenReturn(redeemedOperationProjection(tupleBytes)); + + TestObserver observer = + callReadProjection(readProjectionRequest(tupleBytes), GAME_DESIGN_URI); + + assertThat(observer.failure).isNull(); + assertThat(observer.completed).isTrue(); + ReadRedeemedOperationProjectionResponse response = observer.value; + assertThat(response.getControlPlaneRequestId()).isEqualTo("start-session/operator/βeta"); + assertThat(response.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tupleBytes); + assertThat(response.getMutationDigest()) + .isEqualTo( + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(tupleBytes, StandardCharsets.UTF_8)) + .mutationDigest()); + assertThat(response.getAuthorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(response.getReservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(response.getReservationClaimFence()).isEqualTo(3L); + assertThat(response.getAuthenticatedRedeemerWorkloadIdentity()).isEqualTo(GAME_SESSION_URI); + assertThat(response.getOwnerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID.toString()); + assertThat(response.getOwnerFence()).isEqualTo(11L); + assertThat(response.getReferenceExpiresAt().getSeconds()) + .isEqualTo(Instant.parse("2026-10-09T00:03:00Z").getEpochSecond()); + assertThat(response.getRedeemedAt().getSeconds()) + .isEqualTo(Instant.parse("2026-10-09T00:02:00Z").getEpochSecond()); + assertThat(response.getIssuanceOperationId()).isEqualTo(ISSUANCE_OPERATION_ID.toString()); + assertThat(response.getIssuanceFence()).isEqualTo(9L); + assertThat(response.getBundleReference().getBundleVersion()) + .isEqualTo(AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION); + assertThat(response.getBundleReference().getSourceVersion()).isEqualTo("17"); + assertThat(response.getBundleReference().getSourceFence()).isEqualTo("4"); + assertThat(response.getBundleReference().getLinearization()).isEqualTo("3"); + assertThat(response.getAuthorityEvidenceBundle().toByteArray()) + .containsExactly(bytes("authority-bundle")); + assertThat(response.toString()).doesNotContain(CONTROL_UI_JWT, AUTHORIZATION_REFERENCE); + + var readCaptor = + org.mockito.ArgumentCaptor.forClass( + AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest + .class); + verify(ownerService).readRedeemedOperationProjection(readCaptor.capture()); + assertThat(readCaptor.getValue().canonicalPreAuthorizationTuple()).containsExactly(tupleBytes); + assertThat(readCaptor.getValue().authorizationReferenceFingerprint()).isEqualTo(FINGERPRINT); + assertThat(readCaptor.getValue().reservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID); + assertThat(readCaptor.getValue().reservationClaimFence()).isEqualTo(3L); + assertThat(readCaptor.getValue().ownerAttemptId()).isEqualTo(OWNER_ATTEMPT_ID); + assertThat(readCaptor.getValue().ownerFence()).isEqualTo(11L); + verifyNoMoreInteractions(ownerService); + } + + @Test + void deniesWrongPeerBeforeParsingAndRejectsMalformedProjectionRead() { + ReadRedeemedOperationProjectionRequest malformed = + readProjectionRequest(new byte[] {(byte) 0xc3, 0x28}); + for (String peerUri : + new String[] { + null, + "spiffe://firemud/ns/other/sa/game-design-service", + GAME_SESSION_URI, + LOGGING_URI, + ACCOUNT_URI + }) { + assertThat(status(callReadProjection(malformed, peerUri))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + + assertThat(status(callReadProjection(malformed, GAME_DESIGN_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + callReadProjection( + readProjectionRequest(canonicalTupleBytes()).toBuilder() + .setUnknownFields(unknownFields()) + .build(), + GAME_DESIGN_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat( + status( + callReadProjection( + readProjectionRequest(canonicalTupleBytes()).toBuilder() + .setOwnerFence(0L) + .build(), + GAME_DESIGN_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(ownerService); + } + + @Test + void rejectsWrongOrMissingPeersBeforeParsingOrInvokingOwnerService() { + IssueHumanOperatorAuthorizationReferenceRequest malformedIssue = + issueRequest(new byte[] {(byte) 0xc3, 0x28}); + for (String peerUri : + new String[] { + null, + "spiffe://firemud/ns/other/sa/logging-admin-service", + "spiffe://firemud/ns/test/sa/game-session-service", + ACCOUNT_URI + }) { + assertThat(status(callIssue(malformedIssue, peerUri))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat( + status( + callRecover( + recoverRequest(canonicalTupleBytes()), + "spiffe://firemud/ns/other/sa/logging-admin-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + status( + callRedeem( + redeemRequest(canonicalTupleBytes()), + "spiffe://firemud/ns/test/sa/logging-admin-service"))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + + StartSessionOperatorAuthorizationGrpcService unconfigured = + new StartSessionOperatorAuthorizationGrpcService(ownerService, ""); + TestObserver unconfiguredObserver = + callIssue(unconfigured, malformedIssue, LOGGING_URI); + assertThat(status(unconfiguredObserver)).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(ownerService); + } + + @Test + void rejectsAuthenticatedCallerContextBeforeParsingOrInvokingOwnerService() { + SessionContext.setContext(ACTOR_ID.toString(), List.of("tenantAdmin"), Map.of()); + + assertThat(status(callIssue(issueRequest(new byte[] {0x01}), LOGGING_URI))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(ownerService); + } + + @Test + void sanitizesUnavailableOwnerFailureWithoutExposingItsDetails() { + when(ownerService.issue(any())) + .thenThrow( + Status.UNAVAILABLE.withDescription("private downstream detail").asRuntimeException()); + + TestObserver observer = + callIssue(issueRequest(canonicalTupleBytes()), LOGGING_URI); + + assertThat(status(observer)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observer.failure.getDescription()) + .isEqualTo("Account operator authorization is temporarily unavailable") + .doesNotContain("private downstream detail"); + } + + @Test + void mapsAccountKeyAndCryptographyUnavailabilityToSanitizedUnavailable() { + List> unavailableTypes = + List.of( + AccountOperatorAuthorizationFingerprintKeyring.KeyUnavailableException.class, + AccountResponseEnvelopeKeyring.KeyUnavailableException.class, + AccountResponseEnvelopeCryptography.CryptographyUnavailableException.class); + + for (Class unavailableType : unavailableTypes) { + AccountStartSessionOperatorAuthorizationService unavailableOwner = + mock(AccountStartSessionOperatorAuthorizationService.class); + RuntimeException unavailable = runtimeFailureWithPrivateCause(unavailableType); + when(unavailableOwner.issue(any())).thenThrow(unavailable); + var unavailableService = + new StartSessionOperatorAuthorizationGrpcService(unavailableOwner, NAMESPACE); + + TestObserver observer = + callIssue(unavailableService, issueRequest(canonicalTupleBytes()), LOGGING_URI); + + assertThat(status(observer)).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(observer.failure.getDescription()) + .isEqualTo("Account operator authorization is temporarily unavailable") + .doesNotContain(unavailableType.getSimpleName(), "private failure detail"); + assertThat(observer.failureHasCause).isFalse(); + } + } + + @Test + void mapsSpringDataAccessFailuresBySqlStateAndSanitizesThem() { + List> failures = + List.of( + Map.entry( + new DataAccessResourceFailureException( + "private connection detail", new SQLException("private", "08006")), + Status.Code.UNAVAILABLE), + Map.entry( + new DataAccessResourceFailureException( + "private constraint detail", new SQLException("private", "23505")), + Status.Code.INTERNAL)); + + for (Map.Entry entry : failures) { + AccountStartSessionOperatorAuthorizationService failingOwner = + mock(AccountStartSessionOperatorAuthorizationService.class); + when(failingOwner.issue(any())).thenThrow(entry.getKey()); + var receiver = new StartSessionOperatorAuthorizationGrpcService(failingOwner, NAMESPACE); + + TestObserver observer = + callIssue(receiver, issueRequest(canonicalTupleBytes()), LOGGING_URI); + + assertThat(status(observer)).isEqualTo(entry.getValue()); + assertThat(observer.failure.getDescription()) + .doesNotContain("private connection detail", "private constraint detail"); + } + } + + @Test + void mapsExpiredResponseRecoveryToTerminalPreconditionAndUnexpectedRuntimeToInternal() { + AccountStartSessionOperatorAuthorizationService expiredOwner = + mock(AccountStartSessionOperatorAuthorizationService.class); + when(expiredOwner.recover(any())) + .thenThrow( + runtimeFailureWithPrivateCause( + AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException.class)); + var expiredReceiver = new StartSessionOperatorAuthorizationGrpcService(expiredOwner, NAMESPACE); + TestObserver expired = + callRecover(expiredReceiver, recoverRequest(canonicalTupleBytes()), LOGGING_URI); + + AccountStartSessionOperatorAuthorizationService unexpectedOwner = + mock(AccountStartSessionOperatorAuthorizationService.class); + when(unexpectedOwner.issue(any())).thenThrow(new RuntimeException("private owner detail")); + var unexpectedReceiver = + new StartSessionOperatorAuthorizationGrpcService(unexpectedOwner, NAMESPACE); + TestObserver unexpected = + callIssue(unexpectedReceiver, issueRequest(canonicalTupleBytes()), LOGGING_URI); + + assertThat(status(expired)).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(expired.failure.getDescription()) + .isEqualTo("Original StartSession authorization response is no longer recoverable") + .doesNotContain("private owner detail"); + assertThat(status(unexpected)).isEqualTo(Status.Code.INTERNAL); + assertThat(unexpected.failure.getDescription()) + .isEqualTo("Account operator authorization could not be completed") + .doesNotContain("private owner detail"); + } + + @Test + void mapsCurrentAuthorityStateSeparatelyFromMalformedOwnerInput() { + AccountStartSessionOperatorAuthorizationService staleAuthorityOwner = + mock(AccountStartSessionOperatorAuthorizationService.class); + when(staleAuthorityOwner.issue(any())) + .thenThrow(new IllegalStateException("current Account authority changed")); + var staleAuthorityService = + new StartSessionOperatorAuthorizationGrpcService(staleAuthorityOwner, NAMESPACE); + TestObserver staleAuthority = + callIssue(staleAuthorityService, issueRequest(canonicalTupleBytes()), LOGGING_URI); + + AccountStartSessionOperatorAuthorizationService malformedOwner = + mock(AccountStartSessionOperatorAuthorizationService.class); + when(malformedOwner.issue(any())) + .thenThrow(new IllegalArgumentException("malformed decoded authority bundle")); + var malformedService = + new StartSessionOperatorAuthorizationGrpcService(malformedOwner, NAMESPACE); + TestObserver malformed = + callIssue(malformedService, issueRequest(canonicalTupleBytes()), LOGGING_URI); + + assertThat(status(staleAuthority)).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(staleAuthority.failure.getDescription()) + .isEqualTo("Current Account authorization evidence is unavailable"); + assertThat(status(malformed)).isEqualTo(Status.Code.INVALID_ARGUMENT); + assertThat(malformed.failure.getDescription()) + .isEqualTo("StartSession authorization input is invalid"); + } + + @Test + void rejectsMalformedUnknownAndOverBoundRequestsBeforeInvokingOwnerService() { + byte[] tupleBytes = canonicalTupleBytes(); + List invalidIssues = + List.of( + issueRequest(tupleBytes).toBuilder().setUnknownFields(unknownFields()).build(), + issueRequest(new byte[] {(byte) 0xc3, 0x28}), + issueRequest(new byte[8 * 1024 + 1]), + issueRequest(tupleBytes).toBuilder().setControlUiJwt("x".repeat(16 * 1024 + 1)).build(), + issueRequest(tupleBytes).toBuilder().setReservationOwnerId("not-a-uuid").build(), + issueRequest(tupleBytes).toBuilder() + .setReservationOwnerId("00000000-0000-0000-0000-000000000000") + .build(), + issueRequest(tupleBytes).toBuilder().setReservationClaimFence(0L).build(), + issueRequest(tupleBytes).toBuilder().setCurrentClaimFence(-1L).build()); + for (IssueHumanOperatorAuthorizationReferenceRequest invalid : invalidIssues) { + assertThat(status(callIssue(invalid, LOGGING_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + + List invalidRecoveries = + List.of( + recoverRequest(tupleBytes).toBuilder().setUnknownFields(unknownFields()).build(), + recoverRequest(new byte[] {(byte) 0xc3, 0x28}), + recoverRequest(tupleBytes).toBuilder().setCurrentClaimOwnerId("not-a-uuid").build(), + recoverRequest(tupleBytes).toBuilder().setCurrentClaimFence(-1L).build()); + for (RecoverOperatorAuthorizationReferenceRequest invalid : invalidRecoveries) { + assertThat(status(callRecover(invalid, LOGGING_URI))).isEqualTo(Status.Code.INVALID_ARGUMENT); + } + + List invalidRedemptions = + List.of( + redeemRequest(tupleBytes).toBuilder().setUnknownFields(unknownFields()).build(), + redeemRequest(new byte[] {(byte) 0xc3, 0x28}), + redeemRequest(tupleBytes).toBuilder() + .setOperatorAuthorizationReference("x".repeat(129)) + .build(), + redeemRequest(tupleBytes).toBuilder() + .setAuthorizationReferenceFingerprint("changed") + .build(), + redeemRequest(tupleBytes).toBuilder().setOwnerAttemptId("not-a-uuid").build(), + redeemRequest(tupleBytes).toBuilder().setOwnerFence(-1L).build()); + for (RedeemOperatorAuthorizationRequest invalid : invalidRedemptions) { + assertThat(status(callRedeem(invalid, GAME_SESSION_URI))) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } + verifyNoInteractions(ownerService); + } + + private TestObserver callIssue( + IssueHumanOperatorAuthorizationReferenceRequest request, String peerUri) { + return callIssue(service, request, peerUri); + } + + private TestObserver callIssue( + StartSessionOperatorAuthorizationGrpcService receiver, + IssueHumanOperatorAuthorizationReferenceRequest request, + String peerUri) { + TestObserver observer = new TestObserver<>(); + runWithPeer( + peerUri, () -> receiver.issueHumanOperatorAuthorizationReference(request, observer)); + return observer; + } + + private TestObserver callRecover( + RecoverOperatorAuthorizationReferenceRequest request, String peerUri) { + return callRecover(service, request, peerUri); + } + + private TestObserver callRecover( + StartSessionOperatorAuthorizationGrpcService receiver, + RecoverOperatorAuthorizationReferenceRequest request, + String peerUri) { + TestObserver observer = new TestObserver<>(); + runWithPeer(peerUri, () -> receiver.recoverOperatorAuthorizationReference(request, observer)); + return observer; + } + + private TestObserver callRedeem( + RedeemOperatorAuthorizationRequest request, String peerUri) { + TestObserver observer = new TestObserver<>(); + runWithPeer(peerUri, () -> service.redeemOperatorAuthorization(request, observer)); + return observer; + } + + private TestObserver callReadProjection( + ReadRedeemedOperationProjectionRequest request, String peerUri) { + TestObserver observer = new TestObserver<>(); + runWithPeer(peerUri, () -> service.readRedeemedOperationProjection(request, observer)); + return observer; + } + + private static void runWithPeer(String peerUri, Runnable invocation) { + if (peerUri == null) { + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, null).run(invocation); + } else { + GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(peerUri).orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(invocation); + } + } + + private static IssueHumanOperatorAuthorizationReferenceRequest issueRequest(byte[] tupleBytes) { + return IssueHumanOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setControlUiJwt(CONTROL_UI_JWT) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(3L) + .setCurrentClaimOwnerId(RESERVATION_OWNER_ID.toString()) + .setCurrentClaimFence(3L) + .build(); + } + + private static RecoverOperatorAuthorizationReferenceRequest recoverRequest(byte[] tupleBytes) { + return RecoverOperatorAuthorizationReferenceRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(3L) + .setCurrentClaimOwnerId(RECOVERY_OWNER_ID.toString()) + .setCurrentClaimFence(5L) + .build(); + } + + private static RedeemOperatorAuthorizationRequest redeemRequest(byte[] tupleBytes) { + return RedeemOperatorAuthorizationRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setOperatorAuthorizationReference(AUTHORIZATION_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(3L) + .setOwnerAttemptId(OWNER_ATTEMPT_ID.toString()) + .setOwnerFence(11L) + .build(); + } + + private static ReadRedeemedOperationProjectionRequest readProjectionRequest(byte[] tupleBytes) { + return ReadRedeemedOperationProjectionRequest.newBuilder() + .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(tupleBytes)) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setReservationOwnerId(RESERVATION_OWNER_ID.toString()) + .setReservationClaimFence(3L) + .setOwnerAttemptId(OWNER_ATTEMPT_ID.toString()) + .setOwnerFence(11L) + .build(); + } + + private static RedeemedOperationProjection redeemedOperationProjection(byte[] tupleBytes) { + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + new String(tupleBytes, StandardCharsets.UTF_8)); + return new RedeemedOperationProjection( + tuple.controlPlaneRequestId(), + tupleBytes, + tuple.mutationDigest(), + FINGERPRINT, + RESERVATION_OWNER_ID, + 3L, + GAME_SESSION_URI, + OWNER_ATTEMPT_ID, + 11L, + Instant.parse("2026-10-09T00:03:00Z"), + Instant.parse("2026-10-09T00:02:00Z"), + ISSUANCE_OPERATION_ID, + 9L, + new AccountStartSessionOperatorAuthorityBundle.BundleReference( + AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION, "17", "4", "3"), + bytes("authority-bundle")); + } + + private static byte[] canonicalTupleBytes() { + StartSessionOperatorAction action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, "tenant-runtime"), + new StartSessionOperatorAction.Target(42L, TARGET_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "unit test StartSession authorization"); + return StartSessionPreAuthorizationReservationTuple.createHuman( + "start-session/operator/βeta", ACTOR_ID, action) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8); + } + + private static AuthorizationResponse authorizationResponse() { + return new AuthorizationResponse( + AUTHORIZATION_REFERENCE, + FINGERPRINT, + Instant.parse("2026-10-09T00:03:00Z"), + bytes("authority-bundle"), + new AccountStartSessionOperatorAuthorityBundle.BundleReference( + AccountStartSessionOperatorAuthorityBundle.BUNDLE_VERSION, "17", "4", "3")); + } + + private static UnknownFieldSet unknownFields() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static Status.Code status(TestObserver observer) { + assertThat(observer.failure).isNotNull(); + return observer.failure.getCode(); + } + + private static RuntimeException runtimeFailureWithPrivateCause( + Class failureType) { + try { + Constructor constructor = failureType.getDeclaredConstructor(); + constructor.setAccessible(true); + RuntimeException failure = constructor.newInstance(); + failure.initCause(new IllegalStateException("private failure detail")); + return failure; + } catch (ReflectiveOperationException failure) { + throw new AssertionError("Unable to construct focused runtime failure", failure); + } + } + + private static final class TestObserver implements StreamObserver { + private T value; + private Status failure; + private boolean failureHasCause; + private boolean completed; + + @Override + public void onNext(T response) { + value = response; + } + + @Override + public void onError(Throwable throwable) { + failureHasCause = throwable.getCause() != null; + failure = Status.fromThrowable(throwable); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java new file mode 100644 index 0000000000..abec236ea2 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java @@ -0,0 +1,295 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit Redis/TLS/ACL/WAITAOF service doubles, not physical Redis or mTLS proof. */ +class AccountControlUiCoordinationTest { + private static final String HASH = "a".repeat(64); + private static final long EXPIRY = 1791467100000L; + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void exactRetryMetadataDeclaresPhysicalReassertionAsMutatingSuccess() { + var descriptor = AccountControlUiRegistryContract.descriptor(); + assertThat(descriptor.outcomes()) + .contains( + new RedisScriptDescriptor.OutcomeSpec( + "EXACT_REASSERTED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING)); + } + + @Test + void registryDescriptorDigestMatchesClasspathLuaSource() throws Exception { + var descriptor = AccountControlUiRegistryContract.descriptor(); + var resource = + AccountControlUiCoordination.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath()); + assertThat(resource).isNotNull(); + + try (resource) { + var sourceDigest = + HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(resource.readAllBytes())); + assertThat(sourceDigest).isEqualTo(descriptor.sha256()); + } + } + + @Test + void registryLuaRejectsNonNumericExpAndDeadlineBeforeExpiryArithmetic() throws Exception { + var descriptor = AccountControlUiRegistryContract.descriptor(); + var resource = + AccountControlUiCoordination.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath()); + assertThat(resource).isNotNull(); + + try (resource) { + String source = new String(resource.readAllBytes(), StandardCharsets.UTF_8); + int expNumericGuard = source.indexOf("or type(nextRecord.exp) ~= 'number'"); + int cleanupNumericGuard = + source.indexOf("or type(nextRecord.registryCleanupDeadlineEpochMillis) ~= 'number'"); + int cleanupDeadlineArgumentMatch = + source.indexOf("or nextRecord.registryCleanupDeadlineEpochMillis ~= deadline"); + int expiryMath = + source.indexOf( + "or nextRecord.registryCleanupDeadlineEpochMillis < nextRecord.exp * 1000"); + assertThat(expNumericGuard).isGreaterThanOrEqualTo(0); + assertThat(cleanupNumericGuard).isGreaterThan(expNumericGuard); + assertThat(cleanupDeadlineArgumentMatch).isGreaterThan(cleanupNumericGuard); + assertThat(expiryMath).isGreaterThan(cleanupDeadlineArgumentMatch); + } + } + + @Test + void exactRetryStillRequiresSameConnectionWriteThenWaitAofThenExactReadback() throws Exception { + Fixture f = new Fixture(); + byte[] pending = record("pending"); + doReturn(0L) + .when(f.commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + when(f.commands.get(any(byte[].class))).thenReturn(pending); + var receipt = f.client.registerPending(HASH, pending, EXPIRY); + assertThat(receipt.tokenHash).isEqualTo(HASH); + assertThat(receipt.recordDigest).isEqualTo(AccountControlUiIssuanceRepository.hash(pending)); + var order = inOrder(f.commands); + order.verify(f.commands).aclWhoami(); + order.verify(f.commands).scriptLoad(any(byte[].class)); + order + .verify(f.commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + order.verify(f.commands).dispatch(any(), any(), any()); + order.verify(f.commands).pexpiretime(any(byte[].class)); + order.verify(f.commands).get(any(byte[].class)); + } + + @Test + void activeReadRequiresOriginalPhysicalExpiryAndNeverRepairs() throws Exception { + Fixture f = new Fixture(); + when(f.commands.get(any(byte[].class))).thenReturn(record("active")); + assertThat(f.client.readActive(HASH)).isEqualTo(record("active")); + for (Long invalid : new Long[] {null, -1L, -2L, EXPIRY + 1}) { + when(f.commands.pexpiretime(any(byte[].class))).thenReturn(invalid); + assertThatThrownBy(() -> f.client.readActive(HASH)).isInstanceOf(IllegalStateException.class); + } + } + + @Test + void recoveryRevocationKeepsOriginalFieldsAndRequiresDurableExactReadback() throws Exception { + for (String prior : List.of("pending", "active", "revoked")) { + Fixture f = new Fixture(); + var original = revoking(); + byte[] revoked = AccountControlUiIssuanceRepository.revokedRegistry(original); + var fields = AccountControlUiIssuanceRepository.object(revoked); + assertThat(fields.get("state")).isEqualTo("revoked"); + assertThat(fields.get("registryVersion")).isEqualTo(3); + assertThat(((Number) fields.get("exp")).longValue()).isEqualTo(EXPIRY / 1000); + when(f.commands.get(any(byte[].class))).thenReturn(record(prior)).thenReturn(revoked); + if (prior.equals("revoked")) { + doReturn(0L) + .when(f.commands) + .evalsha( + anyString(), + eq(ScriptOutputType.INTEGER), + any(byte[][].class), + any(byte[][].class)); + } + var receipt = f.client.revoke(original); + assertThat(receipt.recordDigest).isEqualTo(AccountControlUiIssuanceRepository.hash(revoked)); + assertThat(receipt.expiryMillis).isEqualTo(EXPIRY); + var order = inOrder(f.commands); + order.verify(f.commands).get(any(byte[].class)); + order.verify(f.commands).pexpiretime(any(byte[].class)); + order.verify(f.commands).scriptLoad(any(byte[].class)); + order + .verify(f.commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + order.verify(f.commands).dispatch(any(), any(), any()); + order.verify(f.commands).pexpiretime(any(byte[].class)); + order.verify(f.commands).get(any(byte[].class)); + } + } + + @Test + void missingChangedExpiredOrUnavailableRevocationNeverCountsAsSuccess() throws Exception { + for (byte[] observed : new byte[][] {null, record("other")}) { + Fixture f = new Fixture(); + when(f.commands.get(any(byte[].class))).thenReturn(observed); + assertThatThrownBy(() -> f.client.revoke(revoking())) + .isInstanceOf(IllegalStateException.class); + } + Fixture f = new Fixture(); + when(f.commands.get(any(byte[].class))).thenReturn(record("active")); + when(f.commands.pexpiretime(any(byte[].class))).thenReturn(-2L); + assertThatThrownBy(() -> f.client.revoke(revoking())).isInstanceOf(IllegalStateException.class); + when(f.commands.pexpiretime(any(byte[].class))).thenReturn(EXPIRY); + doReturn(-4L) + .when(f.commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + assertThatThrownBy(() -> f.client.revoke(revoking())).isInstanceOf(IllegalStateException.class); + } + + private static AccountControlUiIssuanceRepository.Stored revoking() { + // Explicit owner-record double only; not a committed producer or physical owner transaction. + Record row = mock(Record.class); + when(row.get("status", String.class)).thenReturn("REVOKING"); + when(row.get("token_hash", String.class)).thenReturn(HASH); + when(row.get("pending_registry", byte[].class)).thenReturn(record("pending")); + when(row.get("active_registry", byte[].class)).thenReturn(record("active")); + when(row.get("issued_at_epoch_second", Long.class)).thenReturn(EXPIRY / 1000 - 300); + when(row.get("expires_at_epoch_second", Long.class)).thenReturn(EXPIRY / 1000); + when(row.get("registry_cleanup_deadline_epoch_millis", Long.class)).thenReturn(EXPIRY); + when(row.get("recovery_expires_at", OffsetDateTime.class)) + .thenReturn( + OffsetDateTime.ofInstant(Instant.ofEpochMilli(EXPIRY - 240000), ZoneOffset.UTC)); + return new AccountControlUiIssuanceRepository.Stored(row); + } + + @Test + void wrongRoleMissingRecordReconnectSqlAndAcknowledgementShortfallDeny() throws Exception { + Fixture f = new Fixture(); + when(f.commands.aclWhoami()).thenReturn("game_session_coord_app"); + assertThatThrownBy(() -> f.client.readActive(HASH)).isInstanceOf(IllegalStateException.class); + when(f.commands.aclWhoami()).thenReturn("account_coord_app"); + when(f.commands.get(any(byte[].class))).thenReturn(null); + assertThatThrownBy(() -> f.client.readActive(HASH)).isInstanceOf(IllegalStateException.class); + when(f.connection.getOptions()).thenReturn(ClientOptions.builder().autoReconnect(true).build()); + assertThatThrownBy(() -> f.client.readActive(HASH)).isInstanceOf(IllegalStateException.class); + when(f.connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + doReturn(List.of(1L, 0L)).when(f.commands).dispatch(any(), any(), any()); + assertThatThrownBy(() -> f.client.registerPending(HASH, record("pending"), EXPIRY)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> f.client.readActive(HASH)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SQL locks"); + } + + private static byte[] record(String state) { + // A service-double observation only, never an authenticated actor or canonical owner bundle. + return AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry( + "registryVersion", state.equals("active") ? 2 : state.equals("revoked") ? 3 : 1), + Map.entry("tokenHash", HASH), + Map.entry("kid", "key-1"), + Map.entry("signerGeneration", "1"), + Map.entry("issuer", "firemud-account-service"), + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("accountId", "10000000-0000-4000-8000-000000000001"), + Map.entry("jti", "30000000-0000-4000-8000-000000000003"), + Map.entry("iat", EXPIRY / 1000 - 300), + Map.entry("nbf", EXPIRY / 1000 - 300), + Map.entry("exp", EXPIRY / 1000), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", Map.of("accountAuthorityGeneration", 1)), + Map.entry("membershipVersion", Map.of("20000000-0000-4000-8000-000000000002", 1)), + Map.entry("issuanceFence", 1), + Map.entry("operationId", "40000000-0000-4000-8000-000000000004"), + Map.entry("requestId", "50000000-0000-4000-8000-000000000005"), + Map.entry("requestDigest", "b".repeat(64)), + Map.entry("registryCleanupDeadlineEpochMillis", EXPIRY), + Map.entry("state", state), + Map.entry( + "authoritySourceVersions", + Map.of("ACCOUNT:10000000-0000-4000-8000-000000000001", 1)), + Map.entry("authEvidenceBundle", Map.of("bundleVersion", "1")), + Map.entry("originalSignerReceiptDigest", "c".repeat(64)))); + } + + private static final class Fixture { + @SuppressWarnings("unchecked") + final StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + + @SuppressWarnings("unchecked") + final RedisCommands commands = mock(RedisCommands.class); + + final RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + final AccountControlUiCoordination client; + + Fixture() throws Exception { + var descriptor = AccountControlUiRegistryContract.descriptor(); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()) + .thenReturn(ClientOptions.builder().autoReconnect(false).build()); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn("account_coord_app"); + when(catalog.require(AccountControlUiRegistryContract.SCRIPT_ID)).thenReturn(descriptor); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> + AccountControlUiCoordination.digest("SHA-1", invocation.getArgument(0))); + doReturn(1L) + .when(commands) + .evalsha( + anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class)); + doReturn(List.of(1L, 1L)).when(commands).dispatch(any(), any(), any()); + when(commands.pexpiretime(any(byte[].class))).thenReturn(EXPIRY); + client = + new AccountControlUiCoordination( + () -> connection, new AcknowledgementRequirements(1, 1, 1000), catalog); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java new file mode 100644 index 0000000000..25da63c4fd --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java @@ -0,0 +1,1096 @@ +package unit.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.ArgumentMatchers.eq; +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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneId; +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.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +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.dto.DemoTenantEntitlementEventV1Codec; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.entity.AccountTenantMembership; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository.CommittedIssuance; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.OriginalCommittedSignerEvidence; +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.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiCurrentActorVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiRegistryReader; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec; +import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot; +import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.json.JsonMapper; + +/** + * Full verifier unit proof. Owner repositories and protected signer/JWKS bindings are mocked at + * their public seams; this does not claim physical PostgreSQL, Redis, or Kubernetes integration + * authority. + */ +class AccountControlUiCurrentActorVerifierTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String ISSUER = "firemud-account-service"; + private static final String KID = "control-ui-key"; + private static final String ENVIRONMENT = "test"; + private static final String CLUSTER = "cluster-test"; + private static final String NAMESPACE = "firemud-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 UUID ACCOUNT_ID = UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID OTHER_ACCOUNT_ID = + UUID.fromString("10000000-0000-4000-8000-000000000009"); + private static final UUID TENANT_ID = UUID.fromString("20000000-0000-4000-8000-000000000002"); + private static final UUID OTHER_TENANT_ID = + UUID.fromString("20000000-0000-4000-8000-000000000009"); + private static final UUID TOKEN_ID = UUID.fromString("30000000-0000-4000-8000-000000000003"); + private static final UUID OPERATION_ID = UUID.fromString("40000000-0000-4000-8000-000000000004"); + private static final UUID REQUEST_ID = UUID.fromString("50000000-0000-4000-8000-000000000005"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("60000000-0000-4000-8000-000000000006"); + private static final UUID PROMOTION_OPERATION_ID = + UUID.fromString("70000000-0000-4000-8000-000000000007"); + private static final UUID GENERATION_OPERATION_ID = + UUID.fromString("80000000-0000-4000-8000-000000000008"); + private static final UUID MEMBERSHIP_EVENT_ID = + UUID.fromString("90000000-0000-4000-8000-000000000009"); + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String PROMOTION_REQUEST_DIGEST = "b".repeat(64); + private static final String PRIVATE_RECEIPT_DIGEST = "c".repeat(64); + private static final String PUBLIC_RECEIPT_DIGEST = "d".repeat(64); + private static final String API_BINDING_DIGEST = "e".repeat(64); + private static final String API_CA_DIGEST = "f".repeat(64); + private static final Instant NOW = Instant.parse("2035-04-05T06:07:08Z"); + private static final long NOW_SECONDS = NOW.getEpochSecond(); + private static final long EXPIRY_SECONDS = NOW_SECONDS + 300L; + private static final long CLEANUP_DEADLINE_MILLIS = EXPIRY_SECONDS * 1000L + 300_000L; + private static KeyPair signingKey; + + @BeforeAll + static void generateSigningKey() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + signingKey = generator.generateKeyPair(); + } + + @Test + void verifiesARealSignedTokenAgainstExactCommittedRegistrySignerAndCurrentTenantEvidence() + throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + AccountControlUiCurrentActorVerifier.CurrentActor actor = + fixture.verifier.verify(fixture.compactJwt, TENANT_ID); + + assertThat(actor.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(actor.tenantId()).isEqualTo(TENANT_ID); + assertThat(actor.issuanceOperationId()).isEqualTo(OPERATION_ID); + assertThat(actor.tokenHash()).isEqualTo(fixture.tokenHash); + assertThat(actor.currentTenantRoles()).containsExactly("tenantAdmin"); + assertThat(actor.issuerGeneration()).isEqualTo(1L); + assertThat(actor.accountGeneration()).isEqualTo(1L); + assertThat(actor.tenantGeneration()).isEqualTo(1L); + assertThat(actor.membershipGeneration()).isEqualTo(1L); + assertThat(actor.membershipVersion()).isEqualTo(1L); + assertThat(actor.issuanceFence()).isEqualTo(1L); + verify(fixture.signerStates) + .readOriginalCommittedSigner( + eq(fixture.signerBinding), + eq(fixture.trustFence), + eq(API_BINDING_DIGEST), + eq("api-r1"), + eq(PROMOTION_OPERATION_ID), + eq(GENERATION_OPERATION_ID)); + } + + @Test + void verifiesTheExactBillingCutoffFromTheCurrentTenantAuthorityEvent() throws Exception { + TenantAuthorityEventV1Codec.Event tenantEvent = currentTenantEvent(); + Fixture fixture = + new Fixture( + ACCOUNT_ID, + null, + 1, + 1, + List.of("tenantAdmin"), + 1, + false, + tenantEvent, + billingCutoff(tenantEvent)); + + AccountControlUiCurrentActorVerifier.CurrentActor actor = + fixture.verifier.verify(fixture.compactJwt, TENANT_ID); + + assertThat(actor.tenantId()).isEqualTo(TENANT_ID); + } + + @Test + void rejectsMissingBillingCutoffWhenTheCurrentTenantEventHasBillingEvidence() throws Exception { + Fixture fixture = + new Fixture( + ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false, currentTenantEvent(), null); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsChangedBillingCutoffWhenTheCurrentTenantEventHasBillingEvidence() throws Exception { + TenantAuthorityEventV1Codec.Event tenantEvent = currentTenantEvent(); + Map changedCutoff = billingCutoff(tenantEvent); + changedCutoff.put( + TENANT_ID.toString(), + Map.of( + "tenantAuthorityGeneration", tenantEvent.tenantAuthorityGeneration(), + "tenantBillingSequence", tenantEvent.tenantBillingSequence() + 1L, + "outboxStreamKey", tenantEvent.outboxStreamKey(), + "outboxSequence", tenantEvent.outboxSequence())); + Fixture fixture = + new Fixture( + ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false, tenantEvent, changedCutoff); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsExtraBillingCutoffScopeWhenTheCurrentTenantEventHasBillingEvidence() + throws Exception { + TenantAuthorityEventV1Codec.Event tenantEvent = currentTenantEvent(); + Map extraCutoff = billingCutoff(tenantEvent); + extraCutoff.put( + OTHER_TENANT_ID.toString(), + Map.of( + "tenantAuthorityGeneration", tenantEvent.tenantAuthorityGeneration(), + "tenantBillingSequence", tenantEvent.tenantBillingSequence(), + "outboxStreamKey", tenantEvent.outboxStreamKey(), + "outboxSequence", tenantEvent.outboxSequence())); + Fixture fixture = + new Fixture( + ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false, tenantEvent, extraCutoff); + + assertThatThrownBy(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + } + + @Test + void futureRegistryCleanupDeadlineDoesNotExtendAnExpiredJwt() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + Map expiredClaims = claims(ACCOUNT_ID, null); + expiredClaims.put("iat", NOW_SECONDS - 300L); + expiredClaims.put("nbf", NOW_SECONDS - 300L); + expiredClaims.put("exp", NOW_SECONDS - 1L); + String expiredJwt = sign(expiredClaims, signingKey); + + assertThatThrownBy(() -> fixture.verifier.verify(expiredJwt, TENANT_ID)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + + verify(fixture.issuances, never()).readCommitted(any()); + } + + @Test + void reusesPinnedFiniteKeyCacheButReloadsCurrentJwksOwnerEvidenceForEachVerification() + throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + fixture.verifier.verify(fixture.compactJwt, TENANT_ID); + fixture.verifier.verify(fixture.compactJwt, TENANT_ID); + + verify(fixture.publicJwks, times(1)).sourceIdentity(); + // One load populates the shared 30-second key cache; each verification still freshly loads + // its separate owner-receipt/current-publication snapshot. + verify(fixture.publicJwks, times(3)).load(); + } + + @Test + void rejectsAChangedActorEvenWhenThePresentedCompactTokenIsValidlySigned() throws Exception { + Fixture fixture = new Fixture(OTHER_ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + + verify(fixture.issuances).readCommitted(fixture.tokenHash); + verify(fixture.membershipPairs, never()).readPositive(OTHER_ACCOUNT_ID, TENANT_ID); + } + + @Test + void rejectsASelectedTenantOutsideTheExactSignedTenantScope() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, OTHER_TENANT_ID)); + + verify(fixture.issuances, never()).readCommitted(any()); + } + + @Test + void rejectsStaleTenantGenerationEvenWhenTheCurrentTenantEventAgreesWithTheOwnerSnapshot() + throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 2, 1, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsStaleMembershipGenerationAgainstTheCurrentPositivePairAndEvent() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 2, List.of("tenantAdmin"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsRoleSnapshotThatDiffersFromTheCurrentMembershipEvent() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("moderator"), 1, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsARevokedIssuanceWhenNoCommittedIssuanceCanBeRead() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, false); + when(fixture.issuances.readCommitted(fixture.tokenHash)).thenReturn(Optional.empty()); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + + verify(fixture.sourceEvidence, never()).readCurrentIssuerAccountSources(ISSUER, ACCOUNT_ID); + } + + @Test + void rejectsACommitRecordWithAnInvalidCoordinationReadbackReceipt() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 0, false); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsACommittedSignerReceiptThatDoesNotMatchProtectedOriginalReadback() throws Exception { + Fixture fixture = new Fixture(ACCOUNT_ID, null, 1, 1, List.of("tenantAdmin"), 1, true); + + assertDenied(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)); + } + + @Test + void rejectsGlobalRoleClaimsInsteadOfTreatingThemAsTenantOperatorAuthority() throws Exception { + Fixture fixture = + new Fixture(ACCOUNT_ID, List.of("platformAdmin"), 1, 1, List.of("tenantAdmin"), 1, false); + + assertThatThrownBy(() -> fixture.verifier.verify(fixture.compactJwt, TENANT_ID)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + + verify(fixture.issuances, never()).readCommitted(any()); + } + + private static void assertDenied(Runnable action) { + assertThatThrownBy(action::run).isInstanceOf(IllegalStateException.class); + } + + private static final class Fixture { + private final UUID issuanceAccountId = ACCOUNT_ID; + private final String compactJwt; + private final String tokenHash; + private final AccountJwtSignerDesiredStateRepository.Binding signerBinding; + private final TrustFence trustFence; + private final AccountControlUiCurrentActorVerifier verifier; + private final AccountControlUiCommittedIssuanceRepository issuances = + mock(AccountControlUiCommittedIssuanceRepository.class); + private final AccountAuthoritySourceEvidenceRepository sourceEvidence = + mock(AccountAuthoritySourceEvidenceRepository.class); + private final AccountAuthorityGenerationRepository generations = + mock(AccountAuthorityGenerationRepository.class); + private final AccountTenantAuthorityEventRepository tenantEvents = + mock(AccountTenantAuthorityEventRepository.class); + private final AccountTenantMembershipRepository memberships = + mock(AccountTenantMembershipRepository.class); + private final AccountMembershipPairAuthorityRepository membershipPairs = + mock(AccountMembershipPairAuthorityRepository.class); + private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots = + mock(AccountTenantMembershipRoleSnapshotRepository.class); + private final AccountAuthorityOutboxRepository outbox = + mock(AccountAuthorityOutboxRepository.class); + private final AccountJwtSignerDesiredStateRepository signerStates = + mock(AccountJwtSignerDesiredStateRepository.class); + private final AccountJwtJwksTrustedSource publicJwks = mock(AccountJwtJwksTrustedSource.class); + + private Fixture( + UUID tokenAccountId, + List globalRoles, + long currentTenantGeneration, + long currentMembershipGeneration, + List roleSnapshot, + int localAofCount, + boolean mismatchPublicReceipt) + throws Exception { + this( + tokenAccountId, + globalRoles, + currentTenantGeneration, + currentMembershipGeneration, + roleSnapshot, + localAofCount, + mismatchPublicReceipt, + null, + null); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "These fixed paths model the protected Account API CA and projected bearer-token trust inputs in the fixture; the test never reads them.") + private Fixture( + UUID tokenAccountId, + List globalRoles, + long currentTenantGeneration, + long currentMembershipGeneration, + List roleSnapshot, + int localAofCount, + boolean mismatchPublicReceipt, + TenantAuthorityEventV1Codec.Event currentTenantEvent, + Map tenantBillingCutoff) + throws Exception { + Map claims = claims(tokenAccountId, globalRoles, tenantBillingCutoff); + compactJwt = sign(claims, signingKey); + tokenHash = sha256(compactJwt.getBytes(StandardCharsets.US_ASCII)); + + String jwksJson = jwks((RSAPublicKey) signingKey.getPublic()); + byte[] jwksBytes = jwksJson.getBytes(StandardCharsets.UTF_8); + SourceIdentity sourceIdentity = sourceIdentity(); + PublicJwksSnapshot jwksSnapshot = new PublicJwksSnapshot(sourceIdentity, jwksBytes); + when(publicJwks.sourceIdentity()).thenReturn(sourceIdentity); + when(publicJwks.load()).thenReturn(jwksSnapshot); + + String trustBindingDigest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "trust-r1", + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-jwt-materializer", + List.of("1".repeat(64))); + Binding materializerBinding = + new Binding( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-jwt-materializer", + List.of("1".repeat(64)), + "trust-r1", + trustBindingDigest); + when(materializerTrust.current()).thenReturn(Optional.of(materializerBinding)); + + ParsedBinding apiParsedBinding = + new ParsedBinding( + "api-r1", + ENVIRONMENT, + CLUSTER, + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("/test/serving-ca.pem"), + API_CA_DIGEST, + Path.of("/test/token"), + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:" + NAMESPACE + ":account-service", + API_BINDING_DIGEST); + when(apiBinding.current()).thenReturn(apiParsedBinding); + + AccountJwtSignerDesiredStateRepository.CustodyMode custodyMode = + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK; + signerBinding = + new AccountJwtSignerDesiredStateRepository.Binding( + ENVIRONMENT, CLUSTER, NAMESPACE, custodyMode); + trustFence = new TrustFence(CLUSTER_UID, NAMESPACE_UID, trustBindingDigest, "trust-r1"); + + byte[] sourceBytes = + canonicalBytes( + Map.of( + "schemaVersion", 1, + "issuer", ISSUER, + "accountId", issuanceAccountId.toString(), + "tenantId", TENANT_ID.toString(), + "sources", List.of())); + String sourceHash = sha256(sourceBytes); + Map bundleRef = + Map.of( + "bundleVersion", "1", + "sourceVersion", "1", + "sourceFence", "1", + "linearization", "1"); + Map operation = + Map.of( + "operationId", OPERATION_ID.toString(), + "requestId", REQUEST_ID.toString(), + "requestDigest", REQUEST_DIGEST, + "callerWorkload", "logging-admin-service", + "callerContextId", CALLER_CONTEXT_ID.toString(), + "accountId", issuanceAccountId.toString()); + Map sourceVersions = sourceVersions(); + Map roleEvidence = + Map.of("scopedRoles", claims.get("scopedRoles"), "freshnessSource", sourceHash); + Map bundle = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("schema", "account-auth-evidence-bundle/v1"), + Map.entry("bundleRef", bundleRef), + Map.entry("snapshotIdentity", sourceHash), + Map.entry("issuer", ISSUER), + Map.entry("profile", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry( + "scope", + Map.of( + "kind", "TENANT", + "accountId", issuanceAccountId.toString(), + "tenantIds", List.of(TENANT_ID.toString()))), + Map.entry("operation", operation), + Map.entry("tokenIdentity", tokenIdentity(claims)), + Map.entry("authorityTuple", claims.get("authorityTuple")), + Map.entry("membershipVersion", claims.get("membershipVersion")), + Map.entry("issuanceFence", claims.get("issuanceFence")), + Map.entry("authoritySourceVersions", sourceVersions), + Map.entry( + "accountIdentitySource", + Map.of( + "accountId", + issuanceAccountId.toString(), + "source", + "account_repository_insert", + "sourceVersion", + 1)), + Map.entry( + "outboxCheckpoints", + Map.of( + "issuer", 0, + "account", 0, + "tenant", 0, + "membership", 1)), + Map.entry("roleEvidence", roleEvidence))); + Map evaluation = + Map.of( + "operation", operation, + "claims", claims, + "bundleRef", bundleRef, + "snapshotIdentity", sourceHash); + bundle.put("evaluationIdentity", sha256(canonicalBytes(evaluation))); + byte[] bundleBytes = canonicalBytes(bundle); + + String fingerprint = publicKeyFingerprint((RSAPublicKey) signingKey.getPublic()); + String publicDataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + jwksJson, "{\"generation\":\"1\",\"kid\":\"" + KID + "\"}"); + byte[] signerReceipt = + canonicalBytes( + Map.ofEntries( + Map.entry("schema", "account-control-ui-committed-signer/v1"), + Map.entry("environmentId", ENVIRONMENT), + Map.entry("clusterId", CLUSTER), + Map.entry("namespace", NAMESPACE), + Map.entry("clusterIncarnationUid", CLUSTER_UID), + Map.entry("namespaceUid", NAMESPACE_UID), + Map.entry("trustBindingDigest", trustBindingDigest), + Map.entry("trustConfigRevision", "trust-r1"), + Map.entry("apiBindingDigest", API_BINDING_DIGEST), + Map.entry("apiConfigRevision", "api-r1"), + Map.entry("promotionOperationId", PROMOTION_OPERATION_ID.toString()), + Map.entry("promotionRequestDigest", PROMOTION_REQUEST_DIGEST), + Map.entry("generationOperationId", GENERATION_OPERATION_ID.toString()), + Map.entry("signerGeneration", "1"), + Map.entry("kid", KID), + Map.entry("algorithm", "RS256"), + Map.entry("publicKeyFingerprint", fingerprint), + Map.entry("privateReceiptDigest", PRIVATE_RECEIPT_DIGEST), + Map.entry("privateResourceVersion", "22"), + Map.entry("publicReceiptDigest", PUBLIC_RECEIPT_DIGEST), + Map.entry("publicResourceVersion", "23"), + Map.entry("publicConfigMapUid", CONFIG_MAP_UID), + Map.entry("publicDataDigest", publicDataDigest))); + + Map authBundleReference = new LinkedHashMap<>(bundleRef); + authBundleReference.put("canonicalSha256", sha256(bundleBytes)); + Map activeRegistryRecord = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("registryVersion", 2), + Map.entry("tokenHash", tokenHash), + Map.entry("kid", KID), + Map.entry("signerGeneration", "1"), + Map.entry("issuer", ISSUER), + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("accountId", issuanceAccountId.toString()), + Map.entry("jti", TOKEN_ID.toString()), + Map.entry("iat", NOW_SECONDS), + Map.entry("nbf", NOW_SECONDS), + Map.entry("exp", EXPIRY_SECONDS), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", claims.get("authorityTuple")), + Map.entry("membershipVersion", claims.get("membershipVersion")), + Map.entry("issuanceFence", 1), + Map.entry("operationId", OPERATION_ID.toString()), + Map.entry("requestId", REQUEST_ID.toString()), + Map.entry("requestDigest", REQUEST_DIGEST), + Map.entry("registryCleanupDeadlineEpochMillis", CLEANUP_DEADLINE_MILLIS), + Map.entry("state", "active"), + Map.entry("authoritySourceVersions", sourceVersions), + Map.entry("authEvidenceBundle", authBundleReference), + Map.entry("originalSignerReceiptDigest", sha256(signerReceipt)))); + byte[] activeRegistry = canonicalBytes(activeRegistryRecord); + Map pendingRegistryRecord = new LinkedHashMap<>(activeRegistryRecord); + pendingRegistryRecord.put("state", "pending"); + pendingRegistryRecord.put("registryVersion", 1); + byte[] pendingRegistry = canonicalBytes(pendingRegistryRecord); + byte[] pendingReceipt = + canonicalBytes( + Map.of( + "schema", + "account-control-ui-pending-readback/v1", + "tokenHash", + tokenHash, + "recordDigest", + sha256(pendingRegistry), + "expiryMillis", + CLEANUP_DEADLINE_MILLIS, + "aclIdentity", + "account_coord_app", + "localAofCount", + localAofCount, + "replicaAofCount", + 1)); + + var committedIssuance = mock(CommittedIssuance.class); + when(committedIssuance.requestId()).thenReturn(REQUEST_ID); + when(committedIssuance.operationId()).thenReturn(OPERATION_ID); + when(committedIssuance.tokenJti()).thenReturn(TOKEN_ID); + when(committedIssuance.accountId()).thenReturn(issuanceAccountId); + when(committedIssuance.tenantId()).thenReturn(TENANT_ID); + when(committedIssuance.callerWorkload()).thenReturn("logging-admin-service"); + when(committedIssuance.callerContextId()).thenReturn(CALLER_CONTEXT_ID); + when(committedIssuance.requestDigest()).thenReturn(REQUEST_DIGEST); + when(committedIssuance.claims()).thenReturn(canonicalBytes(claims)); + when(committedIssuance.source()).thenReturn(sourceBytes); + when(committedIssuance.bundle()).thenReturn(bundleBytes); + when(committedIssuance.signerReceipt()).thenReturn(signerReceipt); + when(committedIssuance.issuedAtEpochSecond()).thenReturn(NOW_SECONDS); + when(committedIssuance.expiresAtEpochSecond()).thenReturn(EXPIRY_SECONDS); + when(committedIssuance.expiryMillis()).thenReturn(CLEANUP_DEADLINE_MILLIS); + when(committedIssuance.status()).thenReturn("COMMITTED"); + when(committedIssuance.tokenHash()).thenReturn(tokenHash); + when(committedIssuance.pendingRegistry()).thenReturn(pendingRegistry); + when(committedIssuance.activeRegistry()).thenReturn(activeRegistry); + when(committedIssuance.pendingReceipt()).thenReturn(pendingReceipt); + when(issuances.readCommitted(tokenHash)).thenReturn(Optional.of(committedIssuance)); + + configureSignerReadback(mismatchPublicReceipt ? "0".repeat(64) : publicDataDigest); + configureRegistry(activeRegistry); + configureCurrentSources( + currentTenantGeneration, currentMembershipGeneration, roleSnapshot, currentTenantEvent); + + PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); + when(transactionManager.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + verifier = + new AccountControlUiCurrentActorVerifier( + publicJwks, + signerStates, + materializerTrust, + apiBinding, + registry, + issuances, + sourceEvidence, + generations, + tenantEvents, + memberships, + membershipPairs, + roleSnapshots, + outbox, + transactionManager, + Clock.fixed(NOW, ZoneId.of("UTC"))); + } + + private final AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + private final AccountJwtJwksApiBinding apiBinding = mock(AccountJwtJwksApiBinding.class); + private AccountControlUiRegistryReader registry; + + private void configureSignerReadback(String originalPublicDataDigest) throws Exception { + var original = mock(OriginalCommittedSignerEvidence.class); + var promotion = mock(PromotionOperationEvidence.class); + var generation = mock(GenerationResult.class); + var privateReceipt = mock(PrivatePromotionReceipt.class); + var publicReceipt = mock(ActiveJwksPromotionReceipt.class); + when(original.promotion()).thenReturn(promotion); + when(original.generationResult()).thenReturn(generation); + when(original.privateReceipt()).thenReturn(privateReceipt); + when(original.publicReceipt()).thenReturn(publicReceipt); + when(promotion.status()).thenReturn("COMMITTED"); + when(promotion.operationId()).thenReturn(PROMOTION_OPERATION_ID); + when(promotion.requestDigest()).thenReturn(PROMOTION_REQUEST_DIGEST); + when(promotion.generationOperationId()).thenReturn(GENERATION_OPERATION_ID); + when(generation.operationId()).thenReturn(GENERATION_OPERATION_ID); + when(generation.targetKid()).thenReturn(KID); + when(generation.targetGeneration()).thenReturn("1"); + when(generation.targetAlgorithm()).thenReturn("RS256"); + when(generation.publicKeyFingerprint()) + .thenReturn(publicKeyFingerprint((RSAPublicKey) signingKey.getPublic())); + when(privateReceipt.receiptDigest()).thenReturn(PRIVATE_RECEIPT_DIGEST); + when(privateReceipt.observedResourceVersion()).thenReturn("22"); + when(publicReceipt.receiptDigest()).thenReturn(PUBLIC_RECEIPT_DIGEST); + when(publicReceipt.observedResourceVersion()).thenReturn("23"); + when(publicReceipt.configMapUid()).thenReturn(CONFIG_MAP_UID); + when(publicReceipt.publicDataDigest()).thenReturn(originalPublicDataDigest); + when(signerStates.readOriginalCommittedSigner( + any(), + any(), + eq(API_BINDING_DIGEST), + eq("api-r1"), + eq(PROMOTION_OPERATION_ID), + eq(GENERATION_OPERATION_ID))) + .thenReturn(Optional.of(original)); + } + + private void configureRegistry(byte[] activeRegistry) { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(activeRegistry); + when(commands.pexpiretime(any(byte[].class))).thenReturn(CLEANUP_DEADLINE_MILLIS); + registry = new AccountControlUiRegistryReader(() -> connection); + } + + private void configureCurrentSources( + long currentTenantGeneration, + long currentMembershipGeneration, + List currentRoleSnapshot, + TenantAuthorityEventV1Codec.Event currentTenantEvent) { + IssuanceFence fence = new IssuanceFence(ACCOUNT_ID, 1L, 1L); + String issuerStream = "account:auth-authority:v1:issuer/" + ISSUER; + String accountStream = "account:auth-authority:v1:account/" + ACCOUNT_ID; + CurrentSourceEvidence issuerSource = + new CurrentSourceEvidence( + AuthorityScope.issuer(ISSUER), + 1L, + 1L, + null, + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + issuerStream, 0L, Optional.empty(), Optional.empty()), + Optional.empty(), + "ISSUER_SCOPE_INSERT", + null, + null, + 1L, + null); + CurrentSourceEvidence accountSource = + new CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 1L, + 1L, + fence, + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + accountStream, 0L, Optional.empty(), Optional.empty()), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 77L, + AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT.name(), + 77L, + 77L); + IssuerAccountSourceSnapshot sourceSnapshot = + new IssuerAccountSourceSnapshot(issuerSource, accountSource, fence); + when(sourceEvidence.readCurrentIssuerAccountSources(ISSUER, ACCOUNT_ID)) + .thenReturn(sourceSnapshot); + + ScopeState issuerState = new ScopeState(AuthorityScope.issuer(ISSUER), 1L, 1L, null); + ScopeState accountState = new ScopeState(AuthorityScope.account(ACCOUNT_ID), 1L, 1L, fence); + ScopeState tenantState = + new ScopeState( + AuthorityScope.tenant(TENANT_ID), + currentTenantGeneration, + currentTenantGeneration, + null); + ScopeState membershipState = + new ScopeState( + AuthorityScope.membership(ACCOUNT_ID, TENANT_ID), + currentMembershipGeneration, + currentMembershipGeneration, + fence); + CompositeSnapshot composite = + new CompositeSnapshot( + issuerState, accountState, List.of(tenantState), List.of(membershipState), fence); + when(generations.readCompositeSnapshot( + eq(ISSUER), eq(ACCOUNT_ID), eq(List.of(TENANT_ID)), eq(List.of(TENANT_ID)))) + .thenReturn(composite); + + TenantAuthorityEventV1Codec.Event tenantEvent = currentTenantEvent; + if (tenantEvent == null) { + tenantEvent = mock(TenantAuthorityEventV1Codec.Event.class); + when(tenantEvent.tenantId()).thenReturn(TENANT_ID); + when(tenantEvent.tenantAuthorityGeneration()).thenReturn(currentTenantGeneration); + when(tenantEvent.tenantAuthoritySourceVersion()).thenReturn(currentTenantGeneration); + } + when(tenantEvents.readCurrentByTenant(TENANT_ID)).thenReturn(tenantEvent); + + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + UUID.fromString("a0000000-0000-4000-8000-00000000000a"), + "sha256:" + "9".repeat(64)); + MembershipEvent membershipEvent = + MembershipAuthorityEventV1Codec.seal( + membershipEventPreimage( + currentTenantGeneration, currentMembershipGeneration, List.of("tenantAdmin"))); + PairAuthority pair = + new PairAuthority( + ACCOUNT_ID, + TENANT_ID, + provenance, + true, + 1L, + currentMembershipGeneration, + 1L, + membershipEvent.eventId(), + membershipEvent.eventDigest(), + false); + when(membershipPairs.readPositive(ACCOUNT_ID, TENANT_ID)).thenReturn(Optional.of(pair)); + + Account account = new Account(); + account.setId(101L); + account.setAccountUuid(ACCOUNT_ID); + AccountTenantMembership membership = new AccountTenantMembership(); + membership.setId(202L); + membership.setAccount(account); + membership.setTenantUuid(TENANT_ID); + membership.setLifecycleState("ACTIVE"); + membership.setMembershipVersion(1L); + membership.setMembershipAuthorityGeneration(currentMembershipGeneration); + when(memberships.findFreshMembership(ACCOUNT_ID, TENANT_ID)) + .thenReturn(Optional.of(membership)); + RoleSnapshot roles = + new RoleSnapshot( + 101L, null, 202L, 1L, currentRoleSnapshot, ACCOUNT_ID, TENANT_ID, provenance); + when(roleSnapshots.findForCanonicalUpdate(ACCOUNT_ID, TENANT_ID, provenance, 202L, 1L)) + .thenReturn(Optional.of(roles)); + + String streamKey = + MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + + "membership/" + + ACCOUNT_ID + + "/" + + TENANT_ID; + AccountAuthorityOutboxRepository.Event membershipOutboxEvent = + new AccountAuthorityOutboxRepository.Event( + streamKey, + membershipEvent.requestId(), + 1L, + membershipEvent.eventId(), + membershipEvent.eventDigest(), + membershipEvent.canonicalJson().getBytes(StandardCharsets.UTF_8)); + when(outbox.findEvent(streamKey, 1L)).thenReturn(Optional.of(membershipOutboxEvent)); + } + } + + private static TenantAuthorityEventV1Codec.Event currentTenantEvent() { + UUID creationRequestId = UUID.fromString("a1000000-0000-4000-8000-000000000001"); + UUID operationId = UUID.fromString("a2000000-0000-4000-8000-000000000002"); + UUID requestId = UUID.fromString("a3000000-0000-4000-8000-000000000003"); + String requestDigest = "sha256:" + "1".repeat(64); + String sourceNamespace = "account-service"; + String sourceTenantKey = "tenant-101"; + String evidenceDigest = + GameTenantCreationDigest.evidenceDigest( + sourceNamespace, + creationRequestId, + operationId, + requestDigest, + TENANT_ID, + 101L, + sourceTenantKey, + "NEW_GAME_ROW"); + FreshTenantCreationEvidence source = + new FreshTenantCreationEvidence( + 1, + sourceNamespace, + creationRequestId, + operationId, + requestDigest, + TENANT_ID, + 101L, + sourceTenantKey, + "NEW_GAME_ROW", + evidenceDigest); + DemoTenantEntitlementRequest request = + new DemoTenantEntitlementRequest( + requestId, + TENANT_ID, + creationRequestId, + requestDigest, + null, + null, + null, + true, + true, + false, + false, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)); + DemoTenantEntitlementEventV1Codec.Event billingEvent = + DemoTenantEntitlementEventV1Codec.seal(request, source, 1L, 1L, 1L, 7L); + TenantAuthorityEventV1Codec.Event authorityEvent = + TenantAuthorityEventV1Codec.seal(request, source, 1L, 1L, 11L, billingEvent); + return TenantAuthorityEventV1Codec.verify(authorityEvent.payload()); + } + + private static Map billingCutoff(TenantAuthorityEventV1Codec.Event event) { + Map cutoff = new LinkedHashMap<>(); + cutoff.put( + TENANT_ID.toString(), + Map.of( + "tenantAuthorityGeneration", event.tenantAuthorityGeneration(), + "tenantBillingSequence", event.tenantBillingSequence(), + "outboxStreamKey", event.outboxStreamKey(), + "outboxSequence", event.outboxSequence())); + return cutoff; + } + + private static Map claims(UUID accountId, List globalRoles) { + return claims(accountId, globalRoles, null); + } + + private static Map claims( + UUID accountId, List globalRoles, Map tenantBillingCutoff) { + Map authorityTuple = + new LinkedHashMap<>( + Map.of( + "issuerAuthGeneration", 1, + "accountAuthorityGeneration", 1, + "tenantAuthorityGeneration", Map.of(TENANT_ID.toString(), 1), + "membershipAuthorityGeneration", Map.of(TENANT_ID.toString(), 1), + "privateRealmGrantVersions", List.of())); + Map claims = + new LinkedHashMap<>( + Map.ofEntries( + Map.entry("iss", ISSUER), + Map.entry("sub", accountId.toString()), + Map.entry("jti", TOKEN_ID.toString()), + Map.entry("accountId", accountId.toString()), + Map.entry("aud", "control-ui"), + Map.entry("iat", NOW_SECONDS), + Map.entry("nbf", NOW_SECONDS), + Map.entry("exp", EXPIRY_SECONDS), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", authorityTuple), + Map.entry("membershipVersion", Map.of(TENANT_ID.toString(), 1)), + Map.entry("issuanceFence", 1), + Map.entry("scopedRoles", Map.of(TENANT_ID.toString(), List.of("tenantAdmin"))))); + if (tenantBillingCutoff != null) { + authorityTuple.put("tenantBillingCutoff", tenantBillingCutoff); + } + if (globalRoles != null) { + claims.put("globalRoles", globalRoles); + } + return claims; + } + + private static Map membershipEventPreimage( + long tenantGeneration, long membershipGeneration, List roles) { + String sourceScope = "membership/" + ACCOUNT_ID + "/" + TENANT_ID; + String streamKey = MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX + sourceScope; + Map tuple = + Map.of( + "issuerAuthGeneration", "1", + "accountAuthorityGeneration", "1", + "tenantAuthorityGeneration", + Map.of(TENANT_ID.toString(), Long.toString(tenantGeneration)), + "membershipAuthorityGeneration", + Map.of(TENANT_ID.toString(), Long.toString(membershipGeneration)), + "privateRealmGrantVersions", List.of()); + return Map.ofEntries( + Map.entry("schemaVersion", MembershipAuthorityEventV1Codec.SCHEMA_VERSION), + Map.entry("eventType", MembershipAuthorityEventV1Codec.EVENT_TYPE), + Map.entry("eventId", MEMBERSHIP_EVENT_ID.toString()), + Map.entry("requestId", MEMBERSHIP_EVENT_ID.toString()), + Map.entry("outboxStreamKey", streamKey), + Map.entry("outboxSequence", "1"), + Map.entry("sourceScope", sourceScope), + Map.entry("accountId", ACCOUNT_ID.toString()), + Map.entry("tenantId", TENANT_ID.toString()), + Map.entry("membershipExists", true), + Map.entry("membershipLifecycleState", "ACTIVE"), + Map.entry("membershipVersion", Map.of(TENANT_ID.toString(), "1")), + Map.entry("membershipAuthorityGeneration", Long.toString(membershipGeneration)), + Map.entry("authorityTuple", tuple), + Map.entry("issuanceFence", "1"), + Map.entry("roles", roles), + Map.entry("gameplayAdmissionAllowed", true), + Map.entry("callerBoundAuthorityInvalidated", false)); + } + + private static Map tokenIdentity(Map claims) { + return Map.of( + "jti", claims.get("jti"), + "tokenGeneration", claims.get("tokenGeneration"), + "iat", claims.get("iat"), + "nbf", claims.get("nbf"), + "exp", claims.get("exp")); + } + + private static Map sourceVersions() { + return Map.of( + "ISSUER:" + ISSUER, 1, + "ACCOUNT:" + ACCOUNT_ID, 1, + "TENANT:" + TENANT_ID, 1, + "MEMBERSHIP:" + ACCOUNT_ID + ":" + TENANT_ID, 1); + } + + private static SourceIdentity sourceIdentity() { + return new SourceIdentity( + ENVIRONMENT, + CLUSTER, + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + CONFIG_MAP_UID, + "api-r1", + "https://kubernetes.test:6443", + API_CA_DIGEST); + } + + private static String jwks(RSAPublicKey key) throws Exception { + String modulus = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getModulus().toByteArray())); + String exponent = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getPublicExponent().toByteArray())); + return JSON.writeValueAsString( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "use", + "sig", + "alg", + "RS256", + "kid", + KID, + "key_ops", + List.of("verify"), + "n", + modulus, + "e", + exponent)))); + } + + private static String publicKeyFingerprint(RSAPublicKey key) throws Exception { + String modulus = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getModulus().toByteArray())); + String exponent = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(unsigned(key.getPublicExponent().toByteArray())); + byte[] canonical = canonicalBytes(Map.of("e", exponent, "kty", "RSA", "n", modulus)); + return sha256(canonical); + } + + private static byte[] unsigned(byte[] value) { + return value.length > 1 && value[0] == 0 + ? java.util.Arrays.copyOfRange(value, 1, value.length) + : value; + } + + private static String sign(Map claims, KeyPair keyPair) throws Exception { + byte[] header = canonicalBytes(Map.of("alg", "RS256", "kid", KID, "typ", "JWT")); + byte[] payload = canonicalBytes(claims); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + String signingInput = encoder.encodeToString(header) + "." + encoder.encodeToString(payload); + Signature signature = Signature.getInstance("SHA256withRSA"); + signature.initSign(keyPair.getPrivate()); + signature.update(signingInput.getBytes(StandardCharsets.US_ASCII)); + return signingInput + "." + encoder.encodeToString(signature.sign()); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } + + private static String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepositoryTest.java new file mode 100644 index 0000000000..2a129df9d5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepositoryTest.java @@ -0,0 +1,217 @@ +package unit.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.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl.ControlUiPrimaryIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiSignerOwner; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountControlUiIssuanceRepositoryTest { + private static final String LINEARIZATION_QUERY = + "SELECT pg_current_xact_id()::TEXT AS xid, " + + "nextval('account_control_ui_source_fence') AS fence"; + private static final UUID ACTOR_ID = UUID.fromString("10000000-0000-4000-8000-000000000001"); + private static final UUID TENANT_ID = UUID.fromString("20000000-0000-4000-8000-000000000002"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void prepareReusesOwnerLinearizationAndAllocatesItsFenceExactlyOnce() throws Exception { + DSLContext dsl = mock(DSLContext.class); + Record linearizationRow = mock(Record.class); + when(dsl.fetchOne(LINEARIZATION_QUERY)).thenReturn(linearizationRow); + when(linearizationRow.get("xid", String.class)).thenReturn("123456"); + when(linearizationRow.get("fence", Long.class)).thenReturn(99L); + var repository = spy(new AccountControlUiIssuanceRepository(dsl)); + AccountControlUiAuthority.Snapshot source = mock(AccountControlUiAuthority.Snapshot.class); + ControlUiPrimaryIdentity authenticated = mock(ControlUiPrimaryIdentity.class); + when(authenticated.accountId()).thenReturn(ACTOR_ID); + when(source.actor()).thenReturn(ACTOR_ID); + when(source.tenant()).thenReturn(TENANT_ID); + when(source.authorityTuple()) + .thenReturn( + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 1L, + "tenantAuthorityGeneration", + Map.of(TENANT_ID.toString(), 1L), + "membershipAuthorityGeneration", + Map.of(TENANT_ID.toString(), 1L), + "privateRealmGrantVersions", + List.of())); + when(source.membershipVersion()).thenReturn(Map.of(TENANT_ID.toString(), 1L)); + when(source.issuanceFence()).thenReturn(1L); + when(source.evidence()).thenReturn(new byte[] {1}); + when(source.sources()).thenReturn(List.of()); + when(source.accountIdentitySource()).thenReturn(Map.of("accountId", ACTOR_ID.toString())); + when(source.outboxCheckpoints()).thenReturn(List.of()); + TransactionSynchronizationManager.setActualTransactionActive(true); + + UUID requestId = UUID.fromString("30000000-0000-4000-8000-000000000003"); + UUID callerContextId = UUID.fromString("40000000-0000-4000-8000-000000000004"); + var signer = mock(AccountControlUiSignerOwner.Capture.class); + var prepare = + AccountControlUiIssuanceRepository.class.getDeclaredMethod( + "prepare", + UUID.class, + String.class, + UUID.class, + String.class, + String.class, + ControlUiPrimaryIdentity.class, + AccountControlUiAuthority.Snapshot.class, + AccountControlUiSignerOwner.Capture.class, + Instant.class, + long.class); + prepare.setAccessible(true); + assertThatThrownBy( + () -> + prepare.invoke( + repository, + requestId, + "spiffe://firemud/ns/test/sa/logging-admin-service", + callerContextId, + "test-mac-key", + "a".repeat(64), + authenticated, + source, + signer, + Instant.parse("2026-10-08T11:00:00Z"), + 300_000L)) + .isInstanceOf(InvocationTargetException.class) + .hasCauseInstanceOf(IllegalStateException.class); + + verify(repository, times(1)).captureOwnerLinearization(); + verify(dsl, times(1)).fetchOne(LINEARIZATION_QUERY); + } + + @Test + void cleanupDeadlineUsesCheckedPerIssuanceMarginAndAllowsExplicitZero() throws Exception { + long tokenExpiryMillis = Instant.parse("2035-04-05T06:12:08Z").toEpochMilli(); + + assertThat(checkedCleanupDeadlineMillis(tokenExpiryMillis, 0L)).isEqualTo(tokenExpiryMillis); + assertThat(checkedCleanupDeadlineMillis(tokenExpiryMillis, 300_000L)) + .isEqualTo(tokenExpiryMillis + 300_000L); + assertThatThrownBy(() -> checkedCleanupDeadlineMillis(tokenExpiryMillis, -1L)) + .hasCauseInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> checkedCleanupDeadlineMillis(maxRedisSafeInteger(), 1L)) + .hasCauseInstanceOf(IllegalStateException.class); + } + + @Test + void retainedLegacyIssuanceWithoutCleanupDeadlineCannotBeReinterpreted() throws Exception { + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer( + call -> + switch (call.getArgument(0, String.class)) { + case "issued_at_epoch_second" -> 1_800_000_000L; + case "expires_at_epoch_second" -> 1_800_000_300L; + case "recovery_expires_at" -> OffsetDateTime.parse("2027-01-15T08:01:00Z"); + default -> null; + }); + var retained = stored(row); + + assertThatThrownBy(() -> storedExpiryMillis(retained)) + .hasCauseInstanceOf(IllegalStateException.class); + } + + @Test + void committedCurrentSourceReadDeniesMissingLegacyCleanupDeadline() { + DSLContext dsl = mock(DSLContext.class); + Record row = mock(Record.class); + Map values = new HashMap<>(); + values.put("request_id", UUID.fromString("30000000-0000-4000-8000-000000000003")); + values.put("operation_id", UUID.fromString("40000000-0000-4000-8000-000000000004")); + values.put("token_jti", UUID.fromString("50000000-0000-4000-8000-000000000005")); + values.put("account_uuid", UUID.fromString("10000000-0000-4000-8000-000000000001")); + values.put("tenant_uuid", UUID.fromString("20000000-0000-4000-8000-000000000002")); + values.put("caller_workload", "test-only-caller"); + values.put("caller_context_id", UUID.fromString("60000000-0000-4000-8000-000000000006")); + values.put("request_digest", "a".repeat(64)); + for (String field : List.of("claims_payload", "source_payload", "bundle_payload")) { + values.put(field, new byte[] {1}); + } + values.put("signer_receipt", new byte[] {1}); + values.put("issued_at_epoch_second", 1_800_000_000L); + values.put("expires_at_epoch_second", 1_800_000_300L); + values.put("registry_cleanup_deadline_epoch_millis", null); + values.put("recovery_expires_at", OffsetDateTime.parse("2027-01-15T08:01:00Z")); + values.put("status", "COMMITTED"); + values.put("token_hash", "b".repeat(64)); + values.put("pending_registry", new byte[] {1}); + values.put("active_registry", new byte[] {1}); + values.put("pending_receipt", new byte[] {1}); + values.put("committed_at", OffsetDateTime.parse("2027-01-15T08:00:10Z")); + values.put("recovery_failed_at", null); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(call -> values.get(call.getArgument(0, String.class))); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(row); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> + new AccountControlUiCommittedIssuanceRepository(dsl).readCommitted("b".repeat(64))) + .isInstanceOf(IllegalStateException.class); + } + + private static long checkedCleanupDeadlineMillis(long tokenExpiryMillis, long marginMillis) + throws Exception { + Method method = + AccountControlUiIssuanceRepository.class.getDeclaredMethod( + "checkedCleanupDeadlineMillis", long.class, long.class); + method.setAccessible(true); + return (long) method.invoke(null, tokenExpiryMillis, marginMillis); + } + + private static long maxRedisSafeInteger() throws Exception { + var field = AccountControlUiIssuanceRepository.class.getDeclaredField("MAX_REDIS_SAFE_INTEGER"); + field.setAccessible(true); + return field.getLong(null); + } + + private static Object stored(Record row) throws Exception { + Class storedClass = + java.util.Arrays.stream(AccountControlUiIssuanceRepository.class.getDeclaredClasses()) + .filter(nested -> nested.getSimpleName().equals("Stored")) + .findFirst() + .orElseThrow(); + var constructor = storedClass.getDeclaredConstructor(Record.class); + constructor.setAccessible(true); + return constructor.newInstance(row); + } + + private static long storedExpiryMillis(Object stored) throws Exception { + Method method = stored.getClass().getDeclaredMethod("expiryMillis"); + method.setAccessible(true); + return (long) method.invoke(stored); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java new file mode 100644 index 0000000000..e9d64dbd1d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java @@ -0,0 +1,570 @@ +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.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Exercises the real workflow orchestration with explicitly synthetic owner, storage, signer, + * registry, transaction, and peer doubles. These definitions prove call ordering and denial only; + * they do not prove real Account authority, SQL durability, signer custody, mTLS, or Redis state. + */ +class AccountControlUiIssuanceWorkflowTest { + private static final Instant NOW = Instant.parse("2026-10-08T11:00:00Z"); + private static final String ISSUER = "spiffe://firemud/ns/firemud/sa/logging-admin-service"; + private static final String OTHER = "spiffe://firemud/ns/firemud/sa/game-design-service"; + + @AfterEach + void clearContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void primaryDenialCommitsAccountingBeforeThrowingAndNeverStartsIssuancePreparation() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + var source = mock(AccountControlUiAuthority.Snapshot.class); + when(source.sources()).thenReturn(java.util.List.of()); + when(fixture.authority.captureInitial(fixture.tenant, fixture.environment)).thenReturn(source); + var denial = new AuthenticationException("AUTH_INVALID_CREDENTIALS", "Invalid credentials"); + when(fixture.primary.authenticateControlUiPrimaryIdentity( + "creator@example.test", "test-only-secret")) + .thenThrow(denial); + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(AuthenticationException.class) + .hasMessage(denial.getMessage()) + .satisfies( + error -> + assertThat(((AuthenticationException) error).getCode()) + .isEqualTo(denial.getCode())); + } + var order = inOrder(fixture.primary, fixture.transactions); + order + .verify(fixture.primary) + .authenticateControlUiPrimaryIdentity("creator@example.test", "test-only-secret"); + order.verify(fixture.transactions).commit(any()); + verify(fixture.transactions, never()).rollback(any()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + verifyNoInteractions(fixture.signers, fixture.cryptography, fixture.registry, fixture.actors); + verify(fixture.operations, never()) + .prepare( + any(), + anyString(), + any(), + anyString(), + anyString(), + any(), + any(), + any(), + any(), + anyLong()); + } + + @Test + void missingOrWrongProtectedPeerDeniesBeforeOwnerLookup() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + var request = fixture.request(fixture.tenant, fixture.context, "test-only-secret"); + + assertThatThrownBy(() -> fixture.service().issue(request, fixture.environment)) + .isInstanceOf(IllegalStateException.class); + try (var ignored = fixture.withPeer(OTHER)) { + assertThatThrownBy(() -> fixture.service().issue(request, fixture.environment)) + .isInstanceOf(IllegalStateException.class); + } + + verifyNoInteractions( + fixture.operations, + fixture.authority, + fixture.fences, + fixture.primary, + fixture.signers, + fixture.registry, + fixture.cryptography, + fixture.actors); + } + + @Test + void changedDigestTenantOrCallerContextConflictsWithoutTerminalizingOriginal() { + for (int changed = 0; changed < 5; changed++) { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + fixture.existing(changed == 4 ? OTHER : ISSUER); + var request = + switch (changed) { + case 0 -> fixture.request(fixture.tenant, fixture.context, "different-secret"); + case 1 -> fixture.request(UUID.randomUUID(), fixture.context, "test-only-secret"); + case 2 -> fixture.request(fixture.tenant, UUID.randomUUID(), "test-only-secret"); + default -> fixture.request(fixture.tenant, fixture.context, "test-only-secret"); + }; + if (changed == 0 || changed == 3) { + when(fixture.cryptography.requestDigest(anyString(), any(byte[].class))) + .thenReturn("changed-request-digest"); + } + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy(() -> fixture.service().issue(request, fixture.environment)) + .isInstanceOf(IllegalArgumentException.class); + } + verify(fixture.operations, never()).beginRecoveryFailure(any()); + verifyNoInteractions(fixture.registry, fixture.primary, fixture.signers); + } + } + + @Test + void currentSourceUnavailabilityDeniesWithoutMarkingOriginalTerminal() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + var original = fixture.existing(); + when(fixture.authority.capture(original.accountId, original.tenantId, fixture.environment)) + .thenThrow(new IllegalStateException("test-only source unavailable")); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(IllegalStateException.class); + } + + verify(fixture.operations, never()).beginRecoveryFailure(any()); + verifyNoInteractions(fixture.registry, fixture.primary); + } + + @Test + void committedRecoveryReturnsTheExactOriginalCredentialWithoutPrimaryAuthenticationOrSigning() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + byte[] exactCredential = "test-only-original-compact-jwt".getBytes(StandardCharsets.US_ASCII); + String tokenHash = AccountControlUiIssuanceRepository.hash(exactCredential); + var original = fixture.useOwnerRepository(tokenHash); + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + when(snapshot.evidence()).thenReturn(new byte[] {1}); + when(snapshot.sources()).thenReturn(java.util.List.of()); + when(fixture.authority.capture(fixture.account, fixture.tenant, fixture.environment)) + .thenReturn(snapshot); + when(fixture.signers.requireOriginal(any(byte[].class))) + .thenReturn(mock(AccountControlUiSignerOwner.Capture.class)); + var binding = fixture.envelopeBinding(original, tokenHash); + var envelope = new AccountControlUiIssuanceRepository.Envelope(new byte[] {9}, binding); + doAnswer(call -> envelope).when(fixture.operations).envelope(any()); + byte[] expectedCredential = exactCredential.clone(); + when(fixture.cryptography.open(any(byte[].class), any(byte[].class), any(Instant.class))) + .thenReturn(exactCredential); + var actor = mock(AccountControlUiActorService.AuthenticatedActor.class); + when(actor.accountId()).thenReturn(fixture.account); + when(actor.issuanceOperationId()).thenReturn(fixture.operationId); + when(fixture.actors.authenticate( + "test-only-original-compact-jwt", fixture.tenant, fixture.environment)) + .thenReturn(actor); + + try (var ignored = fixture.withPeer(ISSUER)) { + try (var issued = + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) { + org.assertj.core.api.Assertions.assertThat(issued.compactBytes()) + .containsExactly(expectedCredential); + org.assertj.core.api.Assertions.assertThat(issued.expiresAt()) + .isEqualTo(NOW.plusSeconds(300)); + } + } + org.assertj.core.api.Assertions.assertThat(exactCredential).containsOnly((byte) 0); + + verify(fixture.registry).activate(any(AccountControlUiIssuanceRepository.Committed.class)); + verify(fixture.primary, never()).authenticateControlUiPrimaryIdentity(anyString(), anyString()); + verify(fixture.signers, never()).sign(any(), any(), any()); + } + + @Test + void unavailableActiveRegistryReadbackDeniesWithoutTerminalizingCommittedOriginal() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + byte[] credential = "test-only-token".getBytes(StandardCharsets.US_ASCII); + String tokenHash = AccountControlUiIssuanceRepository.hash(credential); + var original = fixture.useOwnerRepository(tokenHash); + fixture.recoveryInputs(); + var envelope = + new AccountControlUiIssuanceRepository.Envelope( + new byte[] {9}, fixture.envelopeBinding(original, tokenHash)); + doAnswer(call -> envelope).when(fixture.operations).envelope(any()); + when(fixture.cryptography.open(any(byte[].class), any(byte[].class), any(Instant.class))) + .thenReturn(credential); + when(fixture.actors.authenticate(anyString(), any(), any())) + .thenThrow(new IllegalStateException("test-only active registry unavailable")); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(IllegalStateException.class); + } + + verify(fixture.operations, never()).beginRecoveryFailure(any()); + verify(fixture.registry).activate(any(AccountControlUiIssuanceRepository.Committed.class)); + org.assertj.core.api.Assertions.assertThat(original.status).isEqualTo("COMMITTED"); + } + + @Test + void missingOriginalEnvelopeCreatesRevokingIntentAndDoesNotClaimRevocationOnRegistryFailure() { + Fixture fixture = new Fixture(NOW.plusSeconds(30)); + var original = fixture.useOwnerRepository("unused-token-hash"); + fixture.recoveryInputs(); + doAnswer(call -> null).when(fixture.operations).envelope(any()); + var revoking = fixture.stored("REVOKING", original.recoveryExpiry, original.tokenHash); + doAnswer(call -> revoking) + .when(fixture.operations) + .beginRecoveryFailure(argThat(actual -> sameOriginalRecord(original, actual))); + when(fixture.registry.revoke(revoking)) + .thenThrow(new IllegalStateException("test-only Coordination unavailable")); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(IllegalStateException.class); + } + + ArgumentCaptor originalCaptor = + ArgumentCaptor.forClass(AccountControlUiIssuanceRepository.Stored.class); + verify(fixture.operations).beginRecoveryFailure(originalCaptor.capture()); + assertThat(sameOriginalRecord(original, originalCaptor.getValue())).isTrue(); + verify(fixture.registry) + .revoke( + argThat( + actual -> + "REVOKING".equals(actual.status) + && original.tokenHash.equals(actual.tokenHash) + && original.operationId.equals(actual.operationId))); + verify(fixture.operations, never()).finishRecoveryFailure(any(), any()); + } + + @Test + void expiredOriginalPersistsRevokingIntentBeforeUnavailableRegistryAndNeverReturnsCredential() { + Fixture fixture = new Fixture(NOW.minusSeconds(1)); + var original = fixture.existing(); + var revoking = fixture.stored("REVOKING", original.recoveryExpiry, original.tokenHash); + when(fixture.operations.beginRecoveryFailure(original)).thenReturn(revoking); + when(fixture.registry.revoke(revoking)) + .thenThrow(new IllegalStateException("test-only Coordination unavailable")); + + try (var ignored = fixture.withPeer(ISSUER)) { + assertThatThrownBy( + () -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) + .isInstanceOf(IllegalStateException.class); + } + + verify(fixture.operations).beginRecoveryFailure(original); + verify(fixture.registry).revoke(revoking); + verify(fixture.operations, never()).finishRecoveryFailure(any(), any()); + verifyNoInteractions(fixture.primary, fixture.signers); + verify(fixture.cryptography, never()) + .open(any(byte[].class), any(byte[].class), any(Instant.class)); + verify(fixture.cryptography, never()) + .seal(any(byte[].class), any(byte[].class), any(Instant.class)); + } + + private static boolean sameOriginalRecord( + AccountControlUiIssuanceRepository.Stored expected, + AccountControlUiIssuanceRepository.Stored actual) { + return actual != null + && expected.requestId.equals(actual.requestId) + && expected.operationId.equals(actual.operationId) + && expected.jti.equals(actual.jti) + && expected.accountId.equals(actual.accountId) + && expected.tenantId.equals(actual.tenantId) + && expected.callerContextId.equals(actual.callerContextId) + && expected.caller.equals(actual.caller) + && expected.requestMacKeyId.equals(actual.requestMacKeyId) + && expected.requestDigest.equals(actual.requestDigest) + && expected.status.equals(actual.status) + && expected.tokenHash.equals(actual.tokenHash) + && java.util.Arrays.equals(expected.claims, actual.claims) + && java.util.Arrays.equals(expected.sources, actual.sources) + && java.util.Arrays.equals(expected.bundle, actual.bundle) + && java.util.Arrays.equals(expected.signerReceipt, actual.signerReceipt) + && java.util.Arrays.equals(expected.pendingRegistry, actual.pendingRegistry) + && java.util.Arrays.equals(expected.activeRegistry, actual.activeRegistry) + && expected.issuedAt.equals(actual.issuedAt) + && expected.expiresAt.equals(actual.expiresAt) + && expected.recoveryExpiry.equals(actual.recoveryExpiry); + } + + private static final class Fixture { + final UUID requestId = UUID.randomUUID(); + final UUID operationId = UUID.randomUUID(); + final UUID jti = UUID.randomUUID(); + final UUID account = UUID.randomUUID(); + final UUID tenant = UUID.randomUUID(); + final UUID context = UUID.randomUUID(); + final AccountServiceImpl primary = mock(AccountServiceImpl.class); + AccountControlUiIssuanceRepository operations = mock(AccountControlUiIssuanceRepository.class); + final AccountControlUiAuthority authority = mock(AccountControlUiAuthority.class); + final DraftAuthorizationFenceRepository fences = mock(DraftAuthorizationFenceRepository.class); + final AccountControlUiSignerOwner signers = mock(AccountControlUiSignerOwner.class); + final AccountControlUiResponseCryptography cryptography = + mock(AccountControlUiResponseCryptography.class); + final AccountControlUiCoordination registry = mock(AccountControlUiCoordination.class); + final AccountControlUiActorService actors = mock(AccountControlUiActorService.class); + final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + AccountControlUiIssuanceService service; + Record ownerRow; + + Fixture(Instant recoveryExpiry) { + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer( + call -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); + doAnswer( + call -> { + TransactionSynchronizationManager.clear(); + return null; + }) + .when(transactions) + .commit(any()); + doAnswer( + call -> { + TransactionSynchronizationManager.clear(); + return null; + }) + .when(transactions) + .rollback(any()); + this.recoveryExpiry = recoveryExpiry; + } + + AccountControlUiIssuanceService service() { + if (service == null) { + service = + new AccountControlUiIssuanceService( + primary, + operations, + authority, + fences, + signers, + cryptography, + registry, + actors, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC), + 300_000L, + ISSUER); + } + return service; + } + + final Instant recoveryExpiry; + + AccountControlUiIssuanceRepository.Stored existing() { + return existing(ISSUER); + } + + AccountControlUiIssuanceRepository.Stored existing(String caller) { + var stored = stored("COMMITTED", recoveryExpiry, "original-token-hash", caller); + when(operations.findRequest(requestId)).thenReturn(stored); + when(cryptography.requestDigest(anyString(), any(byte[].class))) + .thenReturn("original-request-digest"); + return stored; + } + + AccountControlUiIssuanceRepository.Stored useOwnerRepository(String tokenHash) { + var stored = stored("COMMITTED", recoveryExpiry, tokenHash); + var dsl = mock(DSLContext.class); + var connection = mock(java.sql.Connection.class); + try { + when(connection.getTransactionIsolation()) + .thenReturn(java.sql.Connection.TRANSACTION_READ_COMMITTED); + } catch (java.sql.SQLException failure) { + throw new AssertionError(failure); + } + doAnswer( + call -> { + call.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(org.jooq.ConnectionRunnable.class)); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenAnswer(call -> ownerRow); + operations = Mockito.spy(new AccountControlUiIssuanceRepository(dsl)); + doAnswer(call -> stored).when(operations).findRequest(requestId); + when(cryptography.requestDigest(anyString(), any(byte[].class))) + .thenReturn("original-request-digest"); + ownerRow = rowFor(stored, tokenHash); + return stored; + } + + void recoveryInputs() { + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + when(snapshot.evidence()).thenReturn(new byte[] {1}); + when(snapshot.sources()).thenReturn(java.util.List.of()); + when(authority.capture(account, tenant, environment)).thenReturn(snapshot); + when(signers.requireOriginal(any(byte[].class))) + .thenReturn(mock(AccountControlUiSignerOwner.Capture.class)); + } + + AccountControlUiIssuanceRepository.Stored stored( + String status, Instant expiry, String tokenHash) { + return stored(status, expiry, tokenHash, ISSUER); + } + + AccountControlUiIssuanceRepository.Stored stored( + String status, Instant expiry, String tokenHash, String caller) { + var values = new java.util.HashMap(); + values.put("request_id", requestId); + values.put("operation_id", operationId); + values.put("token_jti", jti); + values.put("account_uuid", account); + values.put("tenant_uuid", tenant); + values.put("caller_context_id", context); + values.put("caller_workload", caller); + values.put("request_mac_key_id", "test-only-mac-key"); + values.put("request_digest", "original-request-digest"); + values.put("status", status); + values.put("token_hash", tokenHash); + values.put( + "claims_payload", + AccountControlUiAuthority.canonical(java.util.Map.of("synthetic", true))); + values.put("source_payload", new byte[] {1}); + values.put("bundle_payload", new byte[] {2}); + values.put("signer_receipt", new byte[] {3}); + values.put("pending_registry", new byte[] {4}); + values.put("active_registry", new byte[] {5}); + values.put("issued_at_epoch_second", NOW.getEpochSecond()); + values.put("expires_at_epoch_second", NOW.plusSeconds(300).getEpochSecond()); + values.put("registry_cleanup_deadline_epoch_millis", NOW.plusSeconds(600).toEpochMilli()); + values.put("recovery_expires_at", OffsetDateTime.ofInstant(expiry, ZoneOffset.UTC)); + Record row = rowForValues(values); + return new AccountControlUiIssuanceRepository.Stored(row); + } + + Record rowFor(AccountControlUiIssuanceRepository.Stored stored, String tokenHash) { + var values = new java.util.HashMap(); + values.put("request_id", stored.requestId); + values.put("operation_id", stored.operationId); + values.put("token_jti", stored.jti); + values.put("account_uuid", stored.accountId); + values.put("tenant_uuid", stored.tenantId); + values.put("caller_context_id", stored.callerContextId); + values.put("caller_workload", stored.caller); + values.put("request_mac_key_id", stored.requestMacKeyId); + values.put("request_digest", stored.requestDigest); + values.put("status", stored.status); + values.put("token_hash", tokenHash); + values.put("claims_payload", stored.claims); + values.put("source_payload", stored.sources); + values.put("bundle_payload", stored.bundle); + values.put("signer_receipt", stored.signerReceipt); + values.put("pending_registry", stored.pendingRegistry); + values.put("active_registry", stored.activeRegistry); + values.put("issued_at_epoch_second", stored.issuedAt.getEpochSecond()); + values.put("expires_at_epoch_second", stored.expiresAt.getEpochSecond()); + values.put("registry_cleanup_deadline_epoch_millis", stored.expiryMillis()); + values.put( + "recovery_expires_at", OffsetDateTime.ofInstant(stored.recoveryExpiry, ZoneOffset.UTC)); + return rowForValues(values); + } + + Record rowForValues(java.util.Map values) { + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(call -> values.get(call.getArgument(0))); + return row; + } + + byte[] envelopeBinding(AccountControlUiIssuanceRepository.Stored original, String tokenHash) { + return AccountControlUiAuthority.canonical( + java.util.Map.ofEntries( + java.util.Map.entry("purpose", "account-control-ui-original-credential/v1"), + java.util.Map.entry("operationId", original.operationId.toString()), + java.util.Map.entry("requestId", original.requestId.toString()), + java.util.Map.entry("accountId", original.accountId.toString()), + java.util.Map.entry("tenantId", original.tenantId.toString()), + java.util.Map.entry("callerWorkload", original.caller), + java.util.Map.entry("callerContextId", original.callerContextId.toString()), + java.util.Map.entry("requestMacKeyId", original.requestMacKeyId), + java.util.Map.entry("requestDigest", original.requestDigest), + java.util.Map.entry("tokenHash", tokenHash), + java.util.Map.entry( + "claimsDigest", AccountControlUiIssuanceRepository.hash(original.claims)), + java.util.Map.entry( + "bundleDigest", AccountControlUiIssuanceRepository.hash(original.bundle)), + java.util.Map.entry( + "signerReceiptDigest", + AccountControlUiIssuanceRepository.hash(original.signerReceipt)), + java.util.Map.entry("recoveryExpiresAt", original.recoveryExpiry.toString()))); + } + + AccountControlUiIssuanceService.Request request( + UUID requestTenant, UUID requestContext, String secret) { + return new AccountControlUiIssuanceService.Request( + requestId, "creator@example.test", secret, requestTenant, requestContext); + } + + PeerScope withPeer(String uri) { + var identity = GrpcPeerIdentity.parseUri(uri).orElseThrow(); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, identity); + return new PeerScope(context.attach(), context); + } + } + + private record PeerScope(Context previous, Context attached) implements AutoCloseable { + @Override + public void close() { + attached.detach(previous); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java new file mode 100644 index 0000000000..a3b2e0704d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java @@ -0,0 +1,151 @@ +package unit.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.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import de.mkammerer.argon2.Argon2Factory; +import java.time.LocalDateTime; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.dto.AccountDto; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.entity.AccountLifecycleState; +import net.firedevops.firemud.accountservice.mapper.AccountMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountPasswordResetOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual primary-auth secret verification; repositories/transaction markers are explicit doubles. + */ +@ExtendWith(MockitoExtension.class) +class AccountControlUiPrimaryAuthenticationTest { + @Mock AccountRepository accounts; + @Mock AccountAuthorityOutboxRepository authorityOutbox; + @Mock AccountPasswordResetOperationRepository passwordResetOperations; + @Mock AccountLogoutAllOperationRepository logoutAllOperations; + @Mock AccountSecurityStateOperationRepository securityStateOperations; + @Mock AccountEmailLoginChallengeRepository challenges; + @Mock AccountMapper mapper; + @Mock PlatformTransactionManager transactions; + @InjectMocks AccountServiceImpl primary; + Account account; + + @BeforeEach + void setup() { + account = new Account(); + account.setId(41L); + account.setAccountUuid(UUID.randomUUID()); + account.setEmail("creator@example.test"); + account.setUsername("test-creator"); + account.setLoginAuthModes("PASSWORD"); + account.setPasswordHash(hash("test-only-primary-secret")); + TransactionSynchronizationManager.setActualTransactionActive(true); + } + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void actualPasswordProducesCanonicalActorOnlyForEligibleAccount() { + when(accounts.findByEmail("creator@example.test")).thenReturn(Optional.of(account)); + when(mapper.toDto(account)) + .thenReturn( + new AccountDto( + account.getAccountUuid().toString(), + account.getUsername(), + account.getEmail(), + "USER", + false)); + var actor = + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret"); + assertThat(actor.accountId()).isEqualTo(account.getAccountUuid()); + assertThat(actor.toString()).doesNotContain("secret", account.getEmail()); + assertThatThrownBy( + () -> primary.authenticateControlUiPrimaryIdentity(account.getEmail(), "wrong-secret")) + .isInstanceOf(RuntimeException.class); + account.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); + assertThatThrownBy( + () -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) + .isInstanceOf(RuntimeException.class); + } + + @Test + void exactOtpIsConsumedAndFailedPasswordCannotConsumeIt() { + account.setLoginAuthModes("EMAIL_OTP"); + var otp = new AccountEmailLoginChallenge(); + otp.setId(3L); + otp.setAccountId(account.getId()); + otp.setCodeHash(hash("test-only-otp")); + otp.setExpiresAt(LocalDateTime.now().plusMinutes(1)); + when(accounts.findByEmail(account.getEmail())).thenReturn(Optional.of(account)); + when(challenges.findByAccountId(account.getId())).thenReturn(Optional.of(otp)); + assertThatThrownBy( + () -> primary.authenticateControlUiPrimaryIdentity(account.getEmail(), "wrong-secret")) + .isInstanceOf(RuntimeException.class); + verify(challenges, never()).delete(otp); + when(mapper.toDto(account)) + .thenReturn( + new AccountDto( + account.getAccountUuid().toString(), + account.getUsername(), + account.getEmail(), + "USER", + false)); + assertThat( + primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), "test-only-otp") + .accountId()) + .isEqualTo(account.getAccountUuid()); + verify(challenges).delete(otp); + } + + @Test + void missingAndReadOnlyTransactionDenyBeforeCredentialAccess() { + TransactionSynchronizationManager.clear(); + assertThatThrownBy( + () -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy( + () -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) + .isInstanceOf(IllegalStateException.class); + } + + private static String hash(String secret) { + char[] chars = secret.toCharArray(); + var argon = Argon2Factory.create(); + try { + return argon.hash(2, 4096, 1, chars); + } finally { + argon.wipeArray(chars); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java new file mode 100644 index 0000000000..bbc6417ef8 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java @@ -0,0 +1,182 @@ +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.verify; +import static org.mockito.Mockito.when; + +import io.lettuce.core.ClientOptions; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class AccountControlUiRegistryReaderTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String TOKEN_HASH = "a".repeat(64); + + @Test + void acceptsOnlyTheExactCanonicalActiveProfileRecord() throws Exception { + byte[] bytes = canonicalRecord(); + + var parsed = AccountControlUiRegistryReader.parseActiveRecord(bytes, TOKEN_HASH); + + assertThat(parsed).containsEntry("tokenHash", TOKEN_HASH).containsEntry("state", "active"); + } + + @Test + void rejectsUnknownFieldsAndNonCanonicalBytes() throws Exception { + Map extended = new LinkedHashMap<>(record()); + extended.put("unexpected", true); + byte[] withUnknown = canonicalBytes(extended); + + assertThatThrownBy( + () -> AccountControlUiRegistryReader.parseActiveRecord(withUnknown, TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + + Map missingDeadline = new LinkedHashMap<>(record()); + missingDeadline.remove("registryCleanupDeadlineEpochMillis"); + assertThatThrownBy( + () -> + AccountControlUiRegistryReader.parseActiveRecord( + canonicalBytes(missingDeadline), TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + + String canonical = new String(canonicalRecord(), StandardCharsets.UTF_8); + byte[] nonCanonical = (" " + canonical).getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> AccountControlUiRegistryReader.parseActiveRecord(nonCanonical, TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void readsOnlyAfterLiveAclIdentityAndExactExpiryReadback() throws Exception { + byte[] active = canonicalRecord(); + long deadline = 1_800_000_300_000L; + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(active); + when(commands.pexpiretime(any(byte[].class))).thenReturn(deadline); + + AccountCoordinationPinnedConnectionProvider provider = () -> connection; + byte[] observed = new AccountControlUiRegistryReader(provider).readActive(TOKEN_HASH); + + assertThat(observed).isEqualTo(active).isNotSameAs(active); + verify(commands).aclWhoami(); + verify(commands).pexpiretime(any(byte[].class)); + } + + @Test + void deniesWhenPhysicalExpiryDiffersFromExactCleanupDeadline() throws Exception { + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + ClientOptions options = mock(ClientOptions.class); + @SuppressWarnings("unchecked") + RedisCommands commands = mock(RedisCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.getOptions()).thenReturn(options); + when(options.isAutoReconnect()).thenReturn(false); + when(connection.sync()).thenReturn(commands); + when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); + when(commands.get(any(byte[].class))).thenReturn(canonicalRecord()); + when(commands.pexpiretime(any(byte[].class))).thenReturn(1_800_000_000_000L); + + AccountControlUiRegistryReader reader = new AccountControlUiRegistryReader(() -> connection); + + assertThatThrownBy(() -> reader.readActive(TOKEN_HASH)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void acceptsExactCleanupDeadlineAndRejectsMissingOrOutOfRangeEvidence() { + assertThat( + AccountControlUiRegistryReader.checkedCleanupDeadlineMillis( + 1_800_000_000L, 1_800_000_300_000L)) + .isEqualTo(1_800_000_300_000L); + assertThatThrownBy( + () -> AccountControlUiRegistryReader.checkedCleanupDeadlineMillis(1_800_000_000L, null)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + AccountControlUiRegistryReader.checkedCleanupDeadlineMillis( + 1_800_000_000L, 1_799_999_999_999L)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + AccountControlUiRegistryReader.checkedCleanupDeadlineMillis( + Long.MAX_VALUE, 9_007_199_254_740_991L)) + .isInstanceOf(IllegalStateException.class); + } + + private static Map record() { + Map tuple = + Map.of( + "issuerAuthGeneration", 1, + "accountAuthorityGeneration", 1, + "tenantAuthorityGeneration", Map.of("20000000-0000-4000-8000-000000000002", 1), + "membershipAuthorityGeneration", Map.of("20000000-0000-4000-8000-000000000002", 1), + "privateRealmGrantVersions", List.of()); + return Map.ofEntries( + Map.entry("schemaVersion", 1), + Map.entry("registryVersion", 2), + Map.entry("tokenHash", TOKEN_HASH), + Map.entry("kid", "key-1"), + Map.entry("signerGeneration", "1"), + Map.entry("issuer", "firemud-account-service"), + Map.entry("profile", "control-ui"), + Map.entry("type", "control-ui"), + Map.entry("audience", "control-ui"), + Map.entry("accountId", "10000000-0000-4000-8000-000000000001"), + Map.entry("jti", UUID.fromString("30000000-0000-4000-8000-000000000003").toString()), + Map.entry("iat", 1_799_999_700), + Map.entry("nbf", 1_799_999_700), + Map.entry("exp", 1_800_000_000), + Map.entry("tokenGeneration", 1), + Map.entry("authorityTuple", tuple), + Map.entry("membershipVersion", Map.of("20000000-0000-4000-8000-000000000002", 1)), + Map.entry("issuanceFence", 1), + Map.entry("operationId", "40000000-0000-4000-8000-000000000004"), + Map.entry("requestId", "50000000-0000-4000-8000-000000000005"), + Map.entry("requestDigest", "b".repeat(64)), + Map.entry("registryCleanupDeadlineEpochMillis", 1_800_000_300_000L), + Map.entry("state", "active"), + Map.entry( + "authoritySourceVersions", Map.of("ACCOUNT:10000000-0000-4000-8000-000000000001", 1)), + Map.entry( + "authEvidenceBundle", + Map.of( + "bundleVersion", + "1", + "sourceVersion", + "1", + "sourceFence", + "1", + "linearization", + "1", + "canonicalSha256", + "c".repeat(64))), + Map.entry("originalSignerReceiptDigest", "d".repeat(64))); + } + + private static byte[] canonicalRecord() throws Exception { + return canonicalBytes(record()); + } + + private static byte[] canonicalBytes(Object value) throws Exception { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptographyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptographyTest.java new file mode 100644 index 0000000000..393a76858a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptographyTest.java @@ -0,0 +1,102 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Test-only custody files; no production mount, registry or issuer provenance is asserted. */ +class AccountControlUiResponseCryptographyTest { + @TempDir Path temporary; + private static final Instant NOW = Instant.parse("2026-10-08T11:00:00Z"); + + @Test + void recoversOnlyOriginalBoundedBytesAndExactOwnerBinding() throws Exception { + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 29); + var crypto = crypto(NOW); + byte[] credential = bytes("test-only-credential-not-a-production-token"); + byte[] binding = bytes("test-only/exact-owner/request1/actor1/tenant1/fence1"); + byte[] sealed = crypto.seal(credential, binding, NOW.plusSeconds(60)); + for (int offset = 0; offset <= sealed.length - credential.length; offset++) { + assertThat( + Arrays.equals( + sealed, offset, offset + credential.length, credential, 0, credential.length)) + .as("Encrypted envelope must not contain contiguous plaintext at offset %s", offset) + .isFalse(); + } + assertThat(crypto.open(sealed, binding, NOW.plusSeconds(60))).isEqualTo(credential); + assertThatThrownBy(() -> crypto.open(sealed, bytes("different-owner"), NOW.plusSeconds(60))) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + assertThatThrownBy(() -> crypto.open(sealed, binding, NOW.plusSeconds(59))) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + assertThatThrownBy(() -> crypto(NOW.plusSeconds(60)).open(sealed, binding, NOW.plusSeconds(60))) + .isInstanceOf(AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException.class); + } + + @Test + void requestMacIsExactKeyedAndIndependentFromEncryptionCustody() throws Exception { + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 29); + var crypto = crypto(NOW); + assertThat(crypto.currentKeyId()).isEqualTo("mac1"); + String original = crypto.requestDigest("mac1", bytes("test-only-secret/actor/tenant/request")); + assertThat(original).matches("[0-9a-f]{64}"); + assertThat(crypto.requestDigest("mac1", bytes("test-only-secret/actor/tenant/request"))) + .isEqualTo(original); + assertThat(crypto.requestDigest("mac1", bytes("changed-secret/actor/tenant/request"))) + .isNotEqualTo(original); + custody("request-mac", "mac2", 31); + assertThat(crypto.requestDigest("mac2", bytes("test-only-secret/actor/tenant/request"))) + .isNotEqualTo(original); + assertThatThrownBy(() -> crypto.requestDigest("mac1", bytes("exact-request"))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void absentWithdrawnAndSharedPurposeMaterialFailClosed() throws Exception { + assertThatThrownBy(() -> crypto(NOW).currentKeyId()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + custody("encryption", "enc1", 11); + custody("request-mac", "mac1", 11); + assertThatThrownBy(() -> crypto(NOW).requestDigest("mac1", bytes("test-only-presentation"))) + .isInstanceOf(IllegalStateException.class); + custody("request-mac", "mac1", 29); + byte[] binding = bytes("test-only-owner"); + byte[] envelope = crypto(NOW).seal(bytes("test-only-credential"), binding, NOW.plusSeconds(60)); + Files.delete(temporary.resolve("encryption/keyring")); + assertThatThrownBy(() -> crypto(NOW).open(envelope, binding, NOW.plusSeconds(60))) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } + + private AccountControlUiResponseCryptography crypto(Instant now) { + return new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(temporary), Clock.fixed(now, ZoneOffset.UTC)); + } + + private void custody(String purpose, String id, int value) throws Exception { + byte[] key = new byte[32]; + Arrays.fill(key, (byte) value); + Path directory = Files.createDirectories(temporary.resolve(purpose)); + Files.writeString( + directory.resolve("keyring"), + "firemud-account-response-envelope-keyring-v1\nactive " + + id + + " " + + Base64.getUrlEncoder().withoutPadding().encodeToString(key) + + "\n"); + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java new file mode 100644 index 0000000000..196f0f5945 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java @@ -0,0 +1,476 @@ +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.ArgumentMatchers.anyString; +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.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.time.Clock; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import org.jooq.Record; +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.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Actual RSA/profile verification and mounted signing. Registry, Account source, historical signer + * and transaction collaborators below are EXPLICIT SERVICE DOUBLES. No production credential, + * original lifecycle provenance, SQL transaction or physical mTLS/Coordination proof is asserted. + */ +class AccountControlUiSigningAndActorTest { + private static final Instant NOW = Instant.parse("2026-10-08T11:00:00Z"); + private static KeyPair key; + @TempDir Path temporary; + + @BeforeAll + static void key() throws Exception { + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + key = generator.generateKeyPair(); + } + + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void distinctMountedSignerProducesExactOriginalProfileAndWipesCallbackCredential() + throws Exception { + Fixture f = new Fixture(); + Path privateRoot = Files.createDirectory(temporary.resolve("private")); + Path publicRoot = Files.createDirectory(temporary.resolve("public")); + String fingerprint = + AccountControlUiIssuanceRepository.hash( + AccountControlUiAuthority.canonical( + Map.of("kty", "RSA", "n", f.modulus, "e", f.exponent))); + var expected = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + "test-control", + "test-cluster", + "test-control", + UUID.randomUUID().toString(), + "1", + "test-only-control", + fingerprint); + Files.write( + privateRoot.resolve("current.key"), + AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("version", 1), + Map.entry("environmentId", expected.environmentId()), + Map.entry("clusterId", expected.clusterId()), + Map.entry("namespace", expected.namespace()), + Map.entry("operationId", expected.operationId()), + Map.entry("generation", expected.generation()), + Map.entry("kid", expected.kid()), + Map.entry("algorithm", "RS256"), + Map.entry("privateKeyPkcs8", b64(key.getPrivate().getEncoded())), + Map.entry("publicKeyFingerprint", fingerprint)))); + Files.write(publicRoot.resolve("jwks.json"), f.jwks); + var spec = + new AccountControlUiSigningSpec( + f.operationId, f.requestId, f.jti, f.snapshot, NOW, NOW.plusSeconds(300)); + AtomicReference retained = new AtomicReference<>(); + AtomicReference callback = new AtomicReference<>(); + String digest = + AccountMountedJwtSignerBundle.signCommittedControlUiDigest( + privateRoot, + Path.of("current.key"), + publicRoot, + Path.of("jwks.json"), + expected, + spec, + (hash, bytes) -> { + callback.set(bytes); + retained.set(bytes.clone()); + assertThat(hash).isEqualTo(AccountControlUiIssuanceRepository.hash(bytes)); + }); + assertThat(callback.get()).containsOnly((byte) 0); + assertThat(digest).isEqualTo(AccountControlUiIssuanceRepository.hash(retained.get())); + var verified = f.actors.verifySigned(new String(retained.get(), StandardCharsets.US_ASCII)); + var verifiedAgain = + f.actors.verifySigned(new String(retained.get(), StandardCharsets.US_ASCII)); + assertThat(verified.claims.claims()) + .containsEntry("accountId", f.actor.toString()) + .containsEntry("scopedRoles", Map.of(f.tenant.toString(), List.of("tenantAdmin"))); + assertThat(verifiedAgain.claims.claims()).isEqualTo(verified.claims.claims()); + assertThat(verified.claims.claims()) + .doesNotContainKeys("globalRoles", "tokenProfile", "tokenType"); + verify(f.source, times(1)).sourceIdentity(); + verify(f.source, times(1)).load(); + } + + @Test + void signedControlUiNeedsExactActiveOwnerAndIndependentCurrentCreatorSources() throws Exception { + Fixture f = new Fixture(); + String compact = f.sign(f.claims); + f.owner(compact); + var actor = f.actors.authenticate(compact, f.tenant, f.environment); + assertThat(actor.accountId()).isEqualTo(f.actor); + assertThat(actor.tenantId()).isEqualTo(f.tenant); + assertThat(actor.toString()) + .isEqualTo("AccountControlUiActorService.AuthenticatedActor[redacted]"); + assertThatThrownBy(() -> f.actors.authenticate(compact, UUID.randomUUID(), f.environment)) + .isInstanceOf(IllegalStateException.class); + when(f.snapshot.evidence()).thenReturn(new byte[] {99}); + assertThatThrownBy(() -> f.actors.authenticate(compact, f.tenant, f.environment)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void committedCurrentnessByJtiRunsActionWithExactRegistryAndSourceInsideOwnerTransaction() + throws Exception { + Fixture f = new Fixture(); + String compact = f.sign(f.claims); + f.owner(compact); + when(f.signers.requireOriginal(any(byte[].class))) + .thenReturn(mock(AccountControlUiSignerOwner.Capture.class)); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new byte[] {12}; + }) + .when(f.registry) + .readActive(anyString()); + doAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return f.snapshot; + }) + .when(f.authority) + .capture(f.actor, f.tenant, f.environment); + + String selectedActor = + f.actors.withCurrentCommitted( + f.actor, + f.tenant, + f.jti, + f.environment, + current -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(current.stored()).isSameAs(f.stored); + return current.source().actor().toString(); + }); + + assertThat(selectedActor).isEqualTo(f.actor.toString()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + } + + @Test + void committedCurrentnessByJtiRejectsChangedAccountSourceBeforeReturningActor() throws Exception { + Fixture f = new Fixture(); + String compact = f.sign(f.claims); + f.owner(compact); + when(f.signers.requireOriginal(any(byte[].class))) + .thenReturn(mock(AccountControlUiSignerOwner.Capture.class)); + var changed = mock(AccountControlUiAuthority.Snapshot.class); + when(changed.evidence()).thenReturn(new byte[] {99}); + when(f.authority.capture(f.actor, f.tenant, f.environment)).thenReturn(changed); + + assertThatThrownBy( + () -> + f.actors.withCurrentCommitted( + f.actor, f.tenant, f.jti, f.environment, current -> current.source().actor())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void committedCurrentnessByJtiRejectsRevokedOrMismatchedRegistryBeforeSourceRead() + throws Exception { + Fixture revoked = new Fixture(); + String revokedCompact = revoked.sign(revoked.claims); + revoked.owner(revokedCompact); + String revokedHash = + AccountControlUiIssuanceRepository.hash(revokedCompact.getBytes(StandardCharsets.US_ASCII)); + doThrow(new IllegalStateException("test-only revoked token")) + .when(revoked.registry) + .readActive(revokedHash); + assertThatThrownBy( + () -> + revoked.actors.withCurrentCommitted( + revoked.actor, + revoked.tenant, + revoked.jti, + revoked.environment, + current -> current.source().actor())) + .isInstanceOf(IllegalStateException.class); + verify(revoked.authority, never()).capture(revoked.actor, revoked.tenant, revoked.environment); + + Fixture mismatched = new Fixture(); + String mismatchedCompact = mismatched.sign(mismatched.claims); + mismatched.owner(mismatchedCompact); + String mismatchedHash = + AccountControlUiIssuanceRepository.hash( + mismatchedCompact.getBytes(StandardCharsets.US_ASCII)); + doReturn(new byte[] {99}).when(mismatched.registry).readActive(mismatchedHash); + assertThatThrownBy( + () -> + mismatched.actors.withCurrentCommitted( + mismatched.actor, + mismatched.tenant, + mismatched.jti, + mismatched.environment, + current -> current.source().actor())) + .isInstanceOf(IllegalStateException.class); + verify(mismatched.authority, never()) + .capture(mismatched.actor, mismatched.tenant, mismatched.environment); + } + + @Test + void readinessGameplayForgedAndMissingRegistryCredentialsNeverCreateActor() throws Exception { + Fixture f = new Fixture(); + for (String audience : + List.of("account-service", "firemud-account-jwt-readiness", "player-bootstrap")) { + var wrong = new HashMap<>(f.claims); + wrong.put("aud", audience); + assertThatThrownBy(() -> f.actors.authenticate(f.sign(wrong), f.tenant, f.environment)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + } + String compact = f.sign(f.claims); + String forged = compact.substring(0, compact.lastIndexOf('.') + 1) + "A".repeat(512); + assertThatThrownBy(() -> f.actors.authenticate(forged, f.tenant, f.environment)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + when(f.registry.readActive(anyString())) + .thenThrow(new IllegalStateException("test-only missing/inactive registry")); + assertThatThrownBy(() -> f.actors.authenticate(compact, f.tenant, f.environment)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void spoofedSubjectDifferentInitialAssociationAndHistoricalSignerFailureDeny() throws Exception { + Fixture f = new Fixture(); + var wrong = new HashMap<>(f.claims); + wrong.put("sub", UUID.randomUUID().toString()); + assertThatThrownBy(() -> f.actors.authenticate(f.sign(wrong), f.tenant, f.environment)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + String compact = f.sign(f.claims); + f.owner(compact); + when(f.authority.capture(f.actor, f.tenant, f.environment)) + .thenThrow(new IllegalStateException("test-only changed initial association")); + assertThatThrownBy(() -> f.actors.authenticate(compact, f.tenant, f.environment)) + .isInstanceOf(IllegalStateException.class); + doReturn(f.snapshot).when(f.authority).capture(f.actor, f.tenant, f.environment); + when(f.signers.requireOriginal(any(byte[].class))) + .thenThrow(new IllegalStateException("test-only absent original receipt")); + assertThatThrownBy(() -> f.actors.authenticate(compact, f.tenant, f.environment)) + .isInstanceOf(IllegalStateException.class); + } + + private static final class Fixture { + final UUID actor = UUID.randomUUID(), tenant = UUID.randomUUID(), jti = UUID.randomUUID(); + final UUID operationId = UUID.randomUUID(), requestId = UUID.randomUUID(); + final String modulus = unsigned(((RSAPublicKey) key.getPublic()).getModulus()); + final String exponent = unsigned(((RSAPublicKey) key.getPublic()).getPublicExponent()); + final byte[] jwks = + AccountControlUiAuthority.canonical( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "kid", + "test-only-control", + "use", + "sig", + "alg", + "RS256", + "key_ops", + List.of("verify"), + "n", + modulus, + "e", + exponent)))); + final AccountControlUiAuthority.Snapshot snapshot = + mock(AccountControlUiAuthority.Snapshot.class); + final AccountControlUiAuthority authority = mock(AccountControlUiAuthority.class); + final AccountControlUiIssuanceRepository operations = + mock(AccountControlUiIssuanceRepository.class); + final AccountControlUiSignerOwner signers = mock(AccountControlUiSignerOwner.class); + final AccountControlUiCoordination registry = mock(AccountControlUiCoordination.class); + final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + final AccountJwtJwksTrustedSource source = mock(AccountJwtJwksTrustedSource.class); + final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + final AccountPublicJwksCache.SourceIdentity pin = + new AccountPublicJwksCache.SourceIdentity( + "test-control", + "test-cluster", + UUID.randomUUID().toString(), + "test-control", + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + "test-revision", + "https://test-api.example.test:6443", + "a".repeat(64)); + final AccountControlUiActorService actors; + final Map claims; + AccountControlUiIssuanceRepository.Stored stored; + + Fixture() { + when(snapshot.actor()).thenReturn(actor); + when(snapshot.tenant()).thenReturn(tenant); + when(snapshot.authorityTuple()) + .thenReturn( + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 1L, + "tenantAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "membershipAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "privateRealmGrantVersions", + List.of())); + when(snapshot.membershipVersion()).thenReturn(Map.of(tenant.toString(), 2L)); + when(snapshot.issuanceFence()).thenReturn(1L); + when(snapshot.evidence()).thenReturn(new byte[] {7}); + claims = + new AccountControlUiSigningSpec( + operationId, requestId, jti, snapshot, NOW, NOW.plusSeconds(300)) + .claims(); + when(source.sourceIdentity()).thenReturn(pin); + when(source.load()).thenReturn(new AccountPublicJwksCache.PublicJwksSnapshot(pin, jwks)); + when(transactions.getTransaction(any())) + .thenAnswer( + ignored -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); + doAnswer( + ignored -> { + TransactionSynchronizationManager.clear(); + return null; + }) + .when(transactions) + .commit(any()); + doAnswer( + ignored -> { + TransactionSynchronizationManager.clear(); + return null; + }) + .when(transactions) + .rollback(any()); + actors = + new AccountControlUiActorService( + operations, + authority, + signers, + registry, + source, + mock(DraftAuthorizationFenceRepository.class), + transactions, + Clock.fixed(NOW, ZoneOffset.UTC)); + } + + void owner(String compact) { + String hash = + AccountControlUiIssuanceRepository.hash(compact.getBytes(StandardCharsets.US_ASCII)); + Map values = new HashMap<>(); + values.put("request_id", requestId); + values.put("operation_id", operationId); + values.put("token_jti", jti); + values.put("account_uuid", actor); + values.put("tenant_uuid", tenant); + values.put("caller_context_id", UUID.randomUUID()); + values.put("caller_workload", "test-only-peer"); + values.put("request_mac_key_id", "test-only-mac"); + values.put("request_digest", "a".repeat(64)); + values.put("status", "COMMITTED"); + values.put("token_hash", hash); + values.put("claims_payload", AccountControlUiAuthority.canonical(claims)); + values.put("source_payload", new byte[] {7}); + values.put("bundle_payload", new byte[] {8}); + values.put( + "signer_receipt", + AccountControlUiAuthority.canonical( + Map.ofEntries( + Map.entry("kid", "test-only-control"), + Map.entry("environmentId", pin.environmentId()), + Map.entry("clusterId", pin.clusterId()), + Map.entry("clusterIncarnationUid", pin.clusterIncarnationUid()), + Map.entry("namespace", pin.namespace()), + Map.entry("namespaceUid", pin.namespaceUid()), + Map.entry("publicConfigMapUid", pin.configMapUid()), + Map.entry("apiConfigRevision", pin.bindingRevision())))); + values.put("pending_registry", new byte[] {11}); + values.put("active_registry", new byte[] {12}); + values.put("issued_at_epoch_second", NOW.getEpochSecond()); + values.put("expires_at_epoch_second", NOW.plusSeconds(300).getEpochSecond()); + values.put("registry_cleanup_deadline_epoch_millis", NOW.plusSeconds(600).toEpochMilli()); + values.put( + "recovery_expires_at", OffsetDateTime.ofInstant(NOW.plusSeconds(60), ZoneOffset.UTC)); + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(invocation -> values.get(invocation.getArgument(0))); + stored = new AccountControlUiIssuanceRepository.Stored(row); + when(operations.findToken(hash)).thenReturn(stored); + when(operations.findTokenJti(jti)).thenReturn(stored); + when(registry.readActive(hash)).thenReturn(new byte[] {12}); + when(authority.capture(actor, tenant, environment)).thenReturn(snapshot); + var committed = mock(AccountControlUiIssuanceRepository.Committed.class); + when(committed.tokenHash()).thenReturn(hash); + when(operations.requireCommitted(stored)).thenReturn(committed); + } + + String sign(Map value) throws Exception { + String input = + b64( + AccountControlUiAuthority.canonical( + Map.of("alg", "RS256", "kid", "test-only-control", "typ", "JWT"))) + + "." + + b64(AccountControlUiAuthority.canonical(value)); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(key.getPrivate()); + signer.update(input.getBytes(StandardCharsets.US_ASCII)); + return input + "." + b64(signer.sign()); + } + } + + private static String unsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + if (bytes[0] == 0) { + bytes = Arrays.copyOfRange(bytes, 1, bytes.length); + } + return b64(bytes); + } + + private static String b64(byte[] bytes) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } +} 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 new file mode 100644 index 0000000000..7069c36ceb --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java @@ -0,0 +1,596 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +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.service.session.AccountJwtJwksConfigMapClient.ApiSession; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasConflictException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.Outcome; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ResourceMissingException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtJwksConfigMapClientTest { + private static final String NAMESPACE = "firemud-prod"; + private static final String KUBE_SYSTEM_UID = "11111111-1111-4111-8111-111111111111"; + private static final String TARGET_NAMESPACE_UID = "22222222-2222-4222-8222-222222222222"; + private static final String CONFIG_MAP_UID = "33333333-3333-4333-8333-333333333333"; + private static final String API_USERNAME = "system:serviceaccount:firemud-prod:account-service"; + private static final String JWKS_OLD = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"old\"}]}"; + private static final String JWKS_NEW = "{\"keys\":[{\"kty\":\"RSA\",\"kid\":\"new\"}]}"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @org.junit.jupiter.api.Test + void observesOnlyFixedConfigMapAfterPrincipalAndNamespaceChecks() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + + ConfigMapSnapshot observed = client.observe(); + + assertThat(observed.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(observed.resourceVersion()).isEqualTo("41"); + assertThat(observed.data()).containsEntry("unrelated.txt", "retain"); + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + assertThat(api.calls) + .allMatch( + call -> + Set.of( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP, + ApiCall.PATCH_JWKS_CONFIG_MAP) + .contains(call)); + } + + @org.junit.jupiter.api.Test + void absentPrecreatedConfigMapFailsWithoutCreateOrWrite() { + FakeKubernetesApi api = new FakeKubernetesApi(); + api.resourceExists = false; + AccountJwtJwksConfigMapClient client = client(api); + + assertThatThrownBy(client::observe).isInstanceOf(ResourceMissingException.class); + + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + assertThat(api.patchCount).isZero(); + } + + @org.junit.jupiter.api.Test + void oversizedConfigMapResponseIsRejectedAtTheBound() { + FakeKubernetesApi api = new FakeKubernetesApi(); + api.oversizedConfigMapResponse = true; + + assertThatThrownBy(() -> client(api).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.ApiFailureException.class); + + assertThat(api.patchCount).isZero(); + } + + @org.junit.jupiter.api.Test + void rejectsWrongAccountPrincipalAndEitherNamespaceIncarnationBeforeConfigMapRead() { + FakeKubernetesApi wrongPrincipal = new FakeKubernetesApi(); + wrongPrincipal.authenticatedUsername = "system:serviceaccount:firemud-prod:firemud-app"; + assertThatThrownBy(() -> client(wrongPrincipal).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongPrincipal.calls).containsExactly(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL); + + FakeKubernetesApi wrongCluster = new FakeKubernetesApi(); + wrongCluster.kubeSystemUid = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + assertThatThrownBy(() -> client(wrongCluster).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongCluster.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, ApiCall.READ_KUBE_SYSTEM_NAMESPACE); + + FakeKubernetesApi wrongNamespace = new FakeKubernetesApi(); + wrongNamespace.targetNamespaceUid = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + assertThatThrownBy(() -> client(wrongNamespace).observe()) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(wrongNamespace.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE); + } + + @org.junit.jupiter.api.Test + void rejectsChangedProtectedTrustBeforeWrite() { + FakeKubernetesApi api = new FakeKubernetesApi(); + ConfigMapSnapshot expected = client(api).observe(); + api.rejectPatchForChangedTrust = true; + + assertThatThrownBy(() -> client(api).publish(expected, desired("op-7"))) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + + assertThat(api.patchCount).isZero(); + assertThat(api.data.get(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY)).isEqualTo(JWKS_OLD); + } + + @org.junit.jupiter.api.Test + void bearerRenewalIsAcceptedOnlyBeforeACompleteOperationAndModeOrOwnerDriftIsRejected() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + + client.observe(); + api.bearerToken = "rotated-token"; + api.bearerFileKey = "rotated-inode"; + assertThat(client.observe().uid()).isEqualTo(CONFIG_MAP_UID); + + api.calls.clear(); + api.bearerMode = "0444"; + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).isEmpty(); + + api.bearerMode = "0440"; + api.bearerOwnerUid = 1001; + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).isEmpty(); + } + + @org.junit.jupiter.api.Test + void bearerRotationMidVerificationCannotSplitSelfReviewFromConfigMapRead() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + api.rotateBearerAfterSelfReview = true; + + assertThatThrownBy(client::observe) + .isInstanceOf(AccountJwtJwksConfigMapClient.BindingRejectedException.class); + assertThat(api.calls).containsExactly(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL); + + api.calls.clear(); + assertThat(client.observe().uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(api.calls) + .containsExactly( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP); + } + + @org.junit.jupiter.api.Test + void compareAndSetConflictNeverOverwritesChangedResourceVersion() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + api.resourceVersion = "42"; + api.data.put("another-writer", "preserved"); + + assertThatThrownBy(() -> client.publish(expected, desired("op-8"))) + .isInstanceOf(CasConflictException.class); + + assertThat(api.patchCount).isZero(); + assertThat(api.data).containsEntry("another-writer", "preserved"); + } + + @org.junit.jupiter.api.Test + void resourceReplacementAndApiConflictAreBothFenced() { + FakeKubernetesApi replacement = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient replacementClient = client(replacement); + ConfigMapSnapshot expected = replacementClient.observe(); + replacement.configMapUid = "44444444-4444-4444-8444-444444444444"; + + assertThatThrownBy(() -> replacementClient.publish(expected, desired("op-replaced"))) + .isInstanceOf(CasConflictException.class); + assertThat(replacement.patchCount).isZero(); + + FakeKubernetesApi inFlightConflict = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient inFlightClient = client(inFlightConflict); + ConfigMapSnapshot beforePatch = inFlightClient.observe(); + inFlightConflict.conflictNextPatch = true; + + assertThatThrownBy(() -> inFlightClient.publish(beforePatch, desired("op-conflict"))) + .isInstanceOf(CasConflictException.class); + assertThat(inFlightConflict.patchCount).isEqualTo(1); + assertThat(inFlightConflict.data.get(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY)) + .isEqualTo(JWKS_OLD); + } + + @org.junit.jupiter.api.Test + void rejectsPrivateJwkMaterialBeforeAnyApiCall() { + FakeKubernetesApi api = new FakeKubernetesApi(); + Map privateJwks = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + "{\"keys\":[{\"kty\":\"RSA\",\"d\":\"private\"}]}", + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("op-private")); + + assertThatThrownBy( + () -> + client(api) + .publish(new ConfigMapSnapshot(CONFIG_MAP_UID, "41", Map.of()), privateJwks)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account public JWKS contains private material"); + + assertThat(api.calls).isEmpty(); + } + + @org.junit.jupiter.api.Test + void lostPatchAcknowledgementSucceedsOnlyAfterExactSameUidContentReadback() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + Map desired = desired("durable-operation-9"); + api.loseNextPatchAcknowledgement = true; + + CasObservation result = client.publish(expected, desired); + + assertThat(result.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(result.uid()).isEqualTo(CONFIG_MAP_UID); + assertThat(result.priorResourceVersion()).isEqualTo("41"); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.publishedData()).isEqualTo(desired); + assertThat(api.patchCount).isEqualTo(1); + } + + @org.junit.jupiter.api.Test + void exactDataAtTheUnchangedExpectedVersionIsNotReportedAsCasSuccess() { + FakeKubernetesApi api = new FakeKubernetesApi(); + Map desired = desired("already-present-operation"); + api.data.putAll(desired); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + + assertThatThrownBy(() -> client.publish(expected, desired)) + .isInstanceOf(CasConflictException.class) + .hasMessage("Account public JWKS ConfigMap compare-and-set conflict"); + + assertThat(api.patchCount).isZero(); + assertThat(api.resourceVersion).isEqualTo(expected.resourceVersion()); + } + + @org.junit.jupiter.api.Test + void updatePreservesUnrelatedDataAndPatchContainsOnlyOwnedPublicEntries() throws Exception { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot expected = client.observe(); + Map desired = desired("durable-operation-10"); + + CasObservation result = client.publish(expected, desired); + + assertThat(result.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.publishedData()).isEqualTo(desired); + assertThat(api.data) + .containsEntry("unrelated.txt", "retain") + .containsEntry(AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, JWKS_NEW) + .containsEntry( + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, marker("durable-operation-10")); + JsonNode patch = JSON.readTree(api.lastPatch); + assertThat(patch.get("metadata").size()).isEqualTo(2); + assertThat(patch.get("metadata").get("uid").asText()).isEqualTo(CONFIG_MAP_UID); + assertThat(patch.get("metadata").get("resourceVersion").asText()).isEqualTo("41"); + assertThat(patch.get("data").size()).isEqualTo(2); + assertThat(patch.get("data").has("unrelated.txt")).isFalse(); + } + + @org.junit.jupiter.api.Test + void activeMarkerCasUsesFreshSnapshotAndPreservesUnrelatedEntries() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot observed = client.observe(); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + + CasObservation result = client.publishActiveProjection(observed, "41", desired); + + assertThat(result.outcome()).isEqualTo(Outcome.APPLIED); + assertThat(result.priorResourceVersion()).isEqualTo("41"); + assertThat(result.resourceVersion()).isEqualTo("42"); + assertThat(result.readbackData()).containsEntry("unrelated.txt", "retain"); + assertThat(api.patchCount).isEqualTo(1); + } + + @org.junit.jupiter.api.Test + void activeMarkerLostAcknowledgementReplayRequiresAdvancedResourceVersion() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + ConfigMapSnapshot observed = client.observe(); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + api.loseNextPatchAcknowledgement = true; + + CasObservation applied = client.publishActiveProjection(observed, "41", desired); + + assertThat(applied.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(applied.priorResourceVersion()).isEqualTo("41"); + assertThat(applied.resourceVersion()).isEqualTo("42"); + int writes = api.patchCount; + CasObservation replay = client.publishActiveProjection(client.observe(), "41", desired); + + assertThat(replay.outcome()).isEqualTo(Outcome.EXACT_REPLAY); + assertThat(replay.priorResourceVersion()).isEqualTo("41"); + assertThat(replay.resourceVersion()).isEqualTo("42"); + assertThat(api.patchCount).isEqualTo(writes); + assertThat(api.data).containsEntry("unrelated.txt", "retain"); + } + + @org.junit.jupiter.api.Test + void activeMarkerDoesNotTreatExactDataAtUnchangedPriorVersionAsSuccessfulCas() { + FakeKubernetesApi api = new FakeKubernetesApi(); + AccountJwtJwksConfigMapClient client = client(api); + Map desired = + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker("active-operation")); + api.data.putAll(desired); + ConfigMapSnapshot observed = client.observe(); + + assertThatThrownBy(() -> client.publishActiveProjection(observed, "41", desired)) + .isInstanceOf(CasConflictException.class); + assertThat(api.patchCount).isZero(); + assertThat(api.resourceVersion).isEqualTo("41"); + } + + @org.junit.jupiter.api.Test + void jwksConfigMapAccessHasNoSecretListCreateOrDeleteCapability() { + assertThat(ApiCall.values()) + .noneMatch( + call -> + call.name().contains("SECRET") + || call.name().contains("CREATE") + || call.name().contains("DELETE")); + assertThat(ApiCall.values()) + .filteredOn(call -> call.name().contains("JWKS_CONFIG_MAP")) + .containsExactly(ApiCall.READ_JWKS_CONFIG_MAP, ApiCall.PATCH_JWKS_CONFIG_MAP); + assertThat(ApiCall.values()) + .filteredOn(call -> call.name().contains("LIST")) + .containsExactly(ApiCall.LIST_VALIDATOR_PODS); + } + + private static AccountJwtJwksConfigMapClient client(FakeKubernetesApi api) { + return new AccountJwtJwksConfigMapClient(api::beginOperation); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "These fixed paths model the protected Account API CA and projected bearer-token trust inputs; the test never reads them.") + private static ParsedBinding parsedBinding() { + return new ParsedBinding( + "revision-1", + "prod", + "prod-cluster-1", + URI.create("https://kubernetes.example:6443/"), + "kubernetes.example", + java.nio.file.Path.of("/etc/firemud/kubernetes-ca.pem"), + "a".repeat(64), + java.nio.file.Path.of("/var/run/secrets/firemud/kubernetes/token"), + NAMESPACE, + KUBE_SYSTEM_UID, + TARGET_NAMESPACE_UID, + API_USERNAME, + "b".repeat(64)); + } + + private static Map desired(String operation) { + return Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_NEW, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + marker(operation)); + } + + private static String marker(String operation) { + return "{\"ownerOperation\":\"" + operation + "\"}"; + } + + private static String namespaceJson(String name, String uid) { + return "{\"apiVersion\":\"v1\",\"kind\":\"Namespace\",\"metadata\":{\"name\":\"" + + name + + "\",\"uid\":\"" + + uid + + "\"},\"status\":{\"phase\":\"Active\"}}"; + } + + private static final class FakeKubernetesApi { + private final List calls = new ArrayList<>(); + private final Map data = + new LinkedHashMap<>( + Map.of( + AccountJwtJwksConfigMapClient.JWKS_DATA_KEY, + JWKS_OLD, + AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, + "{\"ownerOperation\":\"old\"}", + "unrelated.txt", + "retain")); + private String authenticatedUsername = API_USERNAME; + private String kubeSystemUid = KUBE_SYSTEM_UID; + private String targetNamespaceUid = TARGET_NAMESPACE_UID; + private String configMapUid = CONFIG_MAP_UID; + private String resourceVersion = "41"; + private String bearerToken = "initial-token"; + private String bearerFileKey = "initial-inode"; + private long bearerOwnerUid; + private long bearerGroupId = 2000; + private String bearerMode = "0440"; + private boolean resourceExists = true; + private boolean oversizedConfigMapResponse; + private boolean rejectPatchForChangedTrust; + private boolean conflictNextPatch; + private boolean loseNextPatchAcknowledgement; + private boolean rotateBearerAfterSelfReview; + private int patchCount; + private String lastPatch; + private Long acceptedBearerOwnerUid; + private Long acceptedBearerGroupId; + private String acceptedBearerMode; + + private ApiSession beginOperation() { + if (acceptedBearerOwnerUid == null) { + acceptedBearerOwnerUid = bearerOwnerUid; + acceptedBearerGroupId = bearerGroupId; + acceptedBearerMode = bearerMode; + } + if (acceptedBearerOwnerUid != bearerOwnerUid + || acceptedBearerGroupId != bearerGroupId + || !acceptedBearerMode.equals(bearerMode)) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + return new FakeApiSession(this, bearerToken, bearerFileKey); + } + + private ApiResponse send(ApiCall call, byte[] body) { + calls.add(call); + ApiResponse response = + switch (call) { + case REVIEW_AUTHENTICATED_PRINCIPAL -> + response( + 201, + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\"," + + "\"status\":{\"userInfo\":{\"username\":\"" + + authenticatedUsername + + "\"}}}"); + case READ_KUBE_SYSTEM_NAMESPACE -> + response(200, namespaceJson("kube-system", kubeSystemUid)); + case READ_TARGET_NAMESPACE -> + response(200, namespaceJson(NAMESPACE, targetNamespaceUid)); + case READ_JWKS_CONFIG_MAP -> + !resourceExists + ? response(404, "{}") + : oversizedConfigMapResponse + ? response(200, " ".repeat(1024 * 1024 + 1)) + : response(200, configMapJson()); + case PATCH_JWKS_CONFIG_MAP -> patch(body); + case READ_VALIDATOR_DEPLOYMENT, LIST_VALIDATOR_PODS, READ_VALIDATOR_REPLICA_SET -> + throw new AssertionError("Unexpected validator call in ConfigMap client test"); + }; + if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL && rotateBearerAfterSelfReview) { + rotateBearerAfterSelfReview = false; + bearerToken = "rotated-during-operation"; + bearerFileKey = "rotated-during-operation-inode"; + } + return response; + } + + private ApiResponse patch(byte[] body) { + if (rejectPatchForChangedTrust) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + patchCount++; + lastPatch = new String(body, StandardCharsets.UTF_8); + if (conflictNextPatch) { + conflictNextPatch = false; + return response(409, "{}"); + } + JsonNode patch; + try { + patch = JSON.readTree(lastPatch); + } catch (Exception ex) { + throw new AssertionError(ex); + } + JsonNode metadata = patch.get("metadata"); + if (!CONFIG_MAP_UID.equals(metadata.get("uid").asText()) + || !resourceVersion.equals(metadata.get("resourceVersion").asText())) { + return response(409, "{}"); + } + JsonNode patchData = patch.get("data"); + patchData.properties().forEach(entry -> data.put(entry.getKey(), entry.getValue().asText())); + resourceVersion = Long.toString(Long.parseLong(resourceVersion) + 1); + if (loseNextPatchAcknowledgement) { + loseNextPatchAcknowledgement = false; + throw new AccountJwtJwksApiBinding.ApiTransportException(); + } + return response(200, configMapJson()); + } + + private String configMapJson() { + try { + Map metadata = + Map.of( + "name", AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME, + "namespace", NAMESPACE, + "uid", configMapUid, + "resourceVersion", resourceVersion); + Map object = + Map.of("apiVersion", "v1", "kind", "ConfigMap", "metadata", metadata, "data", data); + return JSON.writeValueAsString(object); + } catch (Exception ex) { + throw new AssertionError(ex); + } + } + + private static ApiResponse response(int status, String body) { + return new ApiResponse(status, body.getBytes(StandardCharsets.UTF_8)); + } + } + + private static final class FakeApiSession implements ApiSession { + private final FakeKubernetesApi api; + private final ParsedBinding binding = parsedBinding(); + private String bearerTokenSnapshot; + private String bearerFileKeySnapshot; + + private FakeApiSession(FakeKubernetesApi api, String token, String fileKey) { + this.api = api; + this.bearerTokenSnapshot = token; + this.bearerFileKeySnapshot = fileKey; + } + + @Override + public ParsedBinding binding() { + return binding; + } + + @Override + public ApiResponse send(ApiCall call, byte[] body) { + if (bearerTokenSnapshot == null + || !bearerTokenSnapshot.equals(api.bearerToken) + || !bearerFileKeySnapshot.equals(api.bearerFileKey) + || api.acceptedBearerOwnerUid != api.bearerOwnerUid + || api.acceptedBearerGroupId != api.bearerGroupId + || !api.acceptedBearerMode.equals(api.bearerMode)) { + throw new AccountJwtJwksApiBinding.BindingRejectedException(); + } + return api.send(call, body); + } + + @Override + public void close() { + bearerTokenSnapshot = null; + bearerFileKeySnapshot = null; + } + } +} 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 new file mode 100644 index 0000000000..509d581672 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java @@ -0,0 +1,741 @@ +package unit.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.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity; +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.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +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.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 org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.SimpleTransactionStatus; + +class AccountJwtJwksTrustedSourceTest { + private static final String ENVIRONMENT = "test"; + private static final String CLUSTER = "cluster-test"; + private static final String NAMESPACE = "firemud-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 API_BINDING_DIGEST = "a".repeat(64); + private static final String API_CA_DIGEST = "b".repeat(64); + private static final UUID INITIAL_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-000000000001"); + private static final UUID NEXT_OPERATION_ID = + UUID.fromString("55555555-5555-4555-8555-000000000002"); + 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 JWKS_1 = "{\"keys\":[" + JWK_1 + "]}"; + private static final String JWKS_1_AND_2 = "{\"keys\":[" + JWK_1 + "," + JWK_2 + "]}"; + + @Test + void derivesPinAndReturnsOnlyExactReceiptBackedPublicBytes() { + Fixture fixture = new Fixture(); + + SourceIdentity identity = fixture.source.sourceIdentity(); + PublicJwksSnapshot snapshot = fixture.source.load(); + + assertThat(identity.environmentId()).isEqualTo(ENVIRONMENT); + assertThat(identity.clusterId()).isEqualTo(CLUSTER); + assertThat(identity.clusterIncarnationUid()).isEqualTo(CLUSTER_UID); + assertThat(identity.namespace()).isEqualTo(NAMESPACE); + assertThat(identity.namespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(identity.configMapUid()).isEqualTo(CONFIG_MAP_UID); + assertThat(identity.bindingRevision()).isEqualTo("api-r1"); + assertThat(identity.apiServerOrigin()).isEqualTo("https://kubernetes.test:6443"); + assertThat(identity.servingCaSha256()).isEqualTo(API_CA_DIGEST); + assertThat(snapshot.sourceIdentity()).isEqualTo(identity); + assertThat(snapshot.jwksBytes()).containsExactly(JWKS_1.getBytes(StandardCharsets.UTF_8)); + verify(fixture.desiredStateRepository, never()) + .readCurrentCommittedSigner(any(), any(), any(), any()); + verify(fixture.configMapClient, never()).publish(any(), anyMap()); + } + + @Test + void allowsAbsentKeyOperationsOnlyForTrustedPublishedKeysAndRejectsOtherShapes() { + String jwkWithoutKeyOps = JWK_1.replace("\"key_ops\":[\"verify\"],", ""); + Fixture absentKeyOps = new Fixture("{\"keys\":[" + jwkWithoutKeyOps + "]}"); + + SourceIdentity identity = absentKeyOps.source.sourceIdentity(); + assertThat(absentKeyOps.source.load().jwksBytes()) + .containsExactly( + absentKeyOps + .snapshot + .data() + .get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY) + .getBytes(StandardCharsets.UTF_8)); + assertThat(identity.configMapUid()).isEqualTo(CONFIG_MAP_UID); + + 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\",", ""), + JWK_1.replace("[\"verify\"]", "[\"verify\",\"sign\"]"))) { + Fixture malformed = new Fixture("{\"keys\":[" + malformedJwk + "]}"); + assertThatThrownBy(malformed.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + } + + @Test + void allowsNewAccountPublicationAtSamePinnedResourceWithoutChangingSourceIdentity() { + Fixture fixture = new Fixture(); + fixture.useCommittedState(); + SourceIdentity identity = fixture.source.sourceIdentity(); + String nextJwks = JWKS_1_AND_2; + String nextMarker = + fixture.marker( + NEXT_OPERATION_ID, + "2", + "key_2", + fingerprint(JWK_2), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence nextPublication = + fixture.publication( + nextJwks, + nextMarker, + "42", + "43", + "2", + "key_2", + Optional.of(new ActiveSigner("1", "key_1"))); + Map nextData = + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + nextJwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(nextPublication), Optional.of(nextPublication)); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", nextData)); + + PublicJwksSnapshot snapshot = fixture.source.load(); + + assertThat(snapshot.sourceIdentity()).isEqualTo(identity); + assertThat(snapshot.jwksBytes()).containsExactly(nextJwks.getBytes(StandardCharsets.UTF_8)); + assertThat(new String(snapshot.jwksBytes(), StandardCharsets.UTF_8)).contains(JWK_1, JWK_2); + } + + @Test + void requiresReceiptWhenCurrentPublicationExistsAlongsideCommittedSigner() { + Fixture fixture = new Fixture(); + fixture.useCommittedState(); + fixture.removeCurrentPublicationReceipt(); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void historicalKeyFingerprintRequiresTheCurrentOwnerProvedSetToRetainItsExactIdentity() { + Fixture missingKey = new Fixture(); + missingKey.useCommittedState(); + missingKey.replaceNextJwks("{\"keys\":[" + JWK_2 + "]}"); + assertThatThrownBy(missingKey.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + + Fixture substitutedKey = new Fixture(); + substitutedKey.useCommittedState(); + String substitutedJwk = JWK_1.replace("\"n\":\"AQID\"", "\"n\":\"BAUG\""); + substitutedKey.replaceNextJwks("{\"keys\":[" + substitutedJwk + "," + JWK_2 + "]}"); + assertThatThrownBy(substitutedKey.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void deniesSameNamedDestinationWithDifferentClusterIncarnation() { + Fixture fixture = new Fixture(); + Binding wrongIncarnation = binding("44444444-4444-4444-8444-444444444444", NAMESPACE_UID); + when(fixture.materializerTrust.current()).thenReturn(Optional.of(wrongIncarnation)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void deniesUnexpectedAuthenticatedApiPrincipal() { + Fixture fixture = new Fixture(); + BindingIdentity wrongPrincipal = + new BindingIdentity( + fixture.apiIdentity.bindingDigest(), + fixture.apiIdentity.configRevision(), + fixture.apiIdentity.environmentId(), + fixture.apiIdentity.clusterId(), + fixture.apiIdentity.namespace(), + fixture.apiIdentity.expectedClusterIncarnationUid(), + fixture.apiIdentity.expectedNamespaceUid(), + fixture.apiIdentity.apiServerUrl(), + fixture.apiIdentity.tlsServerName(), + fixture.apiIdentity.servingCaSha256(), + "system:serviceaccount:" + NAMESPACE + ":another-service"); + when(fixture.configMapClient.identity()).thenReturn(wrongPrincipal); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.publicationRepository, never()).readCurrentPublication(any(), any()); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void rejectsRecreatedSameNameConfigMapEvenWithMatchingPublicData() { + Fixture fixture = new Fixture(); + when(fixture.configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + "44444444-4444-4444-8444-444444444444", "42", fixture.snapshot.data())); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void treatsUnreceiptedOrAmbiguousOwnerPublicationAsUnavailableNotAsAKeySet() { + Fixture fixture = new Fixture(); + PublicationEvidence unreceipted = + new PublicationEvidence(fixture.publication.intent(), Optional.empty(), Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(unreceipted)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void doesNotTrustUnexpectedOwnerFailureByMatchingItsMessageText() { + Fixture fixture = new Fixture(); + IllegalStateException unrelated = + new IllegalStateException( + "unrelated adapter failure mentioning Account trusted public JWKS source was rejected"); + when(fixture.desiredStateRepository.readEnrollmentState(fixture.binding.accountBinding())) + .thenThrow(unrelated); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .isNotSameAs(unrelated) + .hasMessage("Account trusted public JWKS source was rejected") + .hasNoCause(); + } + + @Test + void rejectsTrustChangeAcrossTheAuthenticatedRead() { + Fixture fixture = new Fixture(); + Binding changedBinding = binding(CLUSTER_UID, NAMESPACE_UID, "materializer-r2"); + when(fixture.materializerTrust.current()) + .thenReturn(Optional.of(fixture.binding), Optional.of(changedBinding)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void rejectsReadbackThatDoesNotMatchReceiptResourceVersionOrMarker() { + Fixture fixture = new Fixture(); + Map changedData = + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + "{\"phase\":\"OTHER\"}"); + when(fixture.configMapClient.observe()) + .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", changedData)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } + + @Test + void ownerPublicationChangingDuringReadProducesNoSnapshot() { + Fixture fixture = new Fixture(); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(fixture.publication), Optional.empty()); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(SourceUnavailableException.class) + .hasNoCause(); + } + + @Test + void deniesInitialPrepublicationWhenPublicMarkerClaimsAnActiveFence() { + Fixture fixture = new Fixture(); + String activeMarker = + fixture.marker( + INITIAL_OPERATION_ID, + "1", + "key_1", + fingerprint(JWK_1), + Optional.of(new ActiveSigner("1", "key_1"))); + PublicationEvidence conflicting = + fixture.publication(JWKS_1, activeMarker, "41", "42", "1", "key_1", Optional.empty()); + when(fixture.publicationRepository.readCurrentPublication( + eq(fixture.binding.accountBinding()), eq(fixture.trustFence))) + .thenReturn(Optional.of(conflicting)); + + assertThatThrownBy(fixture.source::sourceIdentity) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + verify(fixture.configMapClient, never()).observe(); + } + + @Test + void deniesInitialPrepublicationWhenConfigMapResourceVersionIsStale() { + 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"); + } + + private static Binding binding(String clusterUid, String namespaceUid) { + return binding(clusterUid, namespaceUid, "materializer-r1"); + } + + private static Binding binding(String clusterUid, String namespaceUid, String revision) { + String expectedPeer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/jwt-signer-materializer"; + List pins = List.of("c".repeat(64)); + String bindingDigest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + revision, + ENVIRONMENT, + CLUSTER, + NAMESPACE, + clusterUid, + namespaceUid, + expectedPeer, + pins); + return new Binding( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + clusterUid, + namespaceUid, + expectedPeer, + pins, + revision, + bindingDigest); + } + + private static String sha256(String value) { + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (Exception unavailable) { + throw new AssertionError(unavailable); + } + } + + private static final class Fixture { + private final AccountJwtJwksConfigMapClient configMapClient = + mock(AccountJwtJwksConfigMapClient.class); + private final AccountJwtSignerMaterializerTrustBinding materializerTrust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + private final AccountJwtSignerDesiredStateRepository desiredStateRepository = + mock(AccountJwtSignerDesiredStateRepository.class); + private final AccountJwtJwksPublicationRepository publicationRepository = + mock(AccountJwtJwksPublicationRepository.class); + private final PlatformTransactionManager transactionManager = + mock(PlatformTransactionManager.class); + private final Binding binding = binding(CLUSTER_UID, NAMESPACE_UID); + private final TrustFence trustFence = + new TrustFence( + CLUSTER_UID, NAMESPACE_UID, binding.bindingDigest(), binding.configRevision()); + private final AccountJwtSignerDesiredStateRepository.Binding accountBinding = + binding.accountBinding(); + private final BindingIdentity apiIdentity = + new BindingIdentity( + API_BINDING_DIGEST, + "api-r1", + ENVIRONMENT, + CLUSTER, + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.test:6443", + "kubernetes.test", + API_CA_DIGEST, + "system:serviceaccount:" + NAMESPACE + ":account-service"); + private final String publicFingerprint = fingerprint(JWK_1); + private final EnrollmentIdentity enrollmentIdentity; + private final GenerationRequest initialRequest; + private final GenerationResult initialResult; + private final DesiredState initialDesiredState; + private final String initialMarker; + private final PublicationEvidence publication; + private PublicationEvidence nextPublication; + private final ConfigMapSnapshot snapshot; + private final AccountJwtJwksTrustedSource source; + + private Fixture() { + this(JWKS_1); + } + + private Fixture(String jwks) { + enrollmentIdentity = + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + binding.bindingDigest(), + binding.configRevision(), + API_BINDING_DIGEST, + "api-r1", + CONFIG_MAP_UID, + "40", + "6".repeat(64)); + initialMarker = + marker(INITIAL_OPERATION_ID, "1", "key_1", publicFingerprint, Optional.empty()); + initialRequest = mock(GenerationRequest.class); + when(initialRequest.phase()).thenReturn(GenerationPhase.GENERATION_RECORDED); + when(initialRequest.operationId()).thenReturn(INITIAL_OPERATION_ID); + when(initialRequest.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(initialRequest.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(initialRequest.generationReceiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + when(initialRequest.desiredStateVersion()).thenReturn(2L); + when(initialRequest.binding()).thenReturn(accountBinding); + when(initialRequest.trustFence()).thenReturn(trustFence); + when(initialRequest.targetGeneration()).thenReturn("1"); + when(initialRequest.targetKid()).thenReturn("key_1"); + when(initialRequest.publicKeyFingerprint()).thenReturn(publicFingerprint); + when(initialRequest.publicJwkJson()).thenReturn(JWK_1); + when(initialRequest.expectedActive()).thenReturn(Optional.empty()); + when(initialRequest.expectedPublishedActive()).thenReturn(Optional.empty()); + + initialResult = mock(GenerationResult.class); + when(initialResult.operationId()).thenReturn(INITIAL_OPERATION_ID); + when(initialResult.binding()).thenReturn(accountBinding); + when(initialResult.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(initialResult.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(initialResult.desiredStateVersion()).thenReturn(2L); + when(initialResult.trustFence()).thenReturn(trustFence); + when(initialResult.targetGeneration()).thenReturn("1"); + when(initialResult.targetKid()).thenReturn("key_1"); + when(initialResult.targetAlgorithm()).thenReturn("RS256"); + when(initialResult.publicKeyFingerprint()).thenReturn(publicFingerprint); + when(initialResult.publicJwkJson()).thenReturn(JWK_1); + when(initialResult.receiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + + initialDesiredState = + new DesiredState( + accountBinding, + 2, + Optional.empty(), + Optional.empty(), + Optional.of(INITIAL_OPERATION_ID), + Optional.empty(), + Optional.of(enrollmentIdentity)); + publication = publication(jwks, initialMarker, "41", "42", "1", "key_1", Optional.empty()); + snapshot = + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "42", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + jwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + initialMarker, + "operator.note", + "retained")); + + when(transactionManager.getTransaction(any())).thenReturn(new SimpleTransactionStatus()); + when(materializerTrust.current()).thenReturn(Optional.of(binding)); + when(configMapClient.identity()).thenReturn(apiIdentity); + when(configMapClient.observe()).thenReturn(snapshot); + when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) + .thenReturn(Optional.of(initialDesiredState)); + when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) + .thenReturn(initialRequest); + when(desiredStateRepository.readCurrentGenerationResult(eq(accountBinding), eq(trustFence))) + .thenReturn(initialResult); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(publication)); + source = + new AccountJwtJwksTrustedSource( + configMapClient, + materializerTrust, + desiredStateRepository, + publicationRepository, + transactionManager); + } + + private void useCommittedState() { + ActiveSigner active = new ActiveSigner("1", "key_1"); + DesiredState committedState = + new DesiredState( + accountBinding, + 3, + Optional.of(active), + Optional.of(active), + Optional.of(NEXT_OPERATION_ID), + Optional.empty(), + Optional.of(enrollmentIdentity)); + CommittedSignerEvidence committed = mock(CommittedSignerEvidence.class); + PromotionOperationEvidence promotion = mock(PromotionOperationEvidence.class); + AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt receipt = + mock(AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt.class); + String activeMarker = activeMarker(active); + String activeDigest = + AccountJwtJwksPublicationRepository.publicDataDigest(JWKS_1, activeMarker); + when(committed.promotion()).thenReturn(promotion); + when(committed.desiredState()).thenReturn(committedState); + when(committed.publicReceipt()).thenReturn(receipt); + when(promotion.targetGeneration()).thenReturn("1"); + when(promotion.targetKid()).thenReturn("key_1"); + when(promotion.targetPublicKeyFingerprint()).thenReturn(publicFingerprint); + 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.activeJwksPublicDataDigest()).thenReturn(Optional.of(activeDigest)); + when(receipt.configMapUid()).thenReturn(CONFIG_MAP_UID); + when(receipt.observedResourceVersion()).thenReturn("42"); + when(receipt.publicDataDigest()).thenReturn(activeDigest); + when(desiredStateRepository.readEnrollmentState(eq(accountBinding))) + .thenReturn(Optional.of(committedState)); + when(desiredStateRepository.readCurrentCommittedSigner( + eq(accountBinding), eq(trustFence), eq(API_BINDING_DIGEST), eq("api-r1"))) + .thenReturn(Optional.of(committed)); + + GenerationRequest nextRequest = mock(GenerationRequest.class); + when(nextRequest.phase()).thenReturn(GenerationPhase.GENERATION_RECORDED); + when(nextRequest.operationId()).thenReturn(NEXT_OPERATION_ID); + when(nextRequest.operationDigest()).thenReturn(GENERATION_OPERATION_DIGEST); + when(nextRequest.generationRequestDigest()).thenReturn(GENERATION_REQUEST_DIGEST); + when(nextRequest.generationReceiptDigest()).thenReturn(GENERATION_RECEIPT_DIGEST); + when(nextRequest.desiredStateVersion()).thenReturn(2L); + when(nextRequest.targetGeneration()).thenReturn("2"); + when(nextRequest.targetKid()).thenReturn("key_2"); + when(nextRequest.publicKeyFingerprint()).thenReturn(fingerprint(JWK_2)); + when(nextRequest.expectedActive()).thenReturn(Optional.of(active)); + when(nextRequest.expectedPublishedActive()).thenReturn(Optional.of(active)); + when(desiredStateRepository.readCurrentGenerationRequest(eq(accountBinding), eq(trustFence))) + .thenReturn(nextRequest); + + 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)); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(nextPublication)); + when(configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + JWKS_1_AND_2, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"))); + } + + private void removeCurrentPublicationReceipt() { + PublicationEvidence unreceipted = + new PublicationEvidence(nextPublication.intent(), Optional.empty(), Optional.empty()); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(unreceipted)); + } + + private void replaceNextJwks(String jwks) { + String nextMarker = + marker( + NEXT_OPERATION_ID, + "2", + "key_2", + fingerprint(JWK_2), + Optional.of(new ActiveSigner("1", "key_1"))); + nextPublication = + publication( + jwks, + nextMarker, + "42", + "43", + "2", + "key_2", + Optional.of(new ActiveSigner("1", "key_1"))); + when(publicationRepository.readCurrentPublication(eq(accountBinding), eq(trustFence))) + .thenReturn(Optional.of(nextPublication)); + when(configMapClient.observe()) + .thenReturn( + new ConfigMapSnapshot( + CONFIG_MAP_UID, + "43", + Map.of( + AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, + jwks, + AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY, + nextMarker, + "operator.note", + "preserved"))); + } + + private PublicationEvidence publication( + String jwks, + String marker, + String expectedResourceVersion, + String observedResourceVersion, + String generation, + String kid, + Optional expectedActive) { + String publicDataDigest = AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker); + String keyFingerprint = "key_1".equals(kid) ? fingerprint(JWK_1) : fingerprint(JWK_2); + UUID operationId = "1".equals(generation) ? INITIAL_OPERATION_ID : NEXT_OPERATION_ID; + PrepublicationIntent intent = + PrepublicationIntent.create( + operationId, + accountBinding, + GENERATION_OPERATION_DIGEST, + GENERATION_REQUEST_DIGEST, + GENERATION_RECEIPT_DIGEST, + 2L, + trustFence, + API_BINDING_DIGEST, + "api-r1", + AccountJwtJwksPublicationRepository.PUBLIC_JWKS_NAME, + CONFIG_MAP_UID, + expectedResourceVersion, + "4".repeat(64), + generation, + kid, + keyFingerprint, + expectedActive, + expectedActive, + jwks, + marker, + publicDataDigest, + sha256(marker)); + PublicationReceipt receipt = PublicationReceipt.create(intent, observedResourceVersion); + return new PublicationEvidence(intent, Optional.of(receipt), Optional.empty()); + } + + private String marker( + UUID operationId, + String generation, + String kid, + String keyFingerprint, + Optional active) { + String activeJson = activeMarker(active); + return "{\"schemaVersion\":1,\"phase\":\"PREPUBLISHED\",\"operationId\":\"" + + operationId + + "\",\"operationDigest\":\"" + + GENERATION_OPERATION_DIGEST + + "\",\"generationRequestDigest\":\"" + + GENERATION_REQUEST_DIGEST + + "\",\"generationReceiptDigest\":\"" + + GENERATION_RECEIPT_DIGEST + + "\",\"binding\":{\"environmentId\":\"" + + ENVIRONMENT + + "\",\"clusterId\":\"" + + CLUSTER + + "\",\"namespace\":\"" + + NAMESPACE + + "\",\"expectedClusterIncarnationUid\":\"" + + CLUSTER_UID + + "\",\"expectedNamespaceUid\":\"" + + NAMESPACE_UID + + "\",\"trustBindingDigest\":\"" + + binding.bindingDigest() + + "\",\"trustConfigRevision\":\"" + + binding.configRevision() + + "\",\"apiBindingDigest\":\"" + + API_BINDING_DIGEST + + "\",\"apiConfigRevision\":\"api-r1\"},\"publicConfigMap\":{\"name\":\"jwt-jwks\"},\"expectedDurableActive\":" + + activeJson + + ",\"expectedPublishedActive\":" + + activeJson + + ",\"pending\":{\"generation\":\"" + + generation + + "\",\"kid\":\"" + + kid + + "\",\"algorithm\":\"RS256\",\"publicKeyFingerprint\":\"" + + keyFingerprint + + "\"}}"; + } + } + + private static String activeMarker(ActiveSigner active) { + return "{\"generation\":\"" + + active.generation() + + "\",\"kid\":\"" + + active.kid() + + "\",\"present\":true}"; + } + + private static String activeMarker(Optional active) { + return active.map(AccountJwtJwksTrustedSourceTest::activeMarker).orElse("{\"present\":false}"); + } + + private static String fingerprint(String jwk) { + String modulus = jwk.contains("key_1") ? "AQID" : "BAUG"; + String preimage = "{\"e\":\"AQAB\",\"kty\":\"RSA\",\"n\":\"" + modulus + "\"}"; + try { + return java.util.HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(Rfc8785CanonicalJson.canonicalizeUtf8(preimage))); + } catch (Exception unavailable) { + throw new AssertionError(unavailable); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeServiceTest.java new file mode 100644 index 0000000000..d3452a63f4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeServiceTest.java @@ -0,0 +1,274 @@ +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.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.DeliveryClaim; +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.AccountJwtReadinessProbeRepository.SignerFence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionTemplate; + +class AccountJwtReadinessProbeServiceTest { + private static final Binding BINDING = + new Binding( + "staging", "cluster-a", "firemud", CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + private static final TrustFence TRUST = + new TrustFence( + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222", + "a".repeat(64), + "trust-r1"); + + @Test + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = "Missing fixed paths prove retries never read mounted signing material") + void exactIssuedRetryReadsOnlyStoredEvidenceAndDoesNotRemintOrRedeliver() { + AccountJwtReadinessProbeRepository repository = mock(AccountJwtReadinessProbeRepository.class); + UUID operationId = UUID.randomUUID(); + UUID jti = UUID.randomUUID(); + long issuedAt = 20_300; + ProbeEntry issued = + new ProbeEntry( + operationId, + "b".repeat(64), + "account-service", + "game-session-account-delegation", + "account-service", + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + jti, + "1", + "first-key", + Optional.empty(), + 1, + 3, + issuedAt, + issuedAt + 180, + ProbeState.ISSUED, + Optional.empty(), + Optional.of(issuedAt), + Optional.of("c".repeat(64)), + Optional.empty()); + ReadinessProbePlan plan = + new ReadinessProbePlan( + operationId, + BINDING, + TRUST, + "d".repeat(64), + "e".repeat(64), + "f".repeat(64), + 2, + "1", + "first-key", + "a".repeat(64), + new SignerFence(Optional.empty(), Optional.empty()), + "1".repeat(64), + "2".repeat(64), + "3".repeat(64), + "{}", + "4".repeat(64), + false, + 300, + 20_000, + 20_300, + 20_600, + 1, + "5".repeat(64), + List.of(issued)); + when(repository.readCurrentPlan(BINDING, TRUST, operationId)).thenReturn(plan); + DeliveryClaim claim = deliveryClaim(plan); + when(repository.requireCurrentDeliveryClaim( + org.mockito.ArgumentMatchers.eq(BINDING), + org.mockito.ArgumentMatchers.eq(TRUST), + org.mockito.ArgumentMatchers.eq(plan), + org.mockito.ArgumentMatchers.eq(claim), + org.mockito.ArgumentMatchers.any())) + .thenReturn(claim); + AtomicInteger deliveries = new AtomicInteger(); + AccountJwtReadinessProbeService service = + new AccountJwtReadinessProbeService( + repository, + new TransactionTemplate(new NoopTransactionManager()), + Clock.fixed(Instant.ofEpochSecond(20_400), ZoneOffset.UTC), + Path.of("/missing/private"), + Path.of("pending.key"), + Path.of("/missing/public"), + Path.of("jwks.json")); + + List result = + service.issueCurrentPlan( + BINDING, TRUST, operationId, claim, (metadata, jwt) -> deliveries.incrementAndGet()); + + assertThat(result).containsExactly(issued); + assertThat(result.get(0).compactTokenSha256()).contains("c".repeat(64)); + assertThat(deliveries).hasValue(0); + verify(repository, org.mockito.Mockito.times(2)).readCurrentPlan(BINDING, TRUST, operationId); + verify(repository) + .requireCurrentDeliveryClaim( + BINDING, TRUST, plan, claim, java.time.Instant.ofEpochSecond(20_400)); + verifyNoMoreInteractions(repository); + } + + @Test + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = "Missing fixed paths prove retries never read mounted signing material") + void exactVerifiedRetryPreservesReceiptWithoutRemintOrRedelivery() { + AccountJwtReadinessProbeRepository repository = mock(AccountJwtReadinessProbeRepository.class); + UUID operationId = UUID.randomUUID(); + UUID jti = UUID.randomUUID(); + long issuedAt = 20_300; + String tokenHash = "c".repeat(64); + var receipt = + new AccountJwtReadinessProbeRepository.VerificationReceipt( + 1, + 3, + 4, + 20_400, + "6".repeat(64), + "first-key", + "account-validator-instance-7", + "7".repeat(64), + "readiness-r1", + "spiffe://firemud/ns/firemud/sa/account-jwt-readiness-harness", + "8".repeat(64)); + ProbeEntry verified = + new ProbeEntry( + operationId, + "b".repeat(64), + "account-service", + "game-session-account-delegation", + "account-service", + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + jti, + "1", + "first-key", + Optional.empty(), + 1, + 4, + issuedAt, + issuedAt + 180, + ProbeState.VERIFIED, + Optional.empty(), + Optional.of(issuedAt), + Optional.of(tokenHash), + Optional.of(receipt)); + ReadinessProbePlan plan = + new ReadinessProbePlan( + operationId, + BINDING, + TRUST, + "d".repeat(64), + "e".repeat(64), + "f".repeat(64), + 2, + "1", + "first-key", + "a".repeat(64), + new SignerFence(Optional.empty(), Optional.empty()), + "1".repeat(64), + "2".repeat(64), + "3".repeat(64), + "{}", + "4".repeat(64), + false, + 300, + 20_000, + 20_300, + 20_600, + 1, + "5".repeat(64), + List.of(verified)); + when(repository.readCurrentPlan(BINDING, TRUST, operationId)).thenReturn(plan); + DeliveryClaim claim = deliveryClaim(plan); + when(repository.requireCurrentDeliveryClaim( + org.mockito.ArgumentMatchers.eq(BINDING), + org.mockito.ArgumentMatchers.eq(TRUST), + org.mockito.ArgumentMatchers.eq(plan), + org.mockito.ArgumentMatchers.eq(claim), + org.mockito.ArgumentMatchers.any())) + .thenReturn(claim); + AtomicInteger deliveries = new AtomicInteger(); + AccountJwtReadinessProbeService service = + new AccountJwtReadinessProbeService( + repository, + new TransactionTemplate(new NoopTransactionManager()), + Clock.fixed(Instant.ofEpochSecond(20_400), ZoneOffset.UTC), + Path.of("/missing/private"), + Path.of("pending.key"), + Path.of("/missing/public"), + Path.of("jwks.json")); + + List result = + service.issueCurrentPlan( + BINDING, TRUST, operationId, claim, (metadata, jwt) -> deliveries.incrementAndGet()); + + assertThat(result).containsExactly(verified); + assertThat(result.get(0).verificationReceipt()).contains(receipt); + assertThat(deliveries).hasValue(0); + verify(repository, org.mockito.Mockito.times(2)).readCurrentPlan(BINDING, TRUST, operationId); + verify(repository) + .requireCurrentDeliveryClaim( + BINDING, TRUST, plan, claim, java.time.Instant.ofEpochSecond(20_400)); + verifyNoMoreInteractions(repository); + } + + private static final class NoopTransactionManager implements PlatformTransactionManager { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) {} + + @Override + public void rollback(TransactionStatus status) {} + } + + private static DeliveryClaim deliveryClaim(ReadinessProbePlan plan) { + return new DeliveryClaim( + plan.operationId(), + plan.planDigest(), + TRUST.expectedClusterIncarnationUid(), + TRUST.expectedNamespaceUid(), + TRUST.bindingDigest(), + TRUST.configRevision(), + plan.targetGeneration(), + plan.targetKid(), + plan.expectedFence().durableActive(), + "9".repeat(64), + "readiness-r1", + plan.expiresAtEpochSecond() + 1, + "account-service", + "account-validator-instance-1", + "spiffe://firemud/ns/firemud/sa/account-jwt-readiness-harness", + "8".repeat(64), + plan.notBeforeEpochSecond(), + plan.expiresAtEpochSecond(), + "7".repeat(64)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java new file mode 100644 index 0000000000..4e515e2997 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.KeyUnavailableException; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.Snapshot; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind; +import org.junit.jupiter.api.Test; + +class AccountOperatorAuthorizationFingerprintKeyringTest { + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final Duration RETENTION_WINDOW = Duration.ofMinutes(3); + private static final byte[] REFERENCE = + "opaque-reference".getBytes(java.nio.charset.StandardCharsets.US_ASCII); + private static final Instant REFERENCE_EXPIRY = NOW.plusSeconds(60); + private static final Instant RESPONSE_EXPIRY = REFERENCE_EXPIRY.plusSeconds(30); + + @Test + void reloadsOwnerSnapshotForEachOperationAndUsesOnlyItsActiveKeyForIssue() { + AtomicInteger reads = new AtomicInteger(); + AccountOperatorAuthorizationFingerprintKeyring keyring = + new AccountOperatorAuthorizationFingerprintKeyring( + () -> { + reads.incrementAndGet(); + return snapshot("active", "active-secret", List.of()); + }, + CLOCK, + RETENTION_WINDOW); + String expected = + calculator("active", "active-secret").fingerprint(ReferenceKind.HUMAN_OPERATOR, REFERENCE); + + assertThat(keyring.fingerprintForIssue(ReferenceKind.HUMAN_OPERATOR, REFERENCE)) + .isEqualTo(expected); + assertThat( + keyring.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + REFERENCE, + expected, + REFERENCE_EXPIRY, + RESPONSE_EXPIRY)) + .isTrue(); + assertThat(reads).hasValue(2); + } + + @Test + void retainedOriginalKeyMustCoverTheImmutableExpiryAndExplicitRecoveryWindow() { + Instant retainedUntil = RESPONSE_EXPIRY.plus(RETENTION_WINDOW).plusNanos(1); + AccountOperatorAuthorizationFingerprintKeyring keyring = + keyring( + snapshot( + "new-active", + "active-secret", + List.of(new KeyMaterial("original", key("original-secret"), retainedUntil)))); + String original = + calculator("original", "original-secret") + .fingerprint(ReferenceKind.HUMAN_OPERATOR, REFERENCE); + + assertThat( + keyring.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + REFERENCE, + original, + REFERENCE_EXPIRY, + RESPONSE_EXPIRY)) + .isTrue(); + } + + @Test + void missingWithdrawnExpiredOrInsufficientlyRetainedOriginalKeyFailsClosed() { + String original = + calculator("original", "original-secret") + .fingerprint(ReferenceKind.HUMAN_OPERATOR, REFERENCE); + List unavailableSnapshots = + List.of( + snapshot("new-active", "active-secret", List.of()), + snapshot( + "new-active", + "active-secret", + List.of(new KeyMaterial("original", key("original-secret"), NOW))), + snapshot( + "new-active", + "active-secret", + List.of( + new KeyMaterial( + "original", + key("original-secret"), + RESPONSE_EXPIRY.plus(RETENTION_WINDOW))))); + + for (Snapshot snapshot : unavailableSnapshots) { + AccountOperatorAuthorizationFingerprintKeyring keyring = keyring(snapshot); + assertThatThrownBy( + () -> + keyring.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + REFERENCE, + original, + REFERENCE_EXPIRY, + RESPONSE_EXPIRY)) + .isInstanceOf(KeyUnavailableException.class); + } + } + + @Test + void rejectsMalformedFingerprintBeforeReadingTheOwnerKeySource() { + AtomicInteger reads = new AtomicInteger(); + AccountOperatorAuthorizationFingerprintKeyring keyring = + new AccountOperatorAuthorizationFingerprintKeyring( + () -> { + reads.incrementAndGet(); + return snapshot("active", "active-secret", List.of()); + }, + CLOCK, + RETENTION_WINDOW); + + assertThatThrownBy( + () -> + keyring.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + REFERENCE, + "arfp/v1/invalid/not-a-digest", + REFERENCE_EXPIRY, + RESPONSE_EXPIRY)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(reads).hasValue(0); + } + + @Test + void rejectsAmbiguousKeySnapshotsAndMissingRetentionPolicy() { + assertThatThrownBy( + () -> + new Snapshot( + new KeyMaterial("duplicate", key("active-secret")), + List.of( + new KeyMaterial( + "duplicate", key("retained-secret"), NOW.plusSeconds(600))))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountOperatorAuthorizationFingerprintKeyring( + () -> snapshot("active", "active-secret", List.of()), CLOCK, Duration.ZERO)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static AccountOperatorAuthorizationFingerprintKeyring keyring(Snapshot snapshot) { + return new AccountOperatorAuthorizationFingerprintKeyring( + () -> snapshot, CLOCK, RETENTION_WINDOW); + } + + private static Snapshot snapshot( + String activeId, String activeSecret, List retainedKeys) { + return new Snapshot(new KeyMaterial(activeId, key(activeSecret)), retainedKeys); + } + + private static AccountOperatorAuthorizationReferenceFingerprint calculator( + String keyId, String secret) { + return new AccountOperatorAuthorizationReferenceFingerprint(keyId, key(secret)); + } + + private static SecretKeySpec key(String value) { + return new SecretKeySpec( + value.getBytes(java.nio.charset.StandardCharsets.US_ASCII), "HmacSHA256"); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprintTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprintTest.java new file mode 100644 index 0000000000..7fb008b2d5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprintTest.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind; +import org.junit.jupiter.api.Test; + +class AccountOperatorAuthorizationReferenceFingerprintTest { + private static final byte[] KEY_BYTES = + new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + private static final String KEY_ID = "test-key-1"; + + @Test + void matchesIndependentKnownAnswerVectorsForKindsKeyIdsReferencesAndFraming() { + var calculator = calculator(KEY_ID); + byte[] opaqueReference = ascii("opaque-A"); + + assertThat(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, opaqueReference)) + .isEqualTo( + expected(KEY_ID, "e573642ff16f83612ae0e4b085ef434cd3b5b951606571c8d86ca05266bb849e")); + assertThat(calculator.fingerprint(ReferenceKind.AUTOMATION_OPERATOR, opaqueReference)) + .isEqualTo( + expected(KEY_ID, "916405c9980e49c7b01ffc9338d5ad947d3b06317cb6b9ed750e96eebdcade7c")); + assertThat(calculator("test-key-2").fingerprint(ReferenceKind.HUMAN_OPERATOR, opaqueReference)) + .isEqualTo( + expected( + "test-key-2", "a331e3fc9cdda1afc5999bd309cbf018610f05a4fed83269e48b026c74d3803c")); + assertThat(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, ascii("opaque-B"))) + .isEqualTo( + expected(KEY_ID, "11117a68f5c3217bfcad0bc0f7642168aff2d6113469f51266bc5ff57aa06db3")); + + // A colon in the reference exercises unambiguous segment framing. + assertThat(calculator("a").fingerprint(ReferenceKind.HUMAN_OPERATOR, ascii("b:xx"))) + .isEqualTo( + expected("a", "0c368b96387f546857f1490dd1790ec0dfdb304c0eff6cdee80661b92cd4ba2a")); + } + + @Test + void preservesExactUnicodeUtf8BytesWithoutNormalization() { + var calculator = calculator(KEY_ID); + byte[] composed = "é".getBytes(StandardCharsets.UTF_8); + byte[] decomposed = "e\u0301".getBytes(StandardCharsets.UTF_8); + + assertThat(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, composed)) + .isEqualTo( + expected(KEY_ID, "26f3a3ff950707bd17f7eca8674cb7cec001c171f6532932b6d57890e5b60af9")); + assertThat(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, decomposed)) + .isEqualTo( + expected(KEY_ID, "3c9c69068a8c6b40a1e8af27d4cba657e2ce1a185aadc8d3ae268a2ccae6c75f")); + assertThat(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, composed)) + .isNotEqualTo(calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, decomposed)); + } + + @Test + void fingerprintsOpaqueBytesWithoutDecodingThemAsText() { + byte[] opaqueBytes = new byte[] {0, (byte) 0xff}; + + assertThat(calculator(KEY_ID).fingerprint(ReferenceKind.HUMAN_OPERATOR, opaqueBytes)) + .isEqualTo( + expected(KEY_ID, "45840d9641eecbbf42a666bbe8a93933b92adb4d7c66d525840043f354904bec")); + } + + @Test + void rejectsMissingOrUnsupportedKeyMaterialAndInvalidKeyIds() { + assertThatThrownBy(() -> new AccountOperatorAuthorizationReferenceFingerprint(KEY_ID, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AccountOperatorAuthorizationReferenceFingerprint( + KEY_ID, new SecretKeySpec(KEY_BYTES, "AES"))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator("")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator("bad/key")).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator("k".repeat(65))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsMissingEmptyAndExcessiveReferenceBytes() { + var calculator = calculator(KEY_ID); + + assertThatThrownBy(() -> calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, new byte[4097])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> calculator.fingerprint(null, ascii("opaque-A"))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void doesNotModifyTheCallerReferenceArrayOrExposeKeyMaterialInToString() { + var calculator = calculator(KEY_ID); + byte[] reference = ascii("opaque-A"); + byte[] before = reference.clone(); + + calculator.fingerprint(ReferenceKind.HUMAN_OPERATOR, reference); + + assertThat(reference).containsExactly(before); + assertThat(calculator.toString()).doesNotContain(KEY_ID).doesNotContain("00010203"); + } + + private static AccountOperatorAuthorizationReferenceFingerprint calculator(String keyId) { + return new AccountOperatorAuthorizationReferenceFingerprint( + keyId, new SecretKeySpec(KEY_BYTES.clone(), "HmacSHA256")); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String expected(String keyId, String digest) { + return "arfp/v1/" + keyId + "/" + digest; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java new file mode 100644 index 0000000000..e112b28752 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java @@ -0,0 +1,288 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.SecureRandom; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountResponseEnvelopeCryptographyTest { + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final Instant RECOVERY_EXPIRY = NOW.plusSeconds(600); + private static final String KEYRING_HEADER = "firemud-account-response-envelope-keyring-v1"; + + @TempDir Path temporaryDirectory; + + @Test + void encryptsAndDecryptsExactResponseBytes() throws IOException { + writeManifest(activeManifest("key-one", 1)); + AccountResponseEnvelopeCryptography cryptography = + cryptography(Clock.fixed(NOW, ZoneOffset.UTC)); + byte[] response = "test-only exact response".getBytes(StandardCharsets.UTF_8); + + AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope envelope = + cryptography.encrypt(binding(), response, RECOVERY_EXPIRY); + + assertThat(envelope.bytes()).isNotEqualTo(response); + assertThat(cryptography.decrypt(envelope, binding(), RECOVERY_EXPIRY)).isEqualTo(response); + } + + @Test + void authenticatesMaximumAuthorityBundleAndResponseWithoutChangingRawBindingBytes() + throws IOException { + writeManifest(activeManifest("key-one", 1)); + AccountResponseEnvelopeCryptography cryptography = + cryptography(Clock.fixed(NOW, ZoneOffset.UTC)); + byte[] authorityBundle = + new byte[AccountResponseEnvelopeCryptography.MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES]; + Arrays.fill(authorityBundle, (byte) 0x5a); + var binding = bindingWithAuthorityBundle(authorityBundle); + byte[] response = new byte[AccountResponseEnvelopeCryptography.MAX_RESPONSE_BYTES]; + Arrays.fill(response, (byte) 0x3c); + + var envelope = cryptography.encrypt(binding, response, RECOVERY_EXPIRY); + + assertThat(envelope.bytes().length).isLessThanOrEqualTo(160 * 1024); + assertThat(cryptography.decrypt(envelope, binding, RECOVERY_EXPIRY)).containsExactly(response); + + byte[] changedAuthorityBundle = authorityBundle.clone(); + changedAuthorityBundle[changedAuthorityBundle.length / 2] ^= 0x01; + assertThatThrownBy( + () -> + cryptography.decrypt( + envelope, bindingWithAuthorityBundle(changedAuthorityBundle), RECOVERY_EXPIRY)) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + } + + @Test + void rejectsAuthorityResponseAndCiphertextBoundsPlusOne() throws IOException { + writeManifest(activeManifest("key-one", 1)); + AccountResponseEnvelopeCryptography cryptography = + cryptography(Clock.fixed(NOW, ZoneOffset.UTC)); + var binding = binding(); + + assertThatThrownBy( + () -> + bindingWithAuthorityBundle( + new byte + [AccountResponseEnvelopeCryptography.MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES + + 1])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + cryptography.encrypt( + binding, + new byte[AccountResponseEnvelopeCryptography.MAX_RESPONSE_BYTES + 1], + RECOVERY_EXPIRY)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + cryptography.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + new byte[AccountResponseEnvelopeCryptography.MAX_ENVELOPE_BYTES + 1]), + binding, + RECOVERY_EXPIRY)) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + } + + @Test + void rejectsTamperingEveryChangedBindingFieldAndChangedExpiry() throws IOException { + writeManifest(activeManifest("key-one", 1)); + AccountResponseEnvelopeCryptography cryptography = + cryptography(Clock.fixed(NOW, ZoneOffset.UTC)); + var binding = binding(); + var envelope = + cryptography.encrypt( + binding, "test-only exact response".getBytes(StandardCharsets.UTF_8), RECOVERY_EXPIRY); + + byte[] tamperedBytes = envelope.bytes(); + tamperedBytes[tamperedBytes.length - 1] ^= 0x01; + var tamperedEnvelope = + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope(tamperedBytes); + assertThatThrownBy(() -> cryptography.decrypt(tamperedEnvelope, binding, RECOVERY_EXPIRY)) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + + for (int field = 0; field < 12; field++) { + var changedBinding = changedBinding(binding, field); + assertThatThrownBy(() -> cryptography.decrypt(envelope, changedBinding, RECOVERY_EXPIRY)) + .as("binding field %s must be authenticated", field) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + } + + assertThatThrownBy(() -> cryptography.decrypt(envelope, binding, RECOVERY_EXPIRY.plusMillis(1))) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + } + + @Test + void onlyDecryptsWithRetainedKeysAndRejectsWithdrawnKeys() throws IOException { + writeManifest(activeManifest("key-one", 1)); + AccountResponseEnvelopeCryptography cryptography = + cryptography(Clock.fixed(NOW, ZoneOffset.UTC)); + var binding = binding(); + var envelope = + cryptography.encrypt( + binding, "test-only exact response".getBytes(StandardCharsets.UTF_8), RECOVERY_EXPIRY); + + long decryptUntil = RECOVERY_EXPIRY.plusSeconds(60).toEpochMilli(); + writeManifest( + KEYRING_HEADER + + "\nactive key-two " + + encodedKey(2) + + "\nretiring key-one " + + decryptUntil + + " " + + encodedKey(1) + + "\n"); + + assertThat(cryptography.decrypt(envelope, binding, RECOVERY_EXPIRY)) + .isEqualTo("test-only exact response".getBytes(StandardCharsets.UTF_8)); + + writeManifest(activeManifest("key-two", 2)); + assertThatThrownBy(() -> cryptography.decrypt(envelope, binding, RECOVERY_EXPIRY)) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } + + @Test + void rejectsDecryptionAtTheImmutableRecoveryExpiry() throws IOException { + writeManifest(activeManifest("key-one", 1)); + var envelope = + cryptography(Clock.fixed(NOW, ZoneOffset.UTC)) + .encrypt( + binding(), + "test-only exact response".getBytes(StandardCharsets.UTF_8), + RECOVERY_EXPIRY); + var expiredCryptography = cryptography(Clock.fixed(RECOVERY_EXPIRY, ZoneOffset.UTC)); + + assertThatThrownBy(() -> expiredCryptography.decrypt(envelope, binding(), RECOVERY_EXPIRY)) + .isInstanceOf(AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException.class) + .satisfies( + failure -> + assertThat( + ((AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException) + failure) + .errorCode()) + .isEqualTo("RESPONSE_RECOVERY_EXPIRED")); + } + + private AccountResponseEnvelopeCryptography cryptography(Clock clock) { + return new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(temporaryDirectory.toString()), + clock, + new SecureRandom()); + } + + private void writeManifest(String contents) throws IOException { + Files.writeString(temporaryDirectory.resolve("keyring"), contents, StandardCharsets.US_ASCII); + } + + private static String activeManifest(String keyId, int keyValue) { + return KEYRING_HEADER + "\nactive " + keyId + " " + encodedKey(keyValue) + "\n"; + } + + private static String encodedKey(int value) { + byte[] key = new byte[AccountResponseEnvelopeKeyring.KEY_BYTES]; + Arrays.fill(key, (byte) value); + return Base64.getUrlEncoder().withoutPadding().encodeToString(key); + } + + private static AccountResponseEnvelopeCryptography.Binding binding() { + return new AccountResponseEnvelopeCryptography.Binding( + "test-envelope", + "request-01", + filledBytes((byte) 1), + "spiffe://firemud/ns/test/sa/logging-admin-service", + "binding-01", + Optional.of("lineage-01"), + Optional.of("replacement-01"), + Optional.of("lease-01"), + 7, + bytes("{\"authority\":\"tuple-01\"}"), + bytes("{\"tenant-01\":\"membership-01\"}"), + bytes("{\"bundleVersion\":\"authorityEvidenceBundle/v1\"}")); + } + + private static AccountResponseEnvelopeCryptography.Binding bindingWithAuthorityBundle( + byte[] authorityEvidenceBundle) { + var source = binding(); + return new AccountResponseEnvelopeCryptography.Binding( + source.operation(), + source.requestId(), + source.requestDigest(), + source.callerWorkload(), + source.bindingId(), + source.lineageId(), + source.replacementId(), + source.leaseId(), + source.issuanceFence(), + source.authorityTupleCanonicalBytes(), + source.membershipVersionMapCanonicalBytes(), + authorityEvidenceBundle); + } + + private static AccountResponseEnvelopeCryptography.Binding changedBinding( + AccountResponseEnvelopeCryptography.Binding source, int field) { + String operation = source.operation(); + String requestId = source.requestId(); + byte[] requestDigest = source.requestDigest(); + String callerWorkload = source.callerWorkload(); + String bindingId = source.bindingId(); + Optional lineageId = source.lineageId(); + Optional replacementId = source.replacementId(); + Optional leaseId = source.leaseId(); + long issuanceFence = source.issuanceFence(); + byte[] authorityTuple = source.authorityTupleCanonicalBytes(); + byte[] membershipVersionMap = source.membershipVersionMapCanonicalBytes(); + byte[] authorityEvidenceBundle = source.authorityEvidenceBundleCanonicalBytes(); + + switch (field) { + case 0 -> operation = "other-operation"; + case 1 -> requestId = "request-02"; + case 2 -> requestDigest = filledBytes((byte) 2); + case 3 -> callerWorkload = "spiffe://firemud/ns/other/sa/logging-admin-service"; + case 4 -> bindingId = "binding-02"; + case 5 -> lineageId = Optional.empty(); + case 6 -> replacementId = Optional.empty(); + case 7 -> leaseId = Optional.empty(); + case 8 -> issuanceFence = 8; + case 9 -> authorityTuple = bytes("{\"authority\":\"tuple-02\"}"); + case 10 -> membershipVersionMap = bytes("{\"tenant-01\":\"membership-02\"}"); + case 11 -> authorityEvidenceBundle = bytes("{\"bundleVersion\":\"changed\"}"); + default -> throw new IllegalArgumentException("Unknown response-envelope binding field"); + } + + return new AccountResponseEnvelopeCryptography.Binding( + operation, + requestId, + requestDigest, + callerWorkload, + bindingId, + lineageId, + replacementId, + leaseId, + issuanceFence, + authorityTuple, + membershipVersionMap, + authorityEvidenceBundle); + } + + private static byte[] filledBytes(byte value) { + byte[] bytes = new byte[32]; + Arrays.fill(bytes, value); + return bytes; + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java new file mode 100644 index 0000000000..2f0b799eaa --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java @@ -0,0 +1,136 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; +import java.time.Instant; +import java.util.Arrays; +import java.util.Base64; +import java.util.Set; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountResponseEnvelopeKeyringTest { + private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); + private static final String KEYRING_HEADER = "firemud-account-response-envelope-keyring-v1"; + + @TempDir Path temporaryDirectory; + + @Test + void reloadsRotationAndAllowsRetiringKeyOnlyUntilItsConfiguredExpiry() throws IOException { + Path mount = Files.createDirectory(temporaryDirectory.resolve("rotation")); + AccountResponseEnvelopeKeyring keyring = new AccountResponseEnvelopeKeyring(mount.toString()); + writeManifest(mount, activeManifest("key-one", 1)); + assertThat(keyring.readCurrent().activeKeyId()).isEqualTo("key-one"); + + Instant decryptUntil = NOW.plusSeconds(60); + writeManifest( + mount, + KEYRING_HEADER + + "\nactive key-two " + + encodedKey(2) + + "\nretiring key-one " + + decryptUntil.toEpochMilli() + + " " + + encodedKey(1) + + "\n"); + + var rotated = keyring.readCurrent(); + assertThat(rotated.activeKeyId()).isEqualTo("key-two"); + assertThat(rotated.decryptionKey("key-one", NOW)).isNotNull(); + assertThatThrownBy(() -> rotated.decryptionKey("key-one", decryptUntil)) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + + writeManifest(mount, activeManifest("key-two", 2)); + assertThatThrownBy(() -> keyring.readCurrent().decryptionKey("key-one", NOW)) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } + + @Test + void acceptsProjectedSecretSymlinksInsideMountAndRejectsTargetsOutsideIt() throws IOException { + Path projectedMount = Files.createDirectory(temporaryDirectory.resolve("projected")); + Path version = Files.createDirectory(projectedMount.resolve("..2026_10_09")); + Files.writeString( + version.resolve("key"), activeManifest("key-one", 1), StandardCharsets.US_ASCII); + Files.createSymbolicLink(projectedMount.resolve("..data"), Path.of("..2026_10_09")); + Files.createSymbolicLink(projectedMount.resolve("keyring"), Path.of("..data/key")); + + assertThat( + new AccountResponseEnvelopeKeyring(projectedMount.toString()) + .readCurrent() + .activeKeyId()) + .isEqualTo("key-one"); + + Path outsideDirectory = Files.createDirectory(temporaryDirectory.resolve("outside")); + Files.writeString( + outsideDirectory.resolve("keyring"), + activeManifest("key-two", 2), + StandardCharsets.US_ASCII); + Path escapingMount = Files.createDirectory(temporaryDirectory.resolve("escaping")); + Files.createSymbolicLink(escapingMount.resolve("keyring"), outsideDirectory.resolve("keyring")); + + assertThatThrownBy( + () -> new AccountResponseEnvelopeKeyring(escapingMount.toString()).readCurrent()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } + + @Test + void failsClosedForMissingAndMalformedMounts() throws IOException { + assertThatThrownBy(() -> new AccountResponseEnvelopeKeyring("").readCurrent()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + assertThatThrownBy( + () -> + new AccountResponseEnvelopeKeyring(temporaryDirectory.resolve("missing").toString()) + .readCurrent()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + + Path malformedMount = Files.createDirectory(temporaryDirectory.resolve("malformed")); + writeManifest(malformedMount, "not-the-keyring-header\nactive key-one " + encodedKey(1) + "\n"); + assertThatThrownBy( + () -> new AccountResponseEnvelopeKeyring(malformedMount.toString()).readCurrent()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } + + @Test + void failsClosedWhenMountedKeyringCannotBeRead() throws IOException { + Assumptions.assumeTrue( + FileSystems.getDefault().supportedFileAttributeViews().contains("posix"), + "Mounted file permission proof requires POSIX file permissions"); + Path mount = Files.createDirectory(temporaryDirectory.resolve("unreadable")); + Path keyringPath = writeManifest(mount, activeManifest("key-one", 1)); + Set originalPermissions = Files.getPosixFilePermissions(keyringPath); + try { + Files.setPosixFilePermissions(keyringPath, Set.of()); + Assumptions.assumeFalse( + Files.isReadable(keyringPath), + "The test process bypasses POSIX read permissions for this file"); + assertThatThrownBy(() -> new AccountResponseEnvelopeKeyring(mount.toString()).readCurrent()) + .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); + } finally { + Files.setPosixFilePermissions(keyringPath, originalPermissions); + } + } + + private static Path writeManifest(Path mount, String contents) throws IOException { + Path keyring = mount.resolve("keyring"); + Files.writeString(keyring, contents, StandardCharsets.US_ASCII); + return keyring; + } + + private static String activeManifest(String keyId, int keyValue) { + return KEYRING_HEADER + "\nactive " + keyId + " " + encodedKey(keyValue) + "\n"; + } + + private static String encodedKey(int value) { + byte[] key = new byte[AccountResponseEnvelopeKeyring.KEY_BYTES]; + Arrays.fill(key, (byte) value); + return Base64.getUrlEncoder().withoutPadding().encodeToString(key); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java new file mode 100644 index 0000000000..fffac6fc00 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java @@ -0,0 +1,360 @@ +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.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.jooq.Record; +import org.junit.jupiter.api.Test; + +class AccountStartSessionOperatorAuthorityBundleTest { + private static final Instant ISSUED_AT = Instant.parse("2026-10-08T11:00:00Z"); + + @Test + void encodesExactHumanTenantArmAndKeepsOwnerLinearizationSeparate() { + Fixture fixture = new Fixture(Map.of()); + var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + fixture.tuple, + fixture.source, + fixture.issuance, + UUID.randomUUID(), + linearization, + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + Map evidence = object(bundle.jsonValue().get("issuanceEvidence")); + var reference = bundle.referenceForSource(fixture.source, linearization); + + assertThat(bundle.jsonValue()) + .containsEntry("bundleVersion", "authorityEvidenceBundle/v1") + .containsEntry("issuanceKind", "human_operator") + .doesNotContainKey("sourceReference"); + assertThat(evidence) + .containsEntry("evidenceType", "HumanAuthorityEvidence/v1") + .containsEntry("actorAccountId", fixture.actorId.toString()) + .containsEntry("controlUiTokenJti", fixture.tokenJti.toString()) + .containsEntry("role", "tenantAdmin") + .doesNotContainKeys("assurance", "globalRoles"); + assertThat(evidence.keySet()) + .containsExactlyInAnyOrder( + "evidenceType", + "actorAccountId", + "controlUiTokenJti", + "role", + "accountGeneration", + "tenantGeneration"); + assertThat(reference.asJsonValue()) + .containsEntry("bundleVersion", "authorityEvidenceBundle/v1") + .containsEntry("sourceVersion", "7") + .containsEntry("sourceFence", "99") + .containsEntry("linearization", "123456"); + + var decoded = AccountStartSessionOperatorAuthorityBundle.decode(bundle.canonicalBytes()); + decoded.requireTupleBinding(fixture.tuple); + decoded.requireCurrent( + fixture.source, fixture.issuance, fixture.tuple, reference, ISSUED_AT.plusSeconds(1)); + } + + @Test + void rejectsAssuranceAdditionGlobalRoleSubstitutionAndTupleSubstitution() { + Fixture assurance = new Fixture(Map.of("assurance", Map.of("level", "step-up"))); + assertThatThrownBy(() -> assurance.create()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAdmin"); + + Fixture globalRole = new Fixture(Map.of("globalRoles", List.of("platformAdmin"))); + assertThatThrownBy(() -> globalRole.create()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAdmin"); + + Fixture valid = new Fixture(Map.of()); + var bundle = valid.create(); + var substituted = tuple(UUID.randomUUID(), valid.tenantId, "different-request"); + assertThatThrownBy(() -> bundle.requireTupleBinding(substituted)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact StartSession tuple"); + } + + @Test + void strictDecoderRejectsTenantAssuranceAndGlobalBranchEvidence() { + Fixture fixture = new Fixture(Map.of()); + var valid = fixture.create(); + Map withAssurance = new LinkedHashMap<>(valid.jsonValue()); + Map assuranceArm = + new LinkedHashMap<>(object(withAssurance.get("issuanceEvidence"))); + assuranceArm.put("assurance", Map.of("level", "step-up")); + withAssurance.put("issuanceEvidence", assuranceArm); + assertThatThrownBy( + () -> + AccountStartSessionOperatorAuthorityBundle.decode( + AccountControlUiAuthority.canonical(withAssurance))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing or unsupported fields"); + + Map globalArm = new LinkedHashMap<>(valid.jsonValue()); + Map substituted = + new LinkedHashMap<>(object(globalArm.get("issuanceEvidence"))); + substituted.put("role", "platformAdmin"); + globalArm.put("issuanceEvidence", substituted); + assertThatThrownBy( + () -> + AccountStartSessionOperatorAuthorityBundle.decode( + AccountControlUiAuthority.canonical(globalArm))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAdmin"); + } + + @Test + void currentSourceMustRetainExactActorGenerationAndSelectedTenant() { + Fixture fixture = new Fixture(Map.of()); + var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + fixture.tuple, + fixture.source, + fixture.issuance, + UUID.randomUUID(), + linearization, + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + var substitutedSource = + fixture.source(fixture.actorId, fixture.tenantId, 8L, new byte[] {8}, 2L); + + assertThatThrownBy( + () -> + bundle.requireCurrent( + substitutedSource, + fixture.issuance, + fixture.tuple, + bundle.referenceForSource(fixture.source, linearization), + ISSUED_AT.plusSeconds(1))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void expiredOrChangedCurrentAuthorityIsPreconditionFailureButMalformedBundleIsInvalid() { + Fixture fixture = new Fixture(Map.of()); + var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + fixture.tuple, + fixture.source, + fixture.issuance, + UUID.randomUUID(), + linearization, + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + var reference = bundle.referenceForSource(fixture.source, linearization); + + assertThatThrownBy( + () -> + bundle.requireCurrent( + fixture.source, + fixture.issuance, + fixture.tuple, + reference, + ISSUED_AT.plusSeconds(60))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("expired"); + + var changedTenantAuthority = + fixture.source(fixture.actorId, fixture.tenantId, 8L, new byte[] {8}, 2L); + assertThatThrownBy( + () -> + bundle.requireCurrent( + changedTenantAuthority, + fixture.issuance, + fixture.tuple, + reference, + ISSUED_AT.plusSeconds(1))) + .isInstanceOf(IllegalStateException.class); + + assertThatThrownBy(() -> AccountStartSessionOperatorAuthorityBundle.decode(new byte[] {0x01})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void sameAttemptReplayAfterEnvelopeHorizonRetainsOriginalSourceLinearization() { + Fixture fixture = new Fixture(Map.of()); + var linearization = new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + fixture.tuple, + fixture.source, + fixture.issuance, + UUID.randomUUID(), + linearization, + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + var originalReference = bundle.referenceForSource(fixture.source, linearization); + + bundle.requireCurrentSnapshotForExactReplay( + fixture.source, fixture.issuance, fixture.tuple, originalReference); + + var substitutedTransaction = + new AccountStartSessionOperatorAuthorityBundle.BundleReference( + originalReference.bundleVersion(), + originalReference.sourceVersion(), + originalReference.sourceFence(), + "123457"); + assertThatThrownBy( + () -> + bundle.requireCurrentSnapshotForExactReplay( + fixture.source, fixture.issuance, fixture.tuple, substitutedTransaction)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source differs"); + + var changedSource = fixture.source(fixture.actorId, fixture.tenantId, 8L, new byte[] {8}, 2L); + assertThatThrownBy( + () -> + bundle.requireCurrentSnapshotForExactReplay( + changedSource, fixture.issuance, fixture.tuple, originalReference)) + .isInstanceOf(IllegalStateException.class); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + UUID actorId, UUID tenantId, String requestId) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, "test"), + new StartSessionOperatorAction.Target(1L, actorId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "authority bundle test"); + return StartSessionPreAuthorizationReservationTuple.createHuman(requestId, actorId, action); + } + + private static Map object(Object value) { + @SuppressWarnings("unchecked") + Map result = (Map) value; + return result; + } + + private static final class Fixture { + final UUID actorId = UUID.randomUUID(); + final UUID tenantId = UUID.randomUUID(); + final UUID tokenJti = UUID.randomUUID(); + final StartSessionPreAuthorizationReservationTuple tuple = + tuple(actorId, tenantId, "request-" + UUID.randomUUID()); + final AccountControlUiAuthority.Snapshot source; + final AccountControlUiIssuanceRepository.Stored issuance; + + Fixture(Map additionalClaims) { + source = source(actorId, tenantId, 7L, new byte[] {7}, 1L); + issuance = stored(actorId, tenantId, tokenJti, source, additionalClaims); + } + + AccountStartSessionOperatorAuthorityBundle create() { + return AccountStartSessionOperatorAuthorityBundle.create( + tuple, + source, + issuance, + UUID.randomUUID(), + new AccountControlUiIssuanceRepository.OwnerLinearization("123456", 99L), + ISSUED_AT, + ISSUED_AT.plusSeconds(60)); + } + + AccountControlUiAuthority.Snapshot source( + UUID actor, UUID tenant, long sourceVersion, byte[] evidence, long accountGeneration) { + var snapshot = mock(AccountControlUiAuthority.Snapshot.class); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + accountGeneration, + "tenantAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "membershipAuthorityGeneration", + Map.of(tenant.toString(), 1L), + "privateRealmGrantVersions", + List.of()); + when(snapshot.actor()).thenReturn(actor); + when(snapshot.tenant()).thenReturn(tenant); + when(snapshot.authorityTuple()).thenReturn(authorityTuple); + when(snapshot.membershipVersion()).thenReturn(Map.of(tenant.toString(), 2L)); + when(snapshot.evidence()).thenReturn(evidence.clone()); + when(snapshot.sources()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + Long.toString(accountGeneration), + Long.toString(sourceVersion), + null, + null, + evidence))); + return snapshot; + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static AccountControlUiIssuanceRepository.Stored stored( + UUID actorId, + UUID tenantId, + UUID tokenJti, + AccountControlUiAuthority.Snapshot source, + Map additionalClaims) { + Map claims = new LinkedHashMap<>(); + claims.put("jti", tokenJti.toString()); + claims.put("sub", actorId.toString()); + claims.put("accountId", actorId.toString()); + claims.put("aud", "control-ui"); + claims.put("tokenGeneration", 1L); + claims.put("authorityTuple", source.authorityTuple()); + claims.put("membershipVersion", source.membershipVersion()); + claims.put("scopedRoles", Map.of(tenantId.toString(), List.of("tenantAdmin"))); + claims.putAll(additionalClaims); + + Map rowValues = + Map.ofEntries( + Map.entry("request_id", UUID.randomUUID()), + Map.entry("operation_id", UUID.randomUUID()), + Map.entry("token_jti", tokenJti), + Map.entry("account_uuid", actorId), + Map.entry("tenant_uuid", tenantId), + Map.entry("caller_context_id", UUID.randomUUID()), + Map.entry("caller_workload", "spiffe://firemud/ns/test/sa/account-service"), + Map.entry("request_mac_key_id", "test-key"), + Map.entry("request_digest", "b".repeat(64)), + Map.entry("status", "COMMITTED"), + Map.entry("token_hash", "c".repeat(64)), + Map.entry("claims_payload", AccountControlUiAuthority.canonical(claims)), + Map.entry("source_payload", source.evidence()), + Map.entry("bundle_payload", AccountControlUiAuthority.canonical(Map.of("version", 1))), + Map.entry("signer_receipt", AccountControlUiAuthority.canonical(Map.of("version", 1))), + Map.entry("pending_registry", new byte[] {1}), + Map.entry("active_registry", new byte[] {2}), + Map.entry("issued_at_epoch_second", ISSUED_AT.minusSeconds(1).getEpochSecond()), + Map.entry("expires_at_epoch_second", ISSUED_AT.plusSeconds(300).getEpochSecond()), + Map.entry( + "recovery_expires_at", + OffsetDateTime.ofInstant(ISSUED_AT.plusSeconds(300), ZoneOffset.UTC))); + Record row = mock(Record.class); + doAnswer(invocation -> rowValues.get(invocation.getArgument(0))) + .when(row) + .get(anyString(), any(Class.class)); + return new AccountControlUiIssuanceRepository.Stored(row); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java new file mode 100644 index 0000000000..8e2c441e20 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java @@ -0,0 +1,1332 @@ +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.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import javax.crypto.spec.SecretKeySpec; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.IssuanceRecord; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionRequest; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.Status; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService.Current; +import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.OwnerLinearization; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest; +import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.SimpleTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Focused flow proof; JWT validation/source locking remain owned by the real actor service. */ +class AccountStartSessionOperatorAuthorizationServiceTest { + private static final Instant NOW = Instant.parse("2026-10-08T11:00:00Z"); + private static final String RESPONSE_KEYRING_HEADER = + "firemud-account-response-envelope-keyring-v1"; + private static final String LOGGING_PEER = "spiffe://firemud/ns/test/sa/logging-admin-service"; + private static final String GAME_SESSION_PEER = + "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String GAME_DESIGN_PEER = "spiffe://firemud/ns/test/sa/game-design-service"; + + @TempDir Path temporaryDirectory; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { + UUID actorId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID requestOwnerId = UUID.randomUUID(); + UUID issuerOperationId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + StartSessionPreAuthorizationReservationTuple tuple = tuple(actorId, tenantId); + AccountControlUiAuthority.Snapshot originalSource = + source(actorId, tenantId, 7L, new byte[] {1}); + AccountControlUiAuthority.Snapshot changedSource = + source(actorId, tenantId, 8L, new byte[] {2}); + AccountControlUiIssuanceRepository.Stored stored = + stored(actorId, tenantId, tokenJti, issuerOperationId, originalSource); + Current original = new Current(stored, originalSource); + Current changed = new Current(stored, changedSource); + + var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); + var issuanceOperations = org.mockito.Mockito.mock(AccountControlUiIssuanceRepository.class); + var claims = org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); + var repository = + org.mockito.Mockito.mock(AccountStartSessionOperatorAuthorizationRepository.class); + var fingerprintKeys = + org.mockito.Mockito.mock(AccountOperatorAuthorizationFingerprintKeyring.class); + var responseCrypto = org.mockito.Mockito.mock(AccountResponseEnvelopeCryptography.class); + var hostedTerms = org.mockito.Mockito.mock(AccountHostedTermsService.class); + var transactions = org.mockito.Mockito.mock(PlatformTransactionManager.class); + var environment = + org.mockito.Mockito.mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenReturn(new SimpleTransactionStatus()); + when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); + when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) + .thenReturn(Optional.empty()); + doAnswer( + ignored -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + return new OwnerLinearization("123456", 99L); + }) + .when(issuanceOperations) + .captureOwnerLinearization(); + when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) + .thenAnswer( + ignored -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return claimEvidence(tuple, requestOwnerId); + }); + doAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return "arfp/v1/test-key/" + "a".repeat(64); + }) + .when(fingerprintKeys) + .fingerprintForIssue(any(), any()); + when(responseCrypto.encrypt(any(), any(), any())) + .thenAnswer( + invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + new byte[] {3, 4, 5}); + }); + + AtomicInteger ownerPass = new AtomicInteger(); + doAnswer( + invocation -> { + int pass = ownerPass.getAndIncrement(); + Current current = pass == 0 ? original : changed; + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(3); + return action.apply(current); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(actors) + .withCurrent(anyString(), any(), any(), any()); + + var service = + new AccountStartSessionOperatorAuthorizationService( + actors, + issuanceOperations, + claims, + repository, + fingerprintKeys, + responseCrypto, + hostedTerms, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC), + new java.security.SecureRandom(), + LOGGING_PEER, + GAME_SESSION_PEER, + java.time.Duration.ofSeconds(60), + java.time.Duration.ofSeconds(20)); + var request = + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + "test-only-forwarded-control-ui-credential", + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + requestOwnerId, + 10L, + requestOwnerId, + 10L); + + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(LOGGING_PEER).orElseThrow()) + .run( + () -> + assertThatThrownBy(() -> service.issue(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source changed")); + + verify(repository, never()).createOrReadExact(any()); + } + + @Test + void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exception { + String requestId = "é".repeat(64); + byte[] requestIdBytes = requestId.getBytes(StandardCharsets.UTF_8); + assertThat(requestIdBytes).hasSize(128); + + UUID actorId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID requestOwnerId = UUID.randomUUID(); + UUID issuerOperationId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + StartSessionPreAuthorizationReservationTuple tuple = tuple(requestId, actorId, tenantId); + byte[] exactTuple = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + AccountControlUiAuthority.Snapshot source = source(actorId, tenantId, 7L, new byte[] {1}); + AccountControlUiIssuanceRepository.Stored stored = + stored(actorId, tenantId, tokenJti, issuerOperationId, source); + Current current = new Current(stored, source); + + var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); + var issuanceOperations = org.mockito.Mockito.mock(AccountControlUiIssuanceRepository.class); + var claims = org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); + var repository = + org.mockito.Mockito.mock(AccountStartSessionOperatorAuthorizationRepository.class); + MutableClock operationClock = new MutableClock(NOW); + byte[] fingerprintKey = new byte[32]; + java.util.Arrays.fill(fingerprintKey, (byte) 11); + var fingerprintKeys = + new AccountOperatorAuthorizationFingerprintKeyring( + () -> + new AccountOperatorAuthorizationFingerprintKeyring.Snapshot( + new AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial( + "test-key", new SecretKeySpec(fingerprintKey, "HmacSHA256")), + List.of()), + operationClock, + Duration.ofSeconds(20)); + var hostedTerms = org.mockito.Mockito.mock(AccountHostedTermsService.class); + var transactions = org.mockito.Mockito.mock(PlatformTransactionManager.class); + var environment = + org.mockito.Mockito.mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); + when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) + .thenAnswer( + invocation -> + claimEvidence( + invocation.getArgument(0), + invocation.getArgument(1))); + + Path responseKeyringDirectory = temporaryDirectory.resolve("operator-response"); + Files.createDirectories(responseKeyringDirectory); + byte[] responseKey = new byte[AccountResponseEnvelopeKeyring.KEY_BYTES]; + java.util.Arrays.fill(responseKey, (byte) 7); + Files.writeString( + responseKeyringDirectory.resolve("keyring"), + RESPONSE_KEYRING_HEADER + + "\nactive test-key " + + java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(responseKey) + + "\n", + StandardCharsets.US_ASCII); + var responseCrypto = + new AccountResponseEnvelopeCryptography( + new AccountResponseEnvelopeKeyring(responseKeyringDirectory.toString()), + operationClock, + new java.security.SecureRandom()); + + Map durableRecords = new ConcurrentHashMap<>(); + Map originalRedemptions = new ConcurrentHashMap<>(); + when(repository.findByControlPlaneRequestId(anyString())) + .thenAnswer( + invocation -> + Optional.ofNullable(durableRecords.get(invocation.getArgument(0)))); + when(repository.createOrReadExact(any())) + .thenAnswer( + invocation -> { + var candidate = + invocation + . + getArgument(0); + IssuanceRecord issuance = issuedRecord(candidate); + IssuanceRecord existing = + durableRecords.putIfAbsent(candidate.controlPlaneRequestId(), issuance); + return new AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult( + existing == null, existing == null ? issuance : existing); + }); + when(repository.redeemExact(any())) + .thenAnswer( + invocation -> { + RedemptionRequest redemption = invocation.getArgument(0); + IssuanceRecord issuance = durableRecords.get(redemption.controlPlaneRequestId()); + assertThat(issuance).isNotNull(); + assertThat(redemption.controlPlaneRequestId()) + .isEqualTo(issuance.controlPlaneRequestId()); + assertThat(redemption.preAuthorizationTuple()) + .containsExactly(issuance.preAuthorizationTuple()); + assertThat(redemption.authorizationReferenceFingerprint()) + .isEqualTo(issuance.authorizationReferenceFingerprint()); + assertThat(redemption.reservationOwnerId()).isEqualTo(issuance.reservationOwnerId()); + assertThat(redemption.reservationClaimFence()) + .isEqualTo(issuance.reservationClaimFence()); + assertThat(redemption.redeemerWorkloadUri()).isEqualTo(GAME_SESSION_PEER); + assertThat(redemption.authorityEvidenceBundle()) + .containsExactly(issuance.authorityEvidenceBundle()); + assertThat(redemption.now()).isEqualTo(operationClock.instant()); + + boolean replay = issuance.status() == Status.REDEEMED; + if (replay) { + RedemptionRequest original = + originalRedemptions.get(redemption.controlPlaneRequestId()); + assertThat(original).isNotNull(); + assertThat(redemption.ownerAttemptId()).isEqualTo(original.ownerAttemptId()); + assertThat(redemption.ownerFence()).isEqualTo(original.ownerFence()); + } else { + assertThat(issuance.status()).isEqualTo(Status.ISSUED); + assertThat(redemption.now()).isBefore(issuance.referenceExpiresAt()); + originalRedemptions.put(redemption.controlPlaneRequestId(), redemption); + durableRecords.put( + redemption.controlPlaneRequestId(), withRedemption(issuance, redemption)); + } + return new RedemptionResult( + issuance.authorizationReferenceFingerprint(), + issuance.authorityEvidenceBundle(), + issuance.issuanceOperationId(), + issuance.issuanceFence(), + replay); + }); + when(issuanceOperations.captureOwnerLinearization()) + .thenReturn(new OwnerLinearization("123456", 99L)); + AtomicReference currentForCalls = new AtomicReference<>(current); + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(3); + return action.apply(currentForCalls.get()); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(actors) + .withCurrent(anyString(), any(), any(), any()); + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(4); + return action.apply(currentForCalls.get()); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(actors) + .withCurrentCommitted(any(), any(), any(), any(), any()); + + var service = + new AccountStartSessionOperatorAuthorizationService( + actors, + issuanceOperations, + claims, + repository, + fingerprintKeys, + responseCrypto, + hostedTerms, + transactions, + operationClock, + new java.security.SecureRandom(), + LOGGING_PEER, + GAME_SESSION_PEER, + java.time.Duration.ofSeconds(60), + java.time.Duration.ofSeconds(20)); + var issueRequest = + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + "test-only-forwarded-control-ui-credential", + exactTuple, + requestOwnerId, + 10L, + requestOwnerId, + 10L); + AtomicReference issued = + new AtomicReference<>(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(LOGGING_PEER).orElseThrow()) + .run(() -> issued.set(service.issue(issueRequest))); + + IssuanceRecord record = durableRecords.get(tuple.controlPlaneRequestId()); + assertThat(record).isNotNull(); + assertThat(record.status()).isEqualTo(Status.ISSUED); + assertThat(record.encryptedResponseEnvelope()).isNotEmpty(); + assertThat(record.encryptedResponseEnvelope().length).isLessThanOrEqualTo(160 * 1024); + AccountStartSessionOperatorAuthorityBundle bundle = + AccountStartSessionOperatorAuthorityBundle.decode(record.authorityEvidenceBundle()); + assertThat(AccountStartSessionOperatorAuthorizationService.envelopeBindingRequestId(requestId)) + .isEqualTo( + java.util.HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(requestIdBytes))); + assertThat( + AccountStartSessionOperatorAuthorizationService.envelopeBindingRequestId( + "retained-ascii-request-01")) + .isEqualTo("retained-ascii-request-01"); + + var recoverRequest = + new AccountStartSessionOperatorAuthorizationService.RecoverRequest( + exactTuple, requestOwnerId, 10L, requestOwnerId, 10L); + AtomicReference + recovered = new AtomicReference<>(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(LOGGING_PEER).orElseThrow()) + .run(() -> recovered.set(service.recover(recoverRequest))); + assertThat(recovered.get().operatorAuthorizationReference()) + .isEqualTo(issued.get().operatorAuthorizationReference()); + assertThat(recovered.get().authorityEvidenceBundle()) + .containsExactly(issued.get().authorityEvidenceBundle()); + + UUID ownerAttemptId = UUID.randomUUID(); + long ownerFence = 18L; + var redeemRequest = + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + exactTuple, + recovered.get().operatorAuthorizationReference(), + recovered.get().authorizationReferenceFingerprint(), + requestOwnerId, + 10L, + ownerAttemptId, + ownerFence); + AtomicReference firstRedemption = new AtomicReference<>(); + operationClock.setInstant(record.referenceExpiresAt().minusMillis(1)); + gameSessionContext().run(() -> firstRedemption.set(service.redeem(redeemRequest))); + assertThat(firstRedemption.get().replay()).isFalse(); + + AtomicReference recoveredRetry = new AtomicReference<>(); + operationClock.setInstant(record.referenceExpiresAt().plusSeconds(1)); + assertThat(operationClock.instant()).isBefore(record.responseEnvelopeExpiresAt()); + gameSessionContext().run(() -> recoveredRetry.set(service.redeem(redeemRequest))); + assertThat(recoveredRetry.get().replay()).isTrue(); + assertThat(recoveredRetry.get().authorizationReferenceFingerprint()) + .isEqualTo(firstRedemption.get().authorizationReferenceFingerprint()); + assertThat(recoveredRetry.get().authorityEvidenceBundle()) + .containsExactly(firstRedemption.get().authorityEvidenceBundle()); + assertThat(recoveredRetry.get().issuanceOperationId()) + .isEqualTo(firstRedemption.get().issuanceOperationId()); + assertThat(recoveredRetry.get().issuanceFence()) + .isEqualTo(firstRedemption.get().issuanceFence()); + + AtomicReference postEnvelopeRetry = new AtomicReference<>(); + operationClock.setInstant(record.responseEnvelopeExpiresAt()); + gameSessionContext().run(() -> postEnvelopeRetry.set(service.redeem(redeemRequest))); + assertThat(postEnvelopeRetry.get().replay()).isTrue(); + assertThat(postEnvelopeRetry.get().authorizationReferenceFingerprint()) + .isEqualTo(firstRedemption.get().authorizationReferenceFingerprint()); + assertThat(postEnvelopeRetry.get().authorityEvidenceBundle()) + .containsExactly(firstRedemption.get().authorityEvidenceBundle()); + assertThat(postEnvelopeRetry.get().issuanceOperationId()) + .isEqualTo(firstRedemption.get().issuanceOperationId()); + assertThat(postEnvelopeRetry.get().issuanceFence()) + .isEqualTo(firstRedemption.get().issuanceFence()); + verify(repository, times(3)).redeemExact(any()); + + var changedAttempt = + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + exactTuple, + recovered.get().operatorAuthorizationReference(), + recovered.get().authorizationReferenceFingerprint(), + requestOwnerId, + 10L, + UUID.randomUUID(), + ownerFence); + var changedFence = + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + exactTuple, + recovered.get().operatorAuthorizationReference(), + recovered.get().authorizationReferenceFingerprint(), + requestOwnerId, + 10L, + ownerAttemptId, + ownerFence + 1); + for (var changedRequest : List.of(changedAttempt, changedFence)) { + gameSessionContext() + .run( + () -> + assertThatThrownBy(() -> service.redeem(changedRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot authorize another owner attempt")); + } + + AccountControlUiAuthority.Snapshot changedSource = + source(actorId, tenantId, 8L, new byte[] {2}); + currentForCalls.set(new Current(stored, changedSource)); + gameSessionContext() + .run( + () -> + assertThatThrownBy(() -> service.redeem(redeemRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current Account source differs")); + verify(repository, times(3)).redeemExact(any()); + + currentForCalls.set(current); + StartSessionPreAuthorizationReservationTuple expiredTuple = tuple(actorId, tenantId); + byte[] expiredTupleBytes = expiredTuple.canonicalJson().getBytes(StandardCharsets.UTF_8); + var expiredIssueRequest = + new AccountStartSessionOperatorAuthorizationService.IssueRequest( + "test-only-forwarded-control-ui-credential", + expiredTupleBytes, + requestOwnerId, + 10L, + requestOwnerId, + 10L); + AtomicReference + expiredIssued = new AtomicReference<>(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(LOGGING_PEER).orElseThrow()) + .run(() -> expiredIssued.set(service.issue(expiredIssueRequest))); + IssuanceRecord expiredRecord = durableRecords.get(expiredTuple.controlPlaneRequestId()); + var firstRedemptionAfterExpiry = + new AccountStartSessionOperatorAuthorizationService.RedeemRequest( + expiredTupleBytes, + expiredIssued.get().operatorAuthorizationReference(), + expiredIssued.get().authorizationReferenceFingerprint(), + requestOwnerId, + 10L, + UUID.randomUUID(), + 19L); + operationClock.setInstant(expiredRecord.referenceExpiresAt()); + gameSessionContext() + .run( + () -> + assertThatThrownBy(() -> service.redeem(firstRedemptionAfterExpiry)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Original Account authority evidence is expired")); + verify(repository, times(3)).redeemExact(any()); + + operationClock.setInstant(record.responseEnvelopeExpiresAt().minusMillis(1)); + String distinctRequestId = "é".repeat(63) + "è"; + assertThat(distinctRequestId.getBytes(StandardCharsets.UTF_8)).hasSize(128); + assertThat( + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + distinctRequestId)) + .isEqualTo(distinctRequestId); + var distinctBinding = + new AccountResponseEnvelopeCryptography.Binding( + "human-start-session-authorization/v1", + AccountStartSessionOperatorAuthorizationService.envelopeBindingRequestId( + distinctRequestId), + MessageDigest.getInstance("SHA-256").digest(exactTuple), + LOGGING_PEER, + record.issuanceOperationId().toString(), + Optional.empty(), + Optional.empty(), + Optional.empty(), + record.issuanceFence(), + AccountControlUiAuthority.canonical(bundle.authorityTuple()), + AccountControlUiAuthority.canonical(bundle.membershipVersion()), + bundle.canonicalBytes()); + assertThatThrownBy( + () -> + responseCrypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + record.encryptedResponseEnvelope()), + distinctBinding, + record.responseEnvelopeExpiresAt())) + .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); + } + + @Test + void exactRepeatedReadReturnsOriginalRedeemedProjectionAfterCurrentnessRevalidation() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + allowCurrent(harness, harness.source()); + AtomicReference first = new AtomicReference<>(); + AtomicReference retry = new AtomicReference<>(); + + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(GAME_DESIGN_PEER).orElseThrow()) + .run( + () -> { + first.set(harness.service().readRedeemedOperationProjection(harness.request())); + retry.set(harness.service().readRedeemedOperationProjection(harness.request())); + }); + + RedeemedOperationProjection original = first.get(); + RedeemedOperationProjection exactRetry = retry.get(); + assertThat(original.controlPlaneRequestId()).isEqualTo(harness.tuple().controlPlaneRequestId()); + assertThat(original.canonicalPreAuthorizationTuple()) + .isEqualTo(harness.record().preAuthorizationTuple()); + assertThat(original.mutationDigest()).isEqualTo(harness.record().mutationDigest()); + assertThat(original.authorizationReferenceFingerprint()) + .isEqualTo(harness.record().authorizationReferenceFingerprint()); + assertThat(original.reservationOwnerId()).isEqualTo(harness.record().reservationOwnerId()); + assertThat(original.reservationClaimFence()) + .isEqualTo(harness.record().reservationClaimFence()); + assertThat(original.redeemerWorkloadUri()).isEqualTo(GAME_SESSION_PEER); + assertThat(original.ownerAttemptId()).isEqualTo(harness.record().redemptionOwnerAttemptId()); + assertThat(original.ownerFence()).isEqualTo(harness.record().redemptionOwnerFence()); + assertThat(original.referenceExpiresAt()).isEqualTo(harness.record().referenceExpiresAt()); + assertThat(original.redeemedAt()).isEqualTo(harness.record().redeemedAt()); + assertThat(original.issuanceOperationId()).isEqualTo(harness.record().issuanceOperationId()); + assertThat(original.issuanceFence()).isEqualTo(harness.record().issuanceFence()); + assertThat(original.bundleReference()) + .isEqualTo( + AccountStartSessionOperatorAuthorityBundle.fromSharedReference( + harness.record().bundleReference())); + assertThat(original.authorityEvidenceBundle()) + .isEqualTo(harness.record().authorityEvidenceBundle()); + assertThat(exactRetry.controlPlaneRequestId()).isEqualTo(original.controlPlaneRequestId()); + assertThat(exactRetry.canonicalPreAuthorizationTuple()) + .isEqualTo(original.canonicalPreAuthorizationTuple()); + assertThat(exactRetry.authorityEvidenceBundle()).isEqualTo(original.authorityEvidenceBundle()); + + byte[] mutatedCopy = original.authorityEvidenceBundle(); + mutatedCopy[0] ^= 0x01; + assertThat(original.authorityEvidenceBundle()) + .isEqualTo(harness.record().authorityEvidenceBundle()); + assertThat(original.toString()).doesNotContain("operatorAuthorizationReference"); + assertThat(original.toString()).doesNotContain("controlUiJwt"); + verify(harness.actors(), times(2)) + .withCurrentCommitted( + eq(harness.actorId()), + eq(harness.tenantId()), + eq(harness.tokenJti()), + eq(harness.environment()), + any()); + verify(harness.repository(), times(4)) + .findByControlPlaneRequestId(harness.tuple().controlPlaneRequestId()); + verify(harness.repository(), never()).createOrReadExact(any()); + verify(harness.repository(), never()).redeemExact(any()); + verifyNoInteractions(harness.claims(), harness.fingerprintKeys(), harness.responseCrypto()); + } + + @Test + void projectionRequiresExactSameNamespaceGameDesignPeerBeforeTupleParsingOrLookup() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + ReadRedeemedOperationProjectionRequest malformed = + new ReadRedeemedOperationProjectionRequest( + "not canonical tuple".getBytes(StandardCharsets.UTF_8), + harness.request().authorizationReferenceFingerprint(), + harness.request().reservationOwnerId(), + harness.request().reservationClaimFence(), + harness.request().ownerAttemptId(), + harness.request().ownerFence()); + + for (String wrongPeerUri : + List.of( + "spiffe://firemud/ns/other/sa/game-design-service", GAME_SESSION_PEER, LOGGING_PEER)) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(wrongPeerUri).orElseThrow()) + .run( + () -> + assertThatThrownBy( + () -> harness.service().readRedeemedOperationProjection(malformed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact authenticated internal workload identity")); + } + + verify(harness.repository(), never()).findByControlPlaneRequestId(anyString()); + verify(harness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); + verify(harness.hostedTerms(), never()).captureCurrentEnvironmentBoundary(); + } + + @Test + void projectionRejectsMissingUnredeemedAndWrongRedeemerRecords() { + Context gameDesignContext = gameDesignContext(); + + ReadHarness missingHarness = readHarness(NOW.plusSeconds(30)); + when(missingHarness + .repository() + .findByControlPlaneRequestId(missingHarness.tuple().controlPlaneRequestId())) + .thenReturn(Optional.empty()); + gameDesignContext.run( + () -> + assertThatThrownBy( + () -> + missingHarness + .service() + .readRedeemedOperationProjection(missingHarness.request())) + .isInstanceOf( + AccountStartSessionOperatorAuthorizationService.NotFoundException.class)); + verify(missingHarness.actors(), never()) + .withCurrentCommitted(any(), any(), any(), any(), any()); + + ReadHarness issuedHarness = readHarness(NOW.plusSeconds(30)); + IssuanceRecord issued = asIssued(issuedHarness.record()); + when(issuedHarness + .repository() + .findByControlPlaneRequestId(issuedHarness.tuple().controlPlaneRequestId())) + .thenReturn(Optional.of(issued)); + gameDesignContext.run( + () -> + assertThatThrownBy( + () -> + issuedHarness + .service() + .readRedeemedOperationProjection(issuedHarness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); + verify(issuedHarness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); + + ReadHarness wrongRedeemerHarness = readHarness(NOW.plusSeconds(30)); + IssuanceRecord wrongRedeemer = + withRedeemer( + wrongRedeemerHarness.record(), "spiffe://firemud/ns/other/sa/game-session-service"); + when(wrongRedeemerHarness + .repository() + .findByControlPlaneRequestId(wrongRedeemerHarness.tuple().controlPlaneRequestId())) + .thenReturn(Optional.of(wrongRedeemer)); + gameDesignContext.run( + () -> + assertThatThrownBy( + () -> + wrongRedeemerHarness + .service() + .readRedeemedOperationProjection(wrongRedeemerHarness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); + verify(wrongRedeemerHarness.actors(), never()) + .withCurrentCommitted(any(), any(), any(), any(), any()); + } + + @Test + void projectionRejectsTupleOwnerAttemptFenceAndFingerprintSubstitutionBeforeCurrentActorLookup() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + ReadRedeemedOperationProjectionRequest original = harness.request(); + UUID substitutedActorId = UUID.randomUUID(); + StartSessionOperatorAction originalAction = harness.tuple().action(); + StartSessionOperatorAction substitutedAction = + new StartSessionOperatorAction( + originalAction.actionFamilySchemaId(), + originalAction.actionFamilySchemaVersion(), + originalAction.scope(), + new StartSessionOperatorAction.Target( + originalAction.target().gameTemplateId(), substitutedActorId), + originalAction.expectedVersion(), + originalAction.mutation(), + originalAction.auditReason()); + byte[] substitutedTuple = + StartSessionPreAuthorizationReservationTuple.createHuman( + harness.tuple().controlPlaneRequestId(), substitutedActorId, substitutedAction) + .canonicalJson() + .getBytes(StandardCharsets.UTF_8); + var requests = + List.of( + new ReadRedeemedOperationProjectionRequest( + substitutedTuple, + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.ownerAttemptId(), + original.ownerFence()), + new ReadRedeemedOperationProjectionRequest( + original.canonicalPreAuthorizationTuple(), + original.authorizationReferenceFingerprint(), + UUID.randomUUID(), + original.reservationClaimFence(), + original.ownerAttemptId(), + original.ownerFence()), + new ReadRedeemedOperationProjectionRequest( + original.canonicalPreAuthorizationTuple(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence() + 1, + original.ownerAttemptId(), + original.ownerFence()), + new ReadRedeemedOperationProjectionRequest( + original.canonicalPreAuthorizationTuple(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + UUID.randomUUID(), + original.ownerFence()), + new ReadRedeemedOperationProjectionRequest( + original.canonicalPreAuthorizationTuple(), + "arfp/v1/test-key/" + "b".repeat(64), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.ownerAttemptId(), + original.ownerFence()), + new ReadRedeemedOperationProjectionRequest( + original.canonicalPreAuthorizationTuple(), + original.authorizationReferenceFingerprint(), + original.reservationOwnerId(), + original.reservationClaimFence(), + original.ownerAttemptId(), + original.ownerFence() + 1)); + Context gameDesignContext = gameDesignContext(); + + for (ReadRedeemedOperationProjectionRequest request : requests) { + gameDesignContext.run( + () -> + assertThatThrownBy(() -> harness.service().readRedeemedOperationProjection(request)) + .isInstanceOf(IllegalStateException.class)); + } + + verify(harness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); + + ReadHarness expiredHarness = readHarness(NOW.minusSeconds(10)); + gameDesignContext.run( + () -> + assertThatThrownBy( + () -> + expiredHarness + .service() + .readRedeemedOperationProjection(expiredHarness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); + verify(expiredHarness.actors(), never()) + .withCurrentCommitted(any(), any(), any(), any(), any()); + } + + @Test + void projectionRejectsRevokedOrChangedCurrentAccountSource() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + AccountControlUiAuthority.Snapshot changedSource = + source(harness.actorId(), harness.tenantId(), 8L, new byte[] {2}); + allowCurrent(harness, changedSource); + + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(GAME_DESIGN_PEER).orElseThrow()) + .run( + () -> + assertThatThrownBy( + () -> harness.service().readRedeemedOperationProjection(harness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current Account source")); + + verify(harness.actors()) + .withCurrentCommitted( + eq(harness.actorId()), + eq(harness.tenantId()), + eq(harness.tokenJti()), + eq(harness.environment()), + any()); + verifyNoInteractions(harness.claims(), harness.fingerprintKeys(), harness.responseCrypto()); + } + + @Test + void recoveryDoesNotDecryptOrRecreateAnErasedOriginalResponse() { + ReadHarness harness = readHarness(NOW.plusSeconds(30)); + IssuanceRecord erased = asIssued(withErasedEnvelope(harness.record())); + when(harness.repository().findByControlPlaneRequestId(harness.tuple().controlPlaneRequestId())) + .thenReturn(Optional.of(erased)); + when(harness + .claims() + .readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) + .thenReturn(claimEvidence(harness.tuple(), erased.reservationOwnerId())); + allowCurrent(harness, harness.source()); + + var request = + new AccountStartSessionOperatorAuthorizationService.RecoverRequest( + harness.tuple().canonicalJson().getBytes(StandardCharsets.UTF_8), + erased.reservationOwnerId(), + erased.reservationClaimFence(), + erased.reservationOwnerId(), + erased.reservationClaimFence()); + + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(LOGGING_PEER).orElseThrow()) + .run( + () -> + assertThatThrownBy(() -> harness.service().recover(request)) + .isInstanceOf( + AccountStartSessionOperatorAuthorizationService + .ResponseEnvelopeErasedException.class)); + + verify(harness.responseCrypto(), never()).decrypt(any(), any(), any()); + verify(harness.repository(), never()).createOrReadExact(any()); + } + + private static ReadHarness readHarness(Instant referenceExpiresAt) { + UUID actorId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID reservationOwnerId = UUID.randomUUID(); + UUID ownerAttemptId = UUID.randomUUID(); + UUID issuanceOperationId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + StartSessionPreAuthorizationReservationTuple tuple = tuple(actorId, tenantId); + AccountControlUiAuthority.Snapshot source = source(actorId, tenantId, 7L, new byte[] {1}); + AccountControlUiIssuanceRepository.Stored stored = + stored(actorId, tenantId, tokenJti, issuanceOperationId, source); + OwnerLinearization linearization = new OwnerLinearization("123456", 99L); + Instant issuedAt = referenceExpiresAt.minusSeconds(50); + Instant redeemedAt = + referenceExpiresAt.isAfter(NOW) ? NOW.minusSeconds(1) : referenceExpiresAt.minusSeconds(1); + var bundle = + AccountStartSessionOperatorAuthorityBundle.create( + tuple, + source, + stored, + issuanceOperationId, + linearization, + issuedAt, + referenceExpiresAt); + var bundleReference = bundle.referenceForSource(source, linearization); + String fingerprint = "arfp/v1/test-key/" + "a".repeat(64); + IssuanceRecord record = + new IssuanceRecord( + tuple.controlPlaneRequestId(), + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + tuple.mutationDigest(), + LOGGING_PEER, + reservationOwnerId, + 10L, + issuanceOperationId, + linearization.sourceFence(), + AccountStartSessionOperatorAuthorityBundle.toSharedReference(bundleReference), + bundle.canonicalBytes(), + fingerprint, + new byte[] {9, 8, 7}, + issuedAt, + referenceExpiresAt, + referenceExpiresAt.plusSeconds(20), + null, + Status.REDEEMED, + GAME_SESSION_PEER, + ownerAttemptId, + 18L, + redeemedAt, + fingerprint, + bundle.canonicalBytes()); + + var actors = org.mockito.Mockito.mock(AccountControlUiActorService.class); + var issuanceOperations = org.mockito.Mockito.mock(AccountControlUiIssuanceRepository.class); + var claims = org.mockito.Mockito.mock(StartSessionReservationEvidenceClient.class); + var repository = + org.mockito.Mockito.mock(AccountStartSessionOperatorAuthorizationRepository.class); + var fingerprintKeys = + org.mockito.Mockito.mock(AccountOperatorAuthorizationFingerprintKeyring.class); + var responseCrypto = org.mockito.Mockito.mock(AccountResponseEnvelopeCryptography.class); + var hostedTerms = org.mockito.Mockito.mock(AccountHostedTermsService.class); + var transactions = org.mockito.Mockito.mock(PlatformTransactionManager.class); + var environment = + org.mockito.Mockito.mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(transactions.getTransaction(any(TransactionDefinition.class))) + .thenAnswer(ignored -> new SimpleTransactionStatus()); + when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); + when(repository.findByControlPlaneRequestId(tuple.controlPlaneRequestId())) + .thenReturn(Optional.of(record)); + var service = + new AccountStartSessionOperatorAuthorizationService( + actors, + issuanceOperations, + claims, + repository, + fingerprintKeys, + responseCrypto, + hostedTerms, + transactions, + Clock.fixed(NOW, ZoneOffset.UTC), + new java.security.SecureRandom(), + LOGGING_PEER, + GAME_SESSION_PEER, + java.time.Duration.ofSeconds(60), + java.time.Duration.ofSeconds(20)); + ReadRedeemedOperationProjectionRequest request = + new ReadRedeemedOperationProjectionRequest( + tuple.canonicalJson().getBytes(StandardCharsets.UTF_8), + fingerprint, + reservationOwnerId, + 10L, + ownerAttemptId, + 18L); + return new ReadHarness( + service, + actors, + claims, + repository, + fingerprintKeys, + responseCrypto, + hostedTerms, + environment, + tuple, + source, + stored, + record, + request, + actorId, + tenantId, + tokenJti); + } + + private static void allowCurrent( + ReadHarness harness, AccountControlUiAuthority.Snapshot currentSource) { + doAnswer( + invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + @SuppressWarnings("unchecked") + Function action = invocation.getArgument(4); + return action.apply(new Current(harness.stored(), currentSource)); + } finally { + TransactionSynchronizationManager.clear(); + } + }) + .when(harness.actors()) + .withCurrentCommitted(any(), any(), any(), any(), any()); + } + + private static IssuanceRecord asIssued(IssuanceRecord record) { + return new IssuanceRecord( + record.controlPlaneRequestId(), + record.preAuthorizationTuple(), + record.mutationDigest(), + record.issuanceWorkloadUri(), + record.reservationOwnerId(), + record.reservationClaimFence(), + record.issuanceOperationId(), + record.issuanceFence(), + record.bundleReference(), + record.authorityEvidenceBundle(), + record.authorizationReferenceFingerprint(), + record.encryptedResponseEnvelope(), + record.issuedAt(), + record.referenceExpiresAt(), + record.responseEnvelopeExpiresAt(), + record.responseEnvelopeErasedAt(), + Status.ISSUED, + null, + null, + null, + null, + null, + null); + } + + private static IssuanceRecord withErasedEnvelope(IssuanceRecord record) { + return new IssuanceRecord( + record.controlPlaneRequestId(), + record.preAuthorizationTuple(), + record.mutationDigest(), + record.issuanceWorkloadUri(), + record.reservationOwnerId(), + record.reservationClaimFence(), + record.issuanceOperationId(), + record.issuanceFence(), + record.bundleReference(), + record.authorityEvidenceBundle(), + record.authorizationReferenceFingerprint(), + null, + record.issuedAt(), + record.referenceExpiresAt(), + record.responseEnvelopeExpiresAt(), + record.responseEnvelopeExpiresAt(), + record.status(), + record.redemptionRedeemerWorkloadUri(), + record.redemptionOwnerAttemptId(), + record.redemptionOwnerFence(), + record.redeemedAt(), + record.redemptionReferenceFingerprint(), + record.redemptionAuthorityEvidenceBundle()); + } + + private static IssuanceRecord withRedemption( + IssuanceRecord record, RedemptionRequest redemption) { + return new IssuanceRecord( + record.controlPlaneRequestId(), + record.preAuthorizationTuple(), + record.mutationDigest(), + record.issuanceWorkloadUri(), + record.reservationOwnerId(), + record.reservationClaimFence(), + record.issuanceOperationId(), + record.issuanceFence(), + record.bundleReference(), + record.authorityEvidenceBundle(), + record.authorizationReferenceFingerprint(), + record.encryptedResponseEnvelope(), + record.issuedAt(), + record.referenceExpiresAt(), + record.responseEnvelopeExpiresAt(), + record.responseEnvelopeErasedAt(), + Status.REDEEMED, + redemption.redeemerWorkloadUri(), + redemption.ownerAttemptId(), + redemption.ownerFence(), + redemption.now(), + redemption.authorizationReferenceFingerprint(), + redemption.authorityEvidenceBundle()); + } + + private static IssuanceRecord withRedeemer(IssuanceRecord record, String redeemerWorkloadUri) { + return new IssuanceRecord( + record.controlPlaneRequestId(), + record.preAuthorizationTuple(), + record.mutationDigest(), + record.issuanceWorkloadUri(), + record.reservationOwnerId(), + record.reservationClaimFence(), + record.issuanceOperationId(), + record.issuanceFence(), + record.bundleReference(), + record.authorityEvidenceBundle(), + record.authorizationReferenceFingerprint(), + record.encryptedResponseEnvelope(), + record.issuedAt(), + record.referenceExpiresAt(), + record.responseEnvelopeExpiresAt(), + record.responseEnvelopeErasedAt(), + Status.REDEEMED, + redeemerWorkloadUri, + record.redemptionOwnerAttemptId(), + record.redemptionOwnerFence(), + record.redeemedAt(), + record.redemptionReferenceFingerprint(), + record.redemptionAuthorityEvidenceBundle()); + } + + private static Context gameDesignContext() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri(GAME_DESIGN_PEER).orElseThrow()); + } + + private static Context gameSessionContext() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri(GAME_SESSION_PEER).orElseThrow()); + } + + private static final class MutableClock extends Clock { + private final AtomicReference currentInstant; + private final ZoneId zone; + + MutableClock(Instant initialInstant) { + this(new AtomicReference<>(initialInstant), ZoneOffset.UTC); + } + + private MutableClock(AtomicReference currentInstant, ZoneId zone) { + this.currentInstant = currentInstant; + this.zone = zone; + } + + void setInstant(Instant instant) { + currentInstant.set(instant); + } + + @Override + public ZoneId getZone() { + return zone; + } + + @Override + public Clock withZone(ZoneId requestedZone) { + return new MutableClock(currentInstant, requestedZone); + } + + @Override + public Instant instant() { + return currentInstant.get(); + } + } + + private record ReadHarness( + AccountStartSessionOperatorAuthorizationService service, + AccountControlUiActorService actors, + StartSessionReservationEvidenceClient claims, + AccountStartSessionOperatorAuthorizationRepository repository, + AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys, + AccountResponseEnvelopeCryptography responseCrypto, + AccountHostedTermsService hostedTerms, + AccountHostedTermsService.CapturedEnvironmentBoundary environment, + StartSessionPreAuthorizationReservationTuple tuple, + AccountControlUiAuthority.Snapshot source, + AccountControlUiIssuanceRepository.Stored stored, + IssuanceRecord record, + ReadRedeemedOperationProjectionRequest request, + UUID actorId, + UUID tenantId, + UUID tokenJti) {} + + private static StartSessionPreAuthorizationReservationTuple tuple(UUID actorId, UUID tenantId) { + return tuple("request-" + UUID.randomUUID(), actorId, tenantId); + } + + private static StartSessionPreAuthorizationReservationTuple tuple( + String requestId, UUID actorId, UUID tenantId) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(tenantId, "test"), + new StartSessionOperatorAction.Target(1L, actorId), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "authorization test"); + return StartSessionPreAuthorizationReservationTuple.createHuman(requestId, actorId, action); + } + + private static IssuanceRecord issuedRecord( + AccountStartSessionOperatorAuthorizationRepository.IssuanceCandidate candidate) { + return new IssuanceRecord( + candidate.controlPlaneRequestId(), + candidate.preAuthorizationTuple(), + candidate.mutationDigest(), + candidate.issuanceWorkloadUri(), + candidate.reservationOwnerId(), + candidate.reservationClaimFence(), + candidate.issuanceOperationId(), + candidate.issuanceFence(), + candidate.bundleReference(), + candidate.authorityEvidenceBundle(), + candidate.authorizationReferenceFingerprint(), + candidate.encryptedResponseEnvelope(), + candidate.issuedAt(), + candidate.referenceExpiresAt(), + candidate.responseEnvelopeExpiresAt(), + null, + Status.ISSUED, + null, + null, + null, + null, + null, + null); + } + + private static AccountControlUiAuthority.Snapshot source( + UUID actorId, UUID tenantId, long sourceVersion, byte[] evidence) { + var source = org.mockito.Mockito.mock(AccountControlUiAuthority.Snapshot.class); + Map authorityTuple = + Map.of( + "issuerAuthGeneration", + 1L, + "accountAuthorityGeneration", + 1L, + "tenantAuthorityGeneration", + Map.of(tenantId.toString(), 1L), + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), 1L), + "privateRealmGrantVersions", + List.of()); + Map membershipVersion = Map.of(tenantId.toString(), 2L); + when(source.actor()).thenReturn(actorId); + when(source.tenant()).thenReturn(tenantId); + when(source.authorityTuple()).thenReturn(authorityTuple); + when(source.membershipVersion()).thenReturn(membershipVersion); + when(source.evidence()).thenReturn(evidence.clone()); + when(source.sources()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + actorId.toString(), + "1", + Long.toString(sourceVersion), + null, + null, + evidence))); + return source; + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static AccountControlUiIssuanceRepository.Stored stored( + UUID actorId, + UUID tenantId, + UUID tokenJti, + UUID operationId, + AccountControlUiAuthority.Snapshot source) { + UUID requestId = UUID.randomUUID(); + Map claims = + Map.of( + "jti", + tokenJti.toString(), + "sub", + actorId.toString(), + "accountId", + actorId.toString(), + "aud", + "control-ui", + "tokenGeneration", + 1L, + "authorityTuple", + source.authorityTuple(), + "membershipVersion", + source.membershipVersion(), + "scopedRoles", + Map.of(tenantId.toString(), List.of("tenantAdmin"))); + Map values = + Map.ofEntries( + Map.entry("request_id", requestId), + Map.entry("operation_id", operationId), + Map.entry("token_jti", tokenJti), + Map.entry("account_uuid", actorId), + Map.entry("tenant_uuid", tenantId), + Map.entry("caller_context_id", UUID.randomUUID()), + Map.entry("caller_workload", "spiffe://firemud/ns/test/sa/account-service"), + Map.entry("request_mac_key_id", "test-key"), + Map.entry("request_digest", "b".repeat(64)), + Map.entry("status", "COMMITTED"), + Map.entry("token_hash", "c".repeat(64)), + Map.entry("claims_payload", AccountControlUiAuthority.canonical(claims)), + Map.entry("source_payload", source.evidence()), + Map.entry("bundle_payload", AccountControlUiAuthority.canonical(Map.of("v", 1))), + Map.entry("signer_receipt", AccountControlUiAuthority.canonical(Map.of("v", 1))), + Map.entry("pending_registry", new byte[] {1}), + Map.entry("active_registry", new byte[] {2}), + Map.entry("issued_at_epoch_second", NOW.minusSeconds(10).getEpochSecond()), + Map.entry("expires_at_epoch_second", NOW.plusSeconds(300).getEpochSecond()), + Map.entry( + "recovery_expires_at", + OffsetDateTime.ofInstant(NOW.plusSeconds(300), ZoneOffset.UTC))); + Record row = org.mockito.Mockito.mock(Record.class); + org.mockito.Mockito.doAnswer(invocation -> values.get(invocation.getArgument(0))) + .when(row) + .get(anyString(), any(Class.class)); + return new AccountControlUiIssuanceRepository.Stored(row); + } + + private static ReadCurrentClaimEvidenceResponse claimEvidence( + StartSessionPreAuthorizationReservationTuple tuple, UUID ownerId) { + return ReadCurrentClaimEvidenceResponse.newBuilder() + .setControlPlaneRequestId(tuple.controlPlaneRequestId()) + .setPreAuthorizationTupleJson( + ByteString.copyFrom(tuple.canonicalJson(), StandardCharsets.UTF_8)) + .setMutationDigest(tuple.mutationDigest()) + .setReservationOwnerId(ownerId.toString()) + .setReservationClaimFence(10L) + .setClaimOwnerId(ownerId.toString()) + .setClaimFence(10L) + .build(); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java new file mode 100644 index 0000000000..8bcd6c5d1f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java @@ -0,0 +1,119 @@ +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.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.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.MockedStatic; + +class LettuceAccountCoordinationPinnedConnectionProviderTest { + @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 (MockedStatic redisClientFactory = mockStatic(RedisClient.class)) { + redisClientFactory.when(() -> RedisClient.create(uri)).thenReturn(client); + LettuceAccountCoordinationPinnedConnectionProvider provider = + new LettuceAccountCoordinationPinnedConnectionProvider(uri); + + assertThat(provider.openPinnedConnection()).isSameAs(connection); + + ArgumentCaptor options = ArgumentCaptor.forClass(ClientOptions.class); + InOrder 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); + redisClientFactory.verify(() -> RedisClient.create(uri), times(1)); + } + } + + @Test + void shutsDownClientIfReconnectConfigurationCannotBeApplied() { + RedisClient client = mock(RedisClient.class); + IllegalStateException failure = new IllegalStateException("options rejected"); + doThrow(failure).when(client).setOptions(any(ClientOptions.class)); + RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); + + try (MockedStatic redisClientFactory = mockStatic(RedisClient.class)) { + redisClientFactory.when(() -> RedisClient.create(uri)).thenReturn(client); + assertThatThrownBy(() -> new LettuceAccountCoordinationPinnedConnectionProvider(uri)) + .isSameAs(failure); + + verify(client).shutdown(); + } + } + + @Test + void disposesConnectionThatFinishesAfterConcurrentProviderClose() throws Exception { + RedisClient client = mock(RedisClient.class); + StatefulRedisConnection connection = connection(); + RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); + CountDownLatch connectStarted = new CountDownLatch(1); + CountDownLatch 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; + }); + ExecutorService executor = Executors.newSingleThreadExecutor(); + try (MockedStatic redisClientFactory = mockStatic(RedisClient.class)) { + redisClientFactory.when(() -> RedisClient.create(uri)).thenReturn(client); + LettuceAccountCoordinationPinnedConnectionProvider provider = + new LettuceAccountCoordinationPinnedConnectionProvider(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); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java new file mode 100644 index 0000000000..359ce03c02 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -0,0 +1,530 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import de.mkammerer.argon2.Argon2Factory; +import io.grpc.Context; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftSourceCompositionService; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.entity.Account; +import net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsCatalogVersion; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEncoding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBinding; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsEnvironmentBindingRepository; +import net.firedevops.firemud.accountservice.hostedterms.HostedTermsRepository; +import net.firedevops.firemud.accountservice.mapper.AccountMapper; +import net.firedevops.firemud.accountservice.repository.AccountAuditOutboxRepository; +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.AccountEmailLoginChallengeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCreatorMembershipSourceReader; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapAuthorizationSource; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest; +import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence; +import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.mapstruct.factory.Mappers; +import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; +import org.springframework.transaction.interceptor.TransactionInterceptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Real Account source/auth owners with explicitly stipulated upstream creator/legal inputs. */ +final class AccountControlUiOwnerSourcesFixture { + private static final String NAMESPACE = "control-ui-owner-proof"; + static final String CALLER = + "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + public static final String OTP = "test-only-original-creator-otp"; + final DSLContext dsl; + final TransactionTemplate transactions; + final Account account; + final AccountRepository accounts; + final UUID tenant; + final UUID request = UUID.randomUUID(), callerContext = UUID.randomUUID(); + final AtomicReference boundary = + new AtomicReference<>(testBoundary("test-production")); + final AtomicInteger coordinationCalls = new AtomicInteger(); + final AccountEmailLoginChallengeRepository challenges; + final AccountHostedTermsService terms; + final AccountControlUiAuthority authority; + final AccountControlUiIssuanceService service; + final DataSourceTransactionManager manager; + final DraftAuthorizationFenceRepository fences; + final AccountServiceImpl primary; + + /** + * Reuses actual Account/source/auth owners while a composed test supplies signer/Redis owners. + */ + AccountControlUiOwnerSourcesFixture( + String jdbcUrl, String username, String password, Path root, boolean installNegativeIssuer) + throws Exception { + this(jdbcUrl, username, password, root, installNegativeIssuer, UUID.randomUUID()); + } + + AccountControlUiOwnerSourcesFixture( + String jdbcUrl, + String username, + String password, + Path root, + boolean installNegativeIssuer, + UUID tenant) + throws Exception { + this.tenant = Objects.requireNonNull(tenant); + String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); + var dataSource = new DriverManagerDataSource(jdbcUrl, username, password); + dataSource.setSchema(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("filesystem:" + accountMigrations()) + .load() + .migrate(); + manager = new DataSourceTransactionManager(dataSource); + transactions = new TransactionTemplate(manager); + transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var generations = new AccountAuthorityGenerationRepository(dsl); + var outbox = new AccountAuthorityOutboxRepository(dsl); + var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); + accounts = new AccountRepository(dsl, sourceEvidence); + account = + tx( + () -> { + Account candidate = new Account(); + String suffix = UUID.randomUUID().toString(); + candidate.setUsername("owner-" + suffix); + candidate.setEmail(suffix + "@example.test"); + candidate.setPasswordHash(hash("test-only-disabled-password")); + candidate.setLoginAuthModes("EMAIL_OTP"); + return accounts.save(candidate); + }); + var creator = testCreation(account.getAccountUuid(), tenant); + var fresh = new FreshTenantIdentityAssociationRepository(dsl, NAMESPACE); + tx( + () -> { + fresh.importVerified(creator.creationEvidence()); + generations.initializeTenantIfAbsent(tenant); + return null; + }); + var pairs = new AccountMembershipPairAuthorityRepository(dsl); + var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); + var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); + var bootstrapOperations = new AccountTenantCreationBootstrapOperationRepository(dsl); + var reader = + new AccountCreatorMembershipSourceReader( + accounts, + new AccountJoinOperationRepository(dsl), + memberships, + pairs, + roles, + fresh, + generations, + outbox, + sourceEvidence, + bootstrapOperations); + var beans = new StaticListableBeanFactory(); + AccountTenantCreationBootstrapAuthorizationSource externalBootstrap = + (actual, mutation) -> { + if (!creator.equals(actual) + || !TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Exact test-only external bootstrap fixture required"); + } + return mutation.get(); + }; + beans.addBean("testOnlyBootstrapAuthority", externalBootstrap); + var bootstrap = + new AccountTenantCreationBootstrapService( + accounts, + fresh, + reader, + pairs, + memberships, + roles, + outbox, + new AccountAuditOutboxRepository(dsl), + bootstrapOperations, + beans.getBeanProvider(AccountTenantCreationBootstrapAuthorizationSource.class)); + tx(() -> bootstrap.bootstrap(creator)); + var party = + new IndividualCreatorPartySource( + UUID.randomUUID(), + account.getAccountUuid(), + VerificationStatus.VERIFIED, + 1L, + "test-only-policy", + 1L, + "test-only-verification", + 1L, + 1L); + insertTestParty(dsl, party); + var parties = new IndividualCreatorPartyRepository(dsl, fresh, bootstrapOperations); + tx(() -> parties.associateFresh(UUID.randomUUID(), creator, party)); + fences = new DraftAuthorizationFenceRepository(dsl); + Map publications = new HashMap<>(); + Map actions = new HashMap<>(); + Map bindings = new HashMap<>(); + terms = + new AccountHostedTermsService( + manager, + new HostedTermsRepository(dsl), + parties, + fences, + id -> externalFixture(publications, id), + id -> externalFixture(actions, id), + new HostedTermsEnvironmentBindingRepository(dsl), + id -> externalFixture(bindings, id), + () -> { + requireOutsideTransaction(); + return boundary.get(); + }); + UUID publication = UUID.randomUUID(); + publications.put( + publication, + new AccountHostedTermsService.PublicationEvidence( + UUID.randomUUID(), + "Test-only Operator", + 1L, + bytes("Test-only initial terms"), + HostedTermsCatalogVersion.Materiality.INITIAL, + null, + null, + "test-only-publication-audit", + 1L, + "test-only-notice", + 1L, + Instant.now().minusSeconds(30).truncatedTo(ChronoUnit.MICROS))); + var catalog = terms.publish(publication).candidate(); + UUID action = UUID.randomUUID(); + actions.put( + action, + new AccountHostedTermsService.AcceptanceAction( + action, + true, + account.getAccountUuid(), + party.creatorPartyId(), + catalog.hostedScopeId(), + catalog.versionId(), + catalog.documentDigest(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + "test-only-affirmative-action", + 1L, + OffsetDateTime.now(ZoneOffset.UTC))); + terms.accept(action); + UUID binding = UUID.randomUUID(); + bindings.put( + binding, + new HostedTermsEnvironmentBinding.PublicationEvidence( + "test-production", + catalog.hostedScopeId(), + catalog.operatorLegalIdentity(), + catalog.operatorIdentityVersion(), + catalog.versionId(), + catalog.sourceVersion(), + "test-only-environment-publisher", + "test-only-environment-publication/" + binding, + null, + null)); + terms.publishEnvironmentBinding(binding); + authority = + new AccountControlUiAuthority( + new AccountDraftSourceCompositionService( + dsl, parties, bootstrap, terms, sourceEvidence)); + challenges = new AccountEmailLoginChallengeRepository(dsl); + tx( + () -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); + var primaryTarget = + new AccountServiceImpl( + accounts, + generations, + sourceEvidence, + outbox, + mock( + net.firedevops.firemud.accountservice.repository + .AccountPasswordResetOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountLogoutAllOperationRepository + .class), + mock( + net.firedevops.firemud.accountservice.repository + .AccountSecurityStateOperationRepository.class), + mock( + net.firedevops.firemud.accountservice.service + .AccountPasswordResetDraftSourceChangeRepository.class), + mock(AccountAuditOutboxRepository.class), + mock( + net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository + .class), + mock(AccountJoinOperationRepository.class), + challenges, + null, // Realm grants are not used by primary authentication. + null, // Tenant memberships are not used by primary authentication. + Mappers.getMapper(AccountMapper.class), + null, // Profiles are not used by primary authentication. + null, // Profile mapper is not used by primary authentication. + null, // Payment transactions are not used by primary authentication. + null, // Subscriptions are not used by primary authentication. + null, // External identities are not used by primary authentication. + null, // Password reset tokens are not used by primary authentication. + null, // Email verification tokens are not used by primary authentication. + null, // Notifications are not used by primary authentication. + null, // Email delivery is not used by primary authentication. + null, // Mail properties are not used by primary authentication. + null, // Token properties are not used by primary authentication. + null, // JWT auth properties are not used by primary authentication. + null, // Game Session client is not used by primary authentication. + null, // Entity Management client is not used by primary authentication. + null, // JWT utility is not used by primary authentication. + null, // Session service is not used by primary authentication. + manager); + // Exercise the real MANDATORY interceptor: noRollbackFor must not poison the owner callback. + var primaryProxy = new ProxyFactory(primaryTarget); + primaryProxy.setProxyTargetClass(true); + primaryProxy.addAdvice( + new TransactionInterceptor(manager, new AnnotationTransactionAttributeSource())); + primary = (AccountServiceImpl) primaryProxy.getProxy(); + if (!installNegativeIssuer) { + service = null; + return; + } + var signerFixture = new AccountControlUiSignerFixture(this, root); + signerFixture.prepareInitialPrepublication(); + var signer = signerFixture.signer; + var operations = new AccountControlUiIssuanceRepository(dsl); + var crypto = + new AccountControlUiResponseCryptography( + new AccountControlUiKeyring(root.resolve("custody")), Clock.systemUTC()); + var registry = + new AccountControlUiCoordination( + () -> { + coordinationCalls.incrementAndGet(); + throw new IllegalStateException("No physical Redis fixture in this negative proof"); + }, + new AcknowledgementRequirements(1, 1, 1000), + RedisScriptCatalog.fromContributions(List.of())); + var publicSource = + new AccountJwtJwksTrustedSource( + signerFixture.client, + signerFixture.trust, + signerFixture.desired, + signerFixture.publication, + manager); + var actors = + new AccountControlUiActorService( + operations, + authority, + signer, + registry, + publicSource, + fences, + manager, + Clock.systemUTC()); + service = + new AccountControlUiIssuanceService( + primary, + operations, + authority, + fences, + signer, + crypto, + registry, + actors, + manager, + Clock.systemUTC(), + 300_000L, + CALLER); + } + + AccountControlUiIssuanceService.Request request(String secret) { + return new AccountControlUiIssuanceService.Request( + request, account.getEmail(), secret, tenant, callerContext); + } + + T tx(Supplier action) { + return transactions.execute(ignored -> action.get()); + } + + /** Uses the real owner to advance generation, fence and source event with the scalar role. */ + Account changeRoleToAdmin() { + Account current = accounts.findById(account.getId()).orElseThrow(); + current.setRole("admin"); + return accounts.save(current); + } + + void assertNoIssuance() { + assertThat(dsl.fetchCount(DSL.table("account_control_ui_issuance_operations"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isZero(); + assertThat(coordinationCalls).hasValue(0); + } + + private static FreshTenantCreatorEvidence testCreation(UUID account, UUID tenant) { + UUID request = UUID.randomUUID(), + operation = UUID.randomUUID(), + authorization = UUID.randomUUID(); + String key = "test-only-game-row-17"; + String digest = + GameTenantCreationDigest.requestDigest(NAMESPACE, request, key, "Test game", null); + var creation = + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + request, + operation, + digest, + tenant, + 17L, + key, + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + NAMESPACE, request, operation, digest, tenant, 17L, key, "NEW_GAME_ROW")); + String authorizationDigest = "sha256:" + "8".repeat(64); + return new FreshTenantCreatorEvidence( + 1, + creation, + account, + authorization, + authorizationDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, account, authorization, authorizationDigest)); + } + + private static void insertTestParty(DSLContext dsl, IndividualCreatorPartySource party) { + byte[] source = CreatorPartyEncoding.party(party); + dsl.execute( + "INSERT INTO account_individual_creator_party_sources" + + " (creator_party_id, account_uuid, verification_status, identity_version, policy_reference, policy_version," + + " verification_evidence_reference, verification_evidence_version, source_version, source_payload, source_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.verificationStatus().name(), + party.identityVersion(), + party.policyReference(), + party.policyVersion(), + party.verificationEvidenceReference(), + party.verificationEvidenceVersion(), + party.sourceVersion(), + source, + CreatorPartyEncoding.digest(source)); + } + + static HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary testBoundary(String name) { + byte[] source = bytes("test-only-environment-observation/" + name); + return new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + name, + "test-only-environment-owner", + "test-only-observation/" + name, + source, + HostedTermsEncoding.digest(source)); + } + + private static T externalFixture(Map values, UUID request) { + requireOutsideTransaction(); + return Objects.requireNonNull( + values.get(request), "Exact test-only external evidence required"); + } + + private static void requireOutsideTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "External fixture observation must precede Account owner locks"); + } + } + + static PeerScope withPeer(String uri) { + var attached = + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(uri).orElseThrow()); + return new PeerScope(attached.attach(), attached); + } + + record PeerScope(Context previous, Context attached) implements AutoCloseable { + @Override + public void close() { + attached.detach(previous); + } + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static String hash(String value) { + char[] secret = value.toCharArray(); + var argon = Argon2Factory.create(); + try { + return argon.hash(2, 4096, 1, secret); + } finally { + argon.wipeArray(secret); + } + } + + private static Path accountMigrations() { + Path current = Path.of("").toAbsolutePath(); + while (current != null) { + Path migrations = current.resolve("services/account-service/src/main/resources/db/migration"); + if (java.nio.file.Files.isDirectory(migrations)) return migrations; + current = current.getParent(); + } + throw new IllegalStateException("Exact Account migration directory is required"); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java new file mode 100644 index 0000000000..d296be3853 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java @@ -0,0 +1,832 @@ +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.mockStatic; +import static org.mockito.Mockito.when; + +import io.grpc.stub.StreamObserver; +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.Instant; +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.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import net.firedevops.firemud.account.v1.EnrollBootstrapRequest; +import net.firedevops.firemud.account.v1.EnrollBootstrapResponse; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest; +import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse; +import net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest; +import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse; +import net.firedevops.firemud.account.v1.RecordSecretObservationRequest; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtSignerMaterializationService; +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.impl.DSL; +import org.springframework.beans.factory.support.StaticListableBeanFactory; +import tools.jackson.databind.json.JsonMapper; + +/** + * Actual signer/readiness owner lifecycle; trust, platform inventory and Pod acceptance are + * stipulated test inputs. + */ +final class AccountControlUiSignerFixture { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK); + 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 TRUST_REVISION = "trust-r1"; + private static final String MATERIALIZER_URI = + "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + private static final List MATERIALIZER_PINS = List.of("c".repeat(64)); + private static final String TRUST_DIGEST = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + TRUST_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + MATERIALIZER_PINS); + private static final String API_DIGEST = "b".repeat(64), API_REVISION = "api-r1"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + final AccountControlUiOwnerSourcesFixture f; + final AccountJwtSignerDesiredStateRepository desired; + final AccountJwtJwksPublicationRepository publication; + final AccountJwtReadinessProbeRepository readiness; + final AccountJwtSignerMaterializerTrustBinding trust = + mock(AccountJwtSignerMaterializerTrustBinding.class); + final AccountJwtJwksApiBinding api = mock(AccountJwtJwksApiBinding.class); + final AccountJwtJwksConfigMapClient client = mock(AccountJwtJwksConfigMapClient.class); + final AccountJwtValidatorInventorySource inventory = + mock(AccountJwtValidatorInventorySource.class); + final AtomicReference configMap = + new AtomicReference<>( + new AccountJwtJwksConfigMapClient.ConfigMapSnapshot( + CONFIG_MAP_UID, "41", Map.of("jwks.json", "{\"keys\":[]}"))); + final Path privateRoot, publicRoot; + final AccountJwtSignerBootstrapCoordinator coordinator; + final AccountJwtSignerMaterializationService materializer; + final AccountControlUiSignerOwner signer; + + AccountControlUiSignerFixture(AccountControlUiOwnerSourcesFixture fixture, Path root) + throws Exception { + f = fixture; + privateRoot = Files.createDirectories(root.resolve("private")); + publicRoot = Files.createDirectories(root.resolve("public")); + desired = new AccountJwtSignerDesiredStateRepository(f.dsl); + publication = new AccountJwtJwksPublicationRepository(f.dsl, desired); + readiness = new AccountJwtReadinessProbeRepository(f.dsl, desired, publication); + when(trust.current()).thenReturn(Optional.of(materializerBinding())); + when(api.current()) + .thenReturn( + new AccountJwtJwksApiBinding.ParsedBinding( + API_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + URI.create("https://kubernetes.default.svc:6443/"), + "kubernetes.default.svc", + root.resolve("test-only-ca"), + "d".repeat(64), + root.resolve("test-only-bearer"), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:firemud-prod:account-service", + API_DIGEST)); + when(client.identity()) + .thenReturn( + new AccountJwtJwksConfigMapClient.BindingIdentity( + API_DIGEST, + API_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + "https://kubernetes.default.svc:6443/", + "kubernetes.default.svc", + "d".repeat(64), + "system:serviceaccount:firemud-prod:account-service")); + when(client.observe()).thenAnswer(ignored -> configMap.get()); + when(client.publish(any(), any())) + .thenAnswer(call -> publish(call.getArgument(0), call.getArgument(1))); + when(client.publishActiveProjection(any(), any(), any())) + .thenAnswer(call -> publish(call.getArgument(0), call.getArgument(2))); + when(inventory.observe(any(ObservationContext.class))) + .thenAnswer(call -> completeInventorySnapshot(now(), call.getArgument(0))); + var mounted = + new AccountJwtJwksPrepublicationService.MountedProjection( + privateRoot, + Path.of("pending.key"), + publicRoot, + Path.of("jwks.json"), + Path.of("jwt-generation.json")); + var prepublication = + new AccountJwtJwksPrepublicationService( + desired, publication, trust, client, f.manager, mounted); + var beans = new StaticListableBeanFactory(); + beans.addBean("testOnlyInventoryInput", inventory); + coordinator = + new AccountJwtSignerBootstrapCoordinator( + trust, + client, + desired, + prepublication, + readiness, + beans.getBeanProvider(AccountJwtValidatorInventorySource.class), + f.transactions); + beans.addBean("actualAccountCoordinator", coordinator); + materializer = + new AccountJwtSignerMaterializationService( + desired, + readiness, + trust, + f.manager, + beans.getBeanProvider(AccountJwtSignerBootstrapCoordinator.class), + beans.getBeanProvider(AccountJwtValidatorInventorySource.class)); + signer = new AccountControlUiSignerOwner(desired, trust, api, privateRoot, publicRoot); + } + + AccountJwtJwksConfigMapClient.CasObservation publish( + AccountJwtJwksConfigMapClient.ConfigMapSnapshot expected, Map data) + throws Exception { + assertThat(configMap.get()).isEqualTo(expected); + var next = + new AccountJwtJwksConfigMapClient.ConfigMapSnapshot( + CONFIG_MAP_UID, Long.toString(Long.parseLong(expected.resourceVersion()) + 1), data); + configMap.set(next); + for (var entry : data.entrySet()) + Files.writeString(publicRoot.resolve(entry.getKey()), entry.getValue()); + return new AccountJwtJwksConfigMapClient.CasObservation( + CONFIG_MAP_UID, + expected.resourceVersion(), + next.resourceVersion(), + data, + data, + AccountJwtJwksConfigMapClient.Outcome.APPLIED); + } + + /** + * Establishes the real receipt-backed first public key without committing a current signer. Only + * this fixture's isolated upstream materializer identity and ConfigMap transport are stipulated; + * Account's enrollment, generation, publication, and readback owners remain real. + */ + void prepareInitialPrepublication() throws Exception { + prepareInitialGeneration(); + assertThatThrownBy( + () -> + f.tx( + () -> + desired.readCurrentCommittedSigner( + BINDING, trust(), API_DIGEST, API_REVISION))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) + .hasMessage("Account durable and published active signer fences disagree"); + } + + private PreparedGeneration prepareInitialGeneration() throws Exception { + // Only the protected upstream identity is stipulated; every owner method/transaction is real. + try (var authenticated = mockStatic(AccountJwtSignerMaterializerTlsInterceptor.class)) { + authenticated + .when(AccountJwtSignerMaterializerTlsInterceptor::authenticatedBinding) + .thenReturn(materializerBinding()); + AccountControlUiSignerFixture.rpc( + out -> + materializer.enrollBootstrap( + EnrollBootstrapRequest.newBuilder().setSchemaVersion(1).build(), out)); + GetCurrentGenerationRequestResponse initial = + rpc( + out -> + materializer.getCurrentGenerationRequest( + GetCurrentGenerationRequestRequest.newBuilder().setSchemaVersion(1).build(), + out)); + var request = f.tx(() -> desired.readCurrentGenerationRequest(BINDING, trust())); + GetCurrentGenerationRequestResponse observed = + rpc( + out -> + materializer.recordSecretObservation( + RecordSecretObservationRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(initial.getOperationId()) + .setOperationDigest(initial.getOperationDigest()) + .setSecretUid(SECRET_UID) + .setObservedResourceVersion("12") + .build(), + out)); + var pair = generateRsa3072(); + var publicKey = publicJwk(request.targetKid(), (RSAPublicKey) pair.getPublic()); + RecordGenerationResultResponse recorded = + rpc( + out -> + materializer.recordGenerationResult( + RecordGenerationResultRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(initial.getOperationId()) + .setGenerationRequestDigest(observed.getGenerationRequestDigest()) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion("12") + .setObservedResourceVersion("13") + .setPublicJwkJson(publicKey.json()) + .build(), + out)); + var result = f.tx(() -> desired.readCurrentGenerationResult(BINDING, trust())); + assertThat(recorded.getOperationId()).isEqualTo(result.operationId().toString()); + assertThat(recorded.getOperationDigest()).isEqualTo(result.operationDigest()); + assertThat(recorded.getGenerationRequestDigest()).isEqualTo(result.generationRequestDigest()); + assertThat(recorded.getGenerationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(recorded.getObservedResourceVersion()).isEqualTo(result.observedResourceVersion()); + assertThat(recorded.getPublicKeyFingerprint()).isEqualTo(result.publicKeyFingerprint()); + Files.writeString( + privateRoot.resolve("pending.key"), privateBundleJson(request, result, pair)); + assertThat( + coordinator + .reconcileCurrentGenerationOnce(result.operationId()) + .publicKeyPrepublished()) + .isTrue(); + return new PreparedGeneration(request, result, pair); + } + } + + void commit() throws Exception { + var initialGeneration = prepareInitialGeneration(); + var request = initialGeneration.request(); + var result = initialGeneration.result(); + var pair = initialGeneration.pair(); + try (var authenticated = mockStatic(AccountJwtSignerMaterializerTlsInterceptor.class)) { + authenticated + .when(AccountJwtSignerMaterializerTlsInterceptor::authenticatedBinding) + .thenReturn(materializerBinding()); + var context = f.tx(() -> readiness.readCurrentInventoryObservationContext(BINDING, trust())); + var plannedAt = now().minusSeconds(300); + var planned = completeInventorySnapshot(plannedAt, context); + var plan = f.tx(() -> readiness.planCurrent(BINDING, trust(), plannedAt, planned)); + var harnessUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"; + var harnessPin = "e".repeat(64); + long validUntil = now().plusSeconds(3600).getEpochSecond(); + String readinessDigest = + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding + .computeBindingDigest( + "test-readiness-r1", + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harnessUri, + List.of(harnessPin), + "test-only-validator", + validUntil); + var harness = + new net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harnessUri, + List.of(harnessPin), + "test-readiness-r1", + "account-service", + "test-only-validator", + validUntil, + readinessDigest); + var peer = + new net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding + .PeerIdentity(harnessUri, harnessPin); + var claim = + f.tx(() -> readiness.claimSingleDelivery(BINDING, trust(), plan, harness, peer, now())); + var producer = + new AccountJwtReadinessProbeService( + readiness, + f.transactions, + Clock.systemUTC(), + privateRoot, + Path.of("pending.key"), + publicRoot, + Path.of("jwks.json")); + var delivered = + producer.issueCurrentPlan( + BINDING, + trust(), + result.operationId(), + claim, + (metadata, compact) -> { + assertThat(compact).isNotEmpty(); + var issued = + f + .tx(() -> readiness.readCurrentPlan(BINDING, trust(), result.operationId())) + .entries() + .stream() + .filter(entry -> entry.jti().equals(metadata.jti())) + .findFirst() + .orElseThrow(); + var current = completeInventorySnapshot(now(), context); + var pods = + f.tx( + () -> readiness.readCurrentExpectedPods(BINDING, trust(), issued, current)); + for (var pod : pods) { + var acceptance = testAuthenticatedAcceptance(issued, pod, now().getEpochSecond()); + f.tx( + () -> + readiness.recordPodAcceptance( + BINDING, trust(), issued, pod, acceptance, current)); + } + }); + assertThat(delivered) + .hasSize(8) + .allSatisfy( + entry -> + assertThat(entry.state()) + .isEqualTo(AccountJwtReadinessProbeRepository.ProbeState.VERIFIED)); + assertThat(f.dsl.fetchCount(DSL.table("account_jwt_readiness_pod_receipts"))).isEqualTo(12); + assertThat( + f.dsl.fetchCount( + DSL.table("account_jwt_readiness_pod_receipts"), + DSL.field("outcome").eq("INAPPLICABLE_REJECT"))) + .isEqualTo(2); + var prepared = coordinator.prepareCurrentPromotionOnce().orElseThrow(); + GetCurrentPromotionRequestResponse dispatched = + rpc( + out -> + materializer.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + out)); + var promotion = + f.tx(() -> desired.readPreparedGenerationForRecovery(BINDING, trust())).promotion(); + assertThat(prepared.operationId()).isEqualTo(promotion.operationId()); + assertThat(dispatched.getPromotionOperationId()) + .isEqualTo(promotion.operationId().toString()); + assertThat(dispatched.getPromotionRequestDigest()).isEqualTo(promotion.requestDigest()); + assertThat(dispatched.getGenerationOperationId()).isEqualTo(result.operationId().toString()); + assertThat(dispatched.getGenerationOperationDigest()).isEqualTo(result.operationDigest()); + assertThat(dispatched.getGenerationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(dispatched.getExpectedSecretUid()).isEqualTo(promotion.secretUid()); + assertThat(dispatched.getExpectedSecretResourceVersion()) + .isEqualTo(promotion.expectedPrivateResourceVersion()); + Files.writeString( + privateRoot.resolve("current.key"), privateBundleJson(request, result, pair)); + RecordPrivatePromotionResultResponse committed = + rpc( + out -> + materializer.recordPrivatePromotionResult( + RecordPrivatePromotionResultRequest.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(promotion.operationId().toString()) + .setPromotionRequestDigest(promotion.requestDigest()) + .setGenerationOperationId(result.operationId().toString()) + .setGenerationOperationDigest(result.operationDigest()) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion( + promotion.expectedPrivateResourceVersion()) + .setObservedResourceVersion("14") + .setCurrent( + PromotionPublicKeyIdentity.newBuilder() + .setGeneration(result.targetGeneration()) + .setKid(result.targetKid()) + .setPublicKeyFingerprint(result.publicKeyFingerprint())) + .addResultingSlots("current") + .build(), + out)); + var durableCommit = + f.tx(() -> desired.readCurrentCommittedSigner(BINDING, trust(), API_DIGEST, API_REVISION)) + .orElseThrow(); + assertThat(committed.getPromotionOperationId()) + .isEqualTo(durableCommit.promotion().operationId().toString()); + assertThat(committed.getGenerationOperationId()) + .isEqualTo(durableCommit.generationResult().operationId().toString()); + assertThat(committed.getObservedResourceVersion()) + .isEqualTo(durableCommit.privateReceipt().observedResourceVersion()); + assertThat(committed.getPublicReceiptDigest()) + .isEqualTo(durableCommit.privateReceipt().receiptDigest()); + } + } + + private record PreparedGeneration( + GenerationRequest request, GenerationResult result, KeyPair pair) {} + + private static T rpc(Consumer> invocation) { + AtomicReference result = new AtomicReference<>(); + AtomicReference failure = new AtomicReference<>(); + AtomicBoolean completed = new AtomicBoolean(); + invocation.accept( + new StreamObserver<>() { + @Override + public void onNext(T value) { + result.set(value); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() { + completed.set(true); + } + }); + if (failure.get() != null) + throw new AssertionError("Actual Account materialization RPC failed", failure.get()); + if (!completed.get()) { + throw new AssertionError("Actual Account materialization RPC did not complete"); + } + return java.util.Objects.requireNonNull(result.get()); + } + + private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + + private static Instant now() { + return Instant.ofEpochSecond(Instant.now().getEpochSecond()); + } + + private static TrustFence trust() { + return new TrustFence(CLUSTER_UID, NAMESPACE_UID, TRUST_DIGEST, TRUST_REVISION); + } + + private static AccountJwtSignerMaterializerTrustBinding.Binding materializerBinding() { + return new AccountJwtSignerMaterializerTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + MATERIALIZER_URI, + MATERIALIZER_PINS, + TRUST_REVISION, + TRUST_DIGEST); + } + + 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()); + return JSON.writeValueAsString(bundle); + } + + 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 ex) { + throw new IllegalStateException("SHA-256 is required for the persistence fixture", ex); + } + } + + /** Stipulated platform input only; Account's real owners derive all private proof from it. */ + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, ObservationContext observationContext) { + return completeInventorySnapshot(observedAt, "10.11.0.11", observationContext); + } + + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, String firstAccountPodIp, ObservationContext observationContext) { + return completeInventorySnapshot( + observedAt, firstAccountPodIp, observationContext, "77777777-7777-4777-8777-777777777777"); + } + + private static InventorySnapshot completeInventorySnapshot( + Instant observedAt, + String firstAccountPodIp, + ObservationContext observationContext, + String firstAccountPodUid) { + 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", + firstAccountPodUid, + "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", CLUSTER_UID); + preimage.put("namespace", BINDING.namespace()); + preimage.put("namespaceUid", NAMESPACE_UID); + preimage.put("apiBindingRevision", API_REVISION); + preimage.put("apiBindingDigest", API_DIGEST); + preimage.put("inventoryBindingRevision", "inventory-r1"); + preimage.put("inventoryBindingDigest", "c".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(CLUSTER_UID); + when(snapshot.namespace()).thenReturn(BINDING.namespace()); + when(snapshot.namespaceUid()).thenReturn(NAMESPACE_UID); + when(snapshot.apiBindingRevision()).thenReturn(API_REVISION); + when(snapshot.apiBindingDigest()).thenReturn(API_DIGEST); + when(snapshot.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(snapshot.inventoryBindingDigest()).thenReturn("c".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 static 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 static 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; + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond) { + return testAuthenticatedAcceptance( + entry, expectedPod, observedAtEpochSecond, entry.targetKid()); + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.ExpectedPod expectedPod, + long observedAtEpochSecond, + String verifiedKid) { + return testAuthenticatedAcceptance( + entry, + expectedPod, + observedAtEpochSecond, + verifiedKid, + expectedPod.target().exactPodEndpoint().orElseThrow().toString()); + } + + private static AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance + testAuthenticatedAcceptance( + ProbeEntry entry, + AccountJwtReadinessProbeRepository.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); + } +} diff --git a/services/common-redis-contracts/build.gradle.kts b/services/common-redis-contracts/build.gradle.kts new file mode 100644 index 0000000000..c7ebd3ff10 --- /dev/null +++ b/services/common-redis-contracts/build.gradle.kts @@ -0,0 +1,7 @@ +plugins { + `java-library` +} + +dependencies { + testImplementation(libs.spring.boot.starter.test) +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalog.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalog.java new file mode 100644 index 0000000000..18c3d7af35 --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalog.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.ServiceLoader; + +/** + * Immutable aggregation of the owner contributions installed in this class loader. + * + *

This is a shared schema/aggregation surface, not proof that every repository owner or script + * has contributed to a complete repository-wide catalog. + */ +public final class RedisScriptCatalog { + public static final int MAX_CONTRIBUTIONS = 128; + public static final int MAX_DESCRIPTORS = 1024; + + private final Map descriptorsById; + + private RedisScriptCatalog(Collection contributions) { + Objects.requireNonNull(contributions, "Redis script contributions are required"); + if (contributions.size() > MAX_CONTRIBUTIONS) { + throw new IllegalArgumentException("Redis script contribution count exceeds its bound"); + } + Map collected = new LinkedHashMap<>(); + int count = 0; + for (RedisScriptContribution contribution : contributions) { + Objects.requireNonNull(contribution, "Redis script contribution is required"); + String ownerId = + Objects.requireNonNull(contribution.ownerId(), "Contribution owner is required"); + Collection descriptors = + Objects.requireNonNull( + contribution.descriptors(), "Contribution descriptors are required"); + if (descriptors.isEmpty()) { + throw new IllegalArgumentException("Redis script contribution cannot be empty"); + } + for (RedisScriptDescriptor descriptor : descriptors) { + Objects.requireNonNull(descriptor, "Redis script descriptor is required"); + if (!ownerId.equals(descriptor.owner())) { + throw new IllegalArgumentException( + "Redis script descriptor owner does not match contribution"); + } + if (++count > MAX_DESCRIPTORS) { + throw new IllegalArgumentException("Redis script descriptor count exceeds its bound"); + } + if (collected.putIfAbsent(descriptor.scriptId(), descriptor) != null) { + throw new IllegalArgumentException("Duplicate Redis script descriptor identity"); + } + } + } + this.descriptorsById = Map.copyOf(collected); + } + + /** Aggregates service-provider contributions installed in the supplied class loader. */ + public static RedisScriptCatalog loadInstalled(ClassLoader classLoader) { + Objects.requireNonNull(classLoader, "Class loader is required"); + return new RedisScriptCatalog( + ServiceLoader.load(RedisScriptContribution.class, classLoader).stream() + .limit(MAX_CONTRIBUTIONS + 1L) + .map(ServiceLoader.Provider::get) + .toList()); + } + + /** Bounded constructor surface for owner-local tests and explicitly assembled applications. */ + public static RedisScriptCatalog fromContributions( + Collection contributions) { + return new RedisScriptCatalog(contributions); + } + + public RedisScriptDescriptor require(String id) { + Objects.requireNonNull(id, "Redis script id is required"); + RedisScriptDescriptor descriptor = descriptorsById.get(id); + if (descriptor == null) throw new IllegalArgumentException("Redis script is not registered"); + return descriptor; + } + + public Collection descriptors() { + return descriptorsById.values(); + } +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptContribution.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptContribution.java new file mode 100644 index 0000000000..e63270cf29 --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptContribution.java @@ -0,0 +1,11 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.util.Collection; + +/** Service-provider entry point for owner-local Redis script descriptors. */ +public interface RedisScriptContribution { + /** Exact service owner identifier declared by every descriptor returned here. */ + String ownerId(); + + Collection descriptors(); +} diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java new file mode 100644 index 0000000000..f7203482ba --- /dev/null +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java @@ -0,0 +1,264 @@ +package net.firedevops.firemud.common.redis.contracts; + +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.regex.Pattern; + +/** Immutable declaration of one versioned, owner-executed Redis script contract. */ +public record RedisScriptDescriptor( + String scriptId, + String resourcePath, + String sha256, + String owner, + String principal, + RedisRole role, + List keys, + List arguments, + ScriptCategory category, + List outcomes, + ResetSensitivity resetSensitivity, + LossClass lossClass, + String tailLossBehavior, + CompatibilityLevel compatibilityLevel, + List supportedCoexistence, + String legacyPayloadShape) { + + public static final String NO_PAYLOAD_VERSION = "none"; + public static final String LEGACY_PAYLOAD_VERSION = "legacy"; + + private static final Pattern SCRIPT_ID_PATTERN = + Pattern.compile("[a-z][a-z0-9-]*(?:\\.[a-z][a-z0-9-]*)*\\.v[1-9][0-9]*"); + private static final Pattern RESOURCE_PATH_PATTERN = + Pattern.compile("redis/(?:[a-z0-9][a-z0-9_-]*/)*[a-z0-9][a-z0-9_-]*\\.lua"); + private static final Pattern OWNER_PATTERN = Pattern.compile("[a-z][a-z0-9-]*"); + private static final Pattern PRINCIPAL_PATTERN = Pattern.compile("[a-z][a-z0-9_]*"); + private static final Pattern PREFIX_PATTERN = + Pattern.compile("[a-z][a-z0-9_-]*(?::[a-z][a-z0-9_-]*)*:"); + private static final Pattern DECLARATION_NAME_PATTERN = Pattern.compile("[a-z][A-Za-z0-9]*"); + private static final Pattern OUTCOME_CODE_PATTERN = Pattern.compile("[A-Z][A-Z0-9_]*"); + private static final Pattern VERSION_PATTERN = Pattern.compile("v[1-9][0-9]*"); + + public RedisScriptDescriptor { + requireMatch(scriptId, SCRIPT_ID_PATTERN, "scriptId must be a supported versioned identifier"); + requireMatch( + resourcePath, + RESOURCE_PATH_PATTERN, + "resourcePath must be a relative redis/ classpath Lua resource path"); + requireMatch(sha256, Pattern.compile("[0-9a-f]{64}"), "sha256 must be 64 lowercase hex digits"); + requireMatch(owner, OWNER_PATTERN, "owner must be a lowercase service identifier"); + requireMatch(principal, PRINCIPAL_PATTERN, "principal must be a lowercase Redis principal"); + Objects.requireNonNull(role, "role is required"); + Objects.requireNonNull(category, "category is required"); + Objects.requireNonNull(resetSensitivity, "resetSensitivity is required"); + Objects.requireNonNull(lossClass, "lossClass is required"); + Objects.requireNonNull(compatibilityLevel, "compatibilityLevel is required"); + + keys = immutableNonEmpty(keys, "KEYS declarations are required"); + arguments = + immutable(arguments, "ARGV declarations are required, including an explicit empty list"); + outcomes = immutableNonEmpty(outcomes, "outcomes are required"); + supportedCoexistence = + immutableNonEmpty( + supportedCoexistence, "supported caller/payload coexistence metadata is required"); + tailLossBehavior = requireDescription(tailLossBehavior, "tailLossBehavior"); + legacyPayloadShape = optionalDescription(legacyPayloadShape, "legacyPayloadShape"); + + Set keyNames = new HashSet<>(); + for (KeySpec key : keys) { + if (!keyNames.add(key.name())) { + throw new IllegalArgumentException("duplicate KEYS declaration name: " + key.name()); + } + } + + Set argumentNames = new HashSet<>(); + for (ArgumentSpec argument : arguments) { + if (!argumentNames.add(argument.name())) { + throw new IllegalArgumentException("duplicate ARGV declaration name: " + argument.name()); + } + } + + Set outcomeCodes = new HashSet<>(); + for (OutcomeSpec outcome : outcomes) { + if (!outcomeCodes.add(outcome.code())) { + throw new IllegalArgumentException("duplicate outcome code: " + outcome.code()); + } + } + + Set combinations = new HashSet<>(); + boolean supportsLegacyPayload = false; + for (SupportedCoexistence combination : supportedCoexistence) { + if (!combinations.add(combination)) { + throw new IllegalArgumentException("duplicate caller/payload coexistence declaration"); + } + supportsLegacyPayload |= combination.payloadVersion().equals(LEGACY_PAYLOAD_VERSION); + } + if (supportsLegacyPayload && legacyPayloadShape == null) { + throw new IllegalArgumentException( + "legacyPayloadShape is required when a versionless payload is supported"); + } + if (!supportsLegacyPayload && legacyPayloadShape != null) { + throw new IllegalArgumentException( + "legacyPayloadShape is only valid when a legacy payload is supported"); + } + + if (keys.size() > 1 + && keys.stream().anyMatch(key -> key.hashTagDeclaration() != HashTagDeclaration.REQUIRED)) { + throw new IllegalArgumentException( + "every KEYS declaration in a multi-key script must require a hash tag"); + } + } + + public List keys() { + return List.copyOf(keys); + } + + public List arguments() { + return List.copyOf(arguments); + } + + public List outcomes() { + return List.copyOf(outcomes); + } + + public List supportedCoexistence() { + return List.copyOf(supportedCoexistence); + } + + public enum RedisRole { + COORDINATION, + CACHE_RATE_LIMIT + } + + public enum HashTagDeclaration { + NOT_REQUIRED, + REQUIRED + } + + public enum ScriptCategory { + TICK_LOCK, + TIMER_QUEUE, + SESSION_CAS, + SESSION_TO_REGION_BRIDGE, + MAINTENANCE, + CACHE, + RATE_LIMIT + } + + public enum OutcomeCategory { + SUCCESS, + REPLAY, + STALE, + VALIDATION_FAILURE, + CONTENTION, + DEFERRAL + } + + public enum MutationEffect { + MUTATING, + NON_MUTATING + } + + public enum ResetSensitivity { + NONE, + SESSION, + REGION, + TENANT, + CLUSTER + } + + /** Work classes from ADR 0058. */ + public enum LossClass { + ACCEPTED_PLAYER_COMMAND, + STAGED_EFFECT_OR_RETRY, + CORRECTNESS_BEARING_TIMER, + LOSSY_TIMER_OR_ADVISORY_HINT, + SESSION_LEASE_CACHE_OR_WAKE_UP, + PREMIUM_FINANCIAL_CROSS_TENANT_OR_UNIQUE_EXTERNAL_EFFECT, + EMPTY_REDIS_COLD_START_OR_RESET + } + + public enum CompatibilityLevel { + COMPATIBLE, + REQUIRES_REGION_RESET, + REQUIRES_TENANT_RESET, + REQUIRES_CLUSTER_RESET + } + + public record KeySpec(String name, String ownedPrefix, HashTagDeclaration hashTagDeclaration) { + public KeySpec { + requireMatch(name, DECLARATION_NAME_PATTERN, "KEYS name must be a supported identifier"); + requireMatch(ownedPrefix, PREFIX_PATTERN, "ownedPrefix must be a colon-delimited key prefix"); + Objects.requireNonNull(hashTagDeclaration, "hashTagDeclaration is required"); + } + } + + public record ArgumentSpec(String name) { + public ArgumentSpec { + requireMatch(name, DECLARATION_NAME_PATTERN, "ARGV name must be a supported identifier"); + } + } + + public record OutcomeSpec(String code, OutcomeCategory category, MutationEffect effect) { + public OutcomeSpec { + requireMatch(code, OUTCOME_CODE_PATTERN, "outcome code must be uppercase and stable"); + Objects.requireNonNull(category, "outcome category is required"); + Objects.requireNonNull(effect, "outcome mutation effect is required"); + if (category != OutcomeCategory.SUCCESS && effect != MutationEffect.NON_MUTATING) { + throw new IllegalArgumentException( + "replay, stale, validation, contention, and deferral outcomes must be non-mutating"); + } + } + } + + /** A caller version and payload version that may coexist for this script version. */ + public record SupportedCoexistence(String callerVersion, String payloadVersion) { + public SupportedCoexistence { + requireMatch(callerVersion, VERSION_PATTERN, "callerVersion must use vN syntax"); + if (!NO_PAYLOAD_VERSION.equals(payloadVersion) + && !LEGACY_PAYLOAD_VERSION.equals(payloadVersion)) { + requireMatch( + payloadVersion, VERSION_PATTERN, "payloadVersion must use vN, none, or legacy"); + } + } + } + + private static void requireMatch(String value, Pattern pattern, String message) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException(message); + } + } + + private static String requireDescription(String value, String fieldName) { + if (value == null || value.isBlank() || !value.equals(value.trim())) { + throw new IllegalArgumentException(fieldName + " is required and must be trimmed"); + } + return value; + } + + private static String optionalDescription(String value, String fieldName) { + if (value == null || value.isBlank()) { + return null; + } + if (!value.equals(value.trim())) { + throw new IllegalArgumentException(fieldName + " must be trimmed"); + } + return value; + } + + private static List immutable(List values, String message) { + if (values == null) { + throw new IllegalArgumentException(message); + } + return List.copyOf(values); + } + + private static List immutableNonEmpty(List values, String message) { + List copy = immutable(values, message); + if (copy.isEmpty()) { + throw new IllegalArgumentException(message); + } + return copy; + } +} diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java new file mode 100644 index 0000000000..d6d99d6f36 --- /dev/null +++ b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java @@ -0,0 +1,192 @@ +package net.firedevops.firemud.common.redis.contracts; + +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.mockStatic; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.ServiceLoader; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +class RedisScriptCatalogTest { + private static final AtomicInteger INSTALLED_PROVIDER_GET_CALLS = new AtomicInteger(); + + @Test + void aggregatesContributionsAndRequiresExactScriptIdentity() { + RedisScriptDescriptor account = descriptor("account.control-ui.v1", "account-service"); + RedisScriptDescriptor session = descriptor("session.tick-lock.v1", "game-session-service"); + RedisScriptCatalog catalog = + RedisScriptCatalog.fromContributions( + List.of( + contribution("account-service", List.of(account)), + contribution("game-session-service", List.of(session)))); + + assertThat(catalog.require("account.control-ui.v1")).isSameAs(account); + assertThat(catalog.descriptors()).containsExactlyInAnyOrder(account, session); + assertThatThrownBy(() -> catalog.require("account.control-ui.v2")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not registered"); + } + + @Test + void rejectsDuplicateScriptIdentityAndContributionOwnerMismatch() { + RedisScriptDescriptor first = descriptor("account.control-ui.v1", "account-service"); + RedisScriptDescriptor duplicate = descriptor("account.control-ui.v1", "account-service"); + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of( + contribution("account-service", List.of(first)), + contribution("account-service", List.of(duplicate))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Duplicate Redis script descriptor identity"); + + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of(contribution("game-session-service", List.of(first))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("owner does not match contribution"); + } + + @Test + void rejectsNullAndEmptyContributionsAndNullDescriptors() { + assertThatThrownBy(() -> RedisScriptCatalog.fromContributions(null)) + .isInstanceOf(NullPointerException.class); + assertThat(RedisScriptCatalog.fromContributions(List.of()).descriptors()).isEmpty(); + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions(Arrays.asList((RedisScriptContribution) null))) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of(contribution("account-service", List.of())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot be empty"); + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of( + contribution( + "account-service", Arrays.asList((RedisScriptDescriptor) null))))) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of(contribution("account-service", null)))) + .isInstanceOf(NullPointerException.class); + } + + @Test + void rejectsContributionAndDescriptorCountOverflow() { + List tooManyContributions = new ArrayList<>(); + for (int index = 0; index <= RedisScriptCatalog.MAX_CONTRIBUTIONS; index++) { + tooManyContributions.add( + contribution( + "account-service", + List.of(descriptor("account.script-" + index + ".v1", "account-service")))); + } + assertThatThrownBy(() -> RedisScriptCatalog.fromContributions(tooManyContributions)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("contribution count exceeds its bound"); + + List tooManyDescriptors = new ArrayList<>(); + for (int index = 0; index <= RedisScriptCatalog.MAX_DESCRIPTORS; index++) { + tooManyDescriptors.add(descriptor("account.script-" + index + ".v1", "account-service")); + } + assertThatThrownBy( + () -> + RedisScriptCatalog.fromContributions( + List.of(contribution("account-service", tooManyDescriptors)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("descriptor count exceeds its bound"); + } + + @Test + void limitsInstalledProviderRealizationBeforeRejectingContributionOverflow() { + INSTALLED_PROVIDER_GET_CALLS.set(0); + ServiceLoader installed = mock(ServiceLoader.class); + ClassLoader classLoader = getClass().getClassLoader(); + Stream> providers = + IntStream.range(0, RedisScriptCatalog.MAX_CONTRIBUTIONS + 20) + .mapToObj( + ignored -> + new ServiceLoader.Provider<>() { + @Override + public Class type() { + return RedisScriptContribution.class; + } + + @Override + public RedisScriptContribution get() { + INSTALLED_PROVIDER_GET_CALLS.incrementAndGet(); + return null; + } + }); + when(installed.stream()).thenReturn(providers); + + try (MockedStatic serviceLoader = mockStatic(ServiceLoader.class)) { + serviceLoader + .when(() -> ServiceLoader.load(RedisScriptContribution.class, classLoader)) + .thenReturn(installed); + + assertThatThrownBy(() -> RedisScriptCatalog.loadInstalled(classLoader)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("contribution count exceeds its bound"); + } + assertThat(INSTALLED_PROVIDER_GET_CALLS).hasValue(RedisScriptCatalog.MAX_CONTRIBUTIONS + 1); + } + + private static RedisScriptContribution contribution( + String owner, Collection descriptors) { + return new RedisScriptContribution() { + @Override + public String ownerId() { + return owner; + } + + @Override + public Collection descriptors() { + return descriptors == null ? null : new ArrayList<>(descriptors); + } + }; + } + + private static RedisScriptDescriptor descriptor(String scriptId, String owner) { + return new RedisScriptDescriptor( + scriptId, + "redis/" + owner + "/script.lua", + "a".repeat(64), + owner, + "account_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + List.of( + new RedisScriptDescriptor.KeySpec( + "record", + "session:control:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + List.of(new RedisScriptDescriptor.ArgumentSpec("requestId")), + RedisScriptDescriptor.ScriptCategory.SESSION_CAS, + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "OK", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING)), + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, + "A lost projection denies the operation until owner recovery.", + RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET, + List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1")), + null); + } +} diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java new file mode 100644 index 0000000000..0ea5d49b6c --- /dev/null +++ b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java @@ -0,0 +1,225 @@ +package net.firedevops.firemud.common.redis.contracts; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import org.junit.jupiter.api.Test; + +class RedisScriptDescriptorTest { + @Test + void acceptsValidDescriptorAndReturnsImmutableDeclarationCopies() { + RedisScriptDescriptor descriptor = descriptor(); + + assertThat(descriptor.scriptId()).isEqualTo("account.control-ui.v1"); + assertThat(descriptor.resourcePath()).isEqualTo("redis/account/control-ui.lua"); + assertThat(descriptor.keys()) + .containsExactly( + new RedisScriptDescriptor.KeySpec( + "record", + "session:control:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)); + assertThat(descriptor.arguments()) + .containsExactly(new RedisScriptDescriptor.ArgumentSpec("requestId")); + assertThat(descriptor.outcomes()).hasSize(2); + assertThat(descriptor.supportedCoexistence()) + .containsExactly(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1")); + } + + @Test + void rejectsMalformedResourceAndDigest() { + assertThatThrownBy(() -> descriptor("account/control-ui.lua", "a".repeat(64), null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("resourcePath"); + assertThatThrownBy( + () -> descriptor("redis/account/control-ui.lua", "A".repeat(64), null, null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("sha256"); + } + + @Test + void rejectsMalformedAndDuplicateKeyIdentities() { + assertThatThrownBy( + () -> + descriptor( + null, + null, + List.of( + new RedisScriptDescriptor.KeySpec( + "1record", + "session:control:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("KEYS name"); + assertThatThrownBy( + () -> + descriptor( + null, + null, + List.of( + new RedisScriptDescriptor.KeySpec( + "record", + "session/control", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + null, + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ownedPrefix"); + var key = + new RedisScriptDescriptor.KeySpec( + "record", "session:control:", RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED); + assertThatThrownBy(() -> descriptor(null, null, List.of(key, key), null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate KEYS"); + + var requiredKey = + new RedisScriptDescriptor.KeySpec( + "other", "session:other:", RedisScriptDescriptor.HashTagDeclaration.REQUIRED); + assertThatThrownBy(() -> descriptorWithCoexistence(null, null, List.of(key, requiredKey))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("multi-key script must require a hash tag"); + } + + @Test + void rejectsMalformedAndDuplicateArgumentAndOutcomeIdentities() { + assertThatThrownBy( + () -> + descriptor( + null, + null, + null, + List.of(new RedisScriptDescriptor.ArgumentSpec("request-id")), + null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("ARGV name"); + var argument = new RedisScriptDescriptor.ArgumentSpec("requestId"); + assertThatThrownBy(() -> descriptor(null, null, null, List.of(argument, argument), null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate ARGV"); + + assertThatThrownBy( + () -> + descriptor( + null, + null, + null, + null, + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "created", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("outcome code"); + var outcome = + new RedisScriptDescriptor.OutcomeSpec( + "OK", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING); + assertThatThrownBy(() -> descriptor(null, null, null, null, List.of(outcome, outcome))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate outcome"); + + assertThatThrownBy( + () -> + new RedisScriptDescriptor.OutcomeSpec( + "CONFLICT", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.MUTATING)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be non-mutating"); + } + + @Test + void rejectsInconsistentLegacyPayloadMetadataAndDuplicateCoexistence() { + var legacy = new RedisScriptDescriptor.SupportedCoexistence("v1", "legacy"); + var versioned = new RedisScriptDescriptor.SupportedCoexistence("v1", "v1"); + + assertThatThrownBy(() -> descriptorWithCoexistence(List.of(legacy), null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("legacyPayloadShape is required"); + assertThatThrownBy(() -> descriptorWithCoexistence(List.of(versioned), "old fields", null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("only valid when a legacy payload is supported"); + assertThatThrownBy(() -> descriptorWithCoexistence(List.of(versioned, versioned), null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("duplicate caller/payload coexistence"); + } + + private static RedisScriptDescriptor descriptor() { + return descriptor(null, null, null, null, null); + } + + private static RedisScriptDescriptor descriptor( + String resourcePath, + String sha256, + List keys, + List arguments, + List outcomes) { + return descriptorWithCoexistence( + List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1")), + null, + keys, + resourcePath, + sha256, + arguments, + outcomes); + } + + private static RedisScriptDescriptor descriptorWithCoexistence( + List supportedCoexistence, + String legacyPayloadShape, + List keys) { + return descriptorWithCoexistence( + supportedCoexistence, legacyPayloadShape, keys, null, null, null, null); + } + + private static RedisScriptDescriptor descriptorWithCoexistence( + List supportedCoexistence, + String legacyPayloadShape, + List keys, + String resourcePath, + String sha256, + List arguments, + List outcomes) { + return new RedisScriptDescriptor( + "account.control-ui.v1", + resourcePath == null ? "redis/account/control-ui.lua" : resourcePath, + sha256 == null ? "a".repeat(64) : sha256, + "account-service", + "account_coord_app", + RedisScriptDescriptor.RedisRole.COORDINATION, + keys == null + ? List.of( + new RedisScriptDescriptor.KeySpec( + "record", + "session:control:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)) + : keys, + arguments == null + ? List.of(new RedisScriptDescriptor.ArgumentSpec("requestId")) + : arguments, + RedisScriptDescriptor.ScriptCategory.SESSION_CAS, + outcomes == null + ? List.of( + new RedisScriptDescriptor.OutcomeSpec( + "OK", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + new RedisScriptDescriptor.OutcomeSpec( + "CONFLICT", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)) + : outcomes, + RedisScriptDescriptor.ResetSensitivity.CLUSTER, + RedisScriptDescriptor.LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP, + "A lost projection denies the operation until owner recovery.", + RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET, + supportedCoexistence == null + ? List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "v1")) + : supportedCoexistence, + legacyPayloadShape); + } +} diff --git a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java index 694dd1e2a5..ed0eca9cac 100644 --- a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java +++ b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/GatewayGameplayBridgeIntegrationTest.java @@ -30,7 +30,6 @@ import org.springframework.context.annotation.Primary; import org.springframework.http.client.ReactorResourceFactory; import org.springframework.http.codec.ServerCodecConfigurer; -import org.springframework.test.util.TestSocketUtils; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import org.springframework.web.reactive.socket.WebSocketHandler; @@ -135,9 +134,8 @@ private static synchronized void ensureStarted() { } private static UpstreamHolder startUpstream() { - int port = TestSocketUtils.findAvailableTcpPort(); TEST_UPSTREAM_STATE.set(new UpstreamRuntimeState()); - return UpstreamHolder.start(port); + return UpstreamHolder.start(0); } private static GatewayHolder startGateway(String upstreamUrl) { @@ -195,7 +193,7 @@ static UpstreamHolder start(int port) { Map.entry("firemud.grpc.plaintext", "true"), Map.entry(GatewayTestProperties.DISABLE_GATEWAY_WARNING_AND_GRPC_SERVER, "")), UpstreamStubApplication.class); - return new UpstreamHolder(app.context(), port); + return new UpstreamHolder(app.context(), app.port()); } String websocketUrl() { diff --git a/settings.gradle.kts b/settings.gradle.kts index 4894fe1e4e..c8a0d7284e 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -10,6 +10,9 @@ project(":common-data-runtime").projectDir = File("services/common-data-runtime" include("common-platform-core") project(":common-platform-core").projectDir = File("services/common-platform-core") +include("common-redis-contracts") +project(":common-redis-contracts").projectDir = File("services/common-redis-contracts") + include("common-saga") project(":common-saga").projectDir = File("services/common-saga")