diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index b181153c1f..1572f637ab 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -12,6 +12,14 @@ Account V40 adds owner-proven sequence-zero source baselines to the inherited V3 Proof qualification: the earlier `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` run is historical. Later physical CI executed the inspection-lock, TRUNCATE and disclosure-source regressions successfully but failed a trigger-catalog fixture. That fixture and the final optional-inventory settlement and malformed source-vector corrections require replacement physical CI. See the [player-access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#current-status) for the canonical proof inventory and exact limits. These results do not establish activation or playable closure. +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 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. + +The source preparation also includes unregistered, caller-transaction-bound creator-source composition and a Control-UI authority/signing-input snapshot. These are owner-evidence preparations only; they do not provide a registered issuer, receiver approval, or activation. + Account's actor-staging eligibility owner read is a read-only, same-namespace Entity workload RPC gated off by default. Under one repeatable-read Account transaction it verifies persisted Account UUID/provenance, current Account membership and pair authority, fresh Game Design tenant-source evidence, and the current membership event/checkpoint, then returns digest-sealed evidence scoped to `PUBLIC_PRODUCTION_STAGING_ONLY`. It reports an eligible or ineligible source snapshot but creates no membership, actor assignment, JOIN, PLAY, or gameplay admission. The staged foundation passed 43 focused Account tests and 92 shared-evidence tests with no failures or skips, plus source generation and Account integration-source compilation. PostgreSQL migration/persistence proof sources are included but physical PostgreSQL and live runtime execution remain unrun; the RPC is not runtime-ready or admission authority. Account V29 persists immutable, unique, non-nil `account_uuid` values with provenance and the unchanged numeric source-row id. Registration REST/gRPC and the Account component of the current Account/profile-local and legacy tenant exports expose that persisted UUID through `AccountDto.id`; the mapper requires a non-nil UUID, provenance, and an exact positive source-row match. Repository insert/readback checks remain the persistence boundary, and new registration audit payloads use the same UUID. Profile and tenant DTO identifiers, authentication results, JWT subjects, and downstream consumers remain unchanged; the current export is still partial Account/profile-local data, not the canonical portable export. The Account-local UUID-to-row resolver also remains confined to Account. The closed consumer boundary is incomplete: shared `SessionContext.currentAccountIdOrNull()` still requires numeric claims and is used by `GrpcClientAuth`, Logging & Admin `SessionActorReaders`, Automation Scripting `ScriptEventIngressServiceImpl`, and Social & Groups current-account authorization; Game Session control-plane owner authorization also compares numeric owner IDs. These consumers are outside this Account-owned slice, so no UUID-authentication or downstream-consumer proof is claimed. Focused repository and retained-row migration integration cases are present, but local PostgreSQL execution is unavailable while Docker is disabled; [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md) remains the identifier authority. diff --git a/design/architecture/system-architecture-jwt-and-token-contracts.md b/design/architecture/system-architecture-jwt-and-token-contracts.md index add7da17bc..8f8d1428e5 100644 --- a/design/architecture/system-architecture-jwt-and-token-contracts.md +++ b/design/architecture/system-architecture-jwt-and-token-contracts.md @@ -6,6 +6,10 @@ This document defines the JWT profiles, claim requirements, issued-token registr This document defines target-state token and revocation behavior. Current implementation remains drifted: the runtime has no complete issued-token registry or Account-owned authority-generation issuance, advancement, propagation, and validation path; checked-in player-facing Kustomize delivery is legacy Secret-backed signing plus a public `jwt-jwks` Secret, while hosted preview Helm remains on its diagnostic public `jwt-jwks` ConfigMap path; validators still use shared-HMAC verification rather than Account JWKS; and the runtime still permits the documented classpath JWKS fallback when the configured file is absent. The first implemented authority-generation path must prove that issuance and refresh cannot cross a concurrent generation advance and that every affected route rejects stale generations; no such runtime proof is currently claimed. +Account now has a bounded passive storage/source-evidence preparation for desired signer state, JWKS publication/readback, readiness/promotion evidence, and validator inventory. These repositories, migrations, and focused proof sources do not register a runtime issuer, materializer, readiness path, promotion executor, or consumer gate, and do not establish current token issuance, stale-authority rejection, or playable admission. This implementation status does not change the canonical target contract below; Account-local consequences and proof limits are recorded in [Account Runtime and Data](./microservices/account-service/runtime-and-data.md#implementation-status). + +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. + 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/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 4dadf43ffb..ff0a3f7f97 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -8,6 +8,14 @@ This is a non-normative implementation tracker for player access and session. Ca Restricted original-claim evidence continuation remains inactive and preparation-only; its bounded preparation and proof limits are recorded under [restricted original-claim continuation preparation](#restricted-original-claim-evidence-continuation-preparation). +### Account signer/currentness storage evidence preparation + +Account V99–V125 and the associated owner repositories, typed evidence carriers, mounted-bundle signer source, and validator-profile sources form a passive storage/evidence preparation only. The selected RPCs, coordinators, transport composition, provisioning, receiver execution, runtime registration, and consumer enforcement are not included or activated. The earlier local result of 727 Account and 154 Common Security cases is historical. The later local Account result is 738 cases with one skip; integration sources compiled, while local integration execution skipped 99 of 101 definitions without Docker. Exact-head hosted Account integration task 114264913703 passed on `607004fe786b2a9e1270a31c90f9031b486b3278` and is historical; its retained evidence does not expose per-suite case or skip counts. The later exact-head result at `7b79a8860baa6f08d3b4ae51d166f64ccf08004f` is also historical: hosted Account task 114304559873, Validation 38083268673, and artifact 11681094163 recorded physical PostgreSQL 18.6 readiness storage proof with 1 case, 70.952 seconds, and 0 skipped, including lawful expired-dispatch recovery. At `e63729562c39e664513bad2be2222e11a6886388`, the required Validation and Smoke checks passed. Hosted Account run 38088195334, task 114319172067, and artifact 11683606431 tested merge commit `05304721b3e705925b4344280a98a65c094f8823`, with parents `75e92718a983ac134cbb75fafbf173ac6b0360e0` and `e63729562c39e664513bad2be2222e11a6886388`, using immutable PostgreSQL 18.6 image `sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336`; the readiness and inventory suites each passed 2 of 2 cases with zero skips or failures. This is bounded storage proof with synthetic inventory/resource inputs, not evidence of live Kubernetes currentness, readiness activation, or signer activation. The AA-1.3 capability remains `partial` / `drift-found`; this subsection updates its passive anchors and proof limits without changing that state or closing a gate. Other capability rows and prior gates remain unchanged. Runtime readiness is not claimed. This preparation does not establish an issuer/currentness path or close `PLAY`, admission, or playable readiness; the canonical design remains [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). + +This preparation is owned by AA-1.3 in [Capability Status](#capability-status), whose state remains `partial` / `drift-found`. Its production anchors are [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), [V99](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql), and [V125](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql). Focused proof anchors are [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java) and [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java). The older exact-head readiness result on `7b79a8860baa6f08d3b4ae51d166f64ccf08004f` and the earlier signer-suite result are historical; the signer artifact has no per-suite count. The latest published proof is the hosted PostgreSQL 18.6 result detailed above: readiness 2/2 and inventory 2/2, zero skips or failures, with synthetic inventory/resource inputs. The subsequent snapshot/matrix closure correction and isolated expiry-recovery regression have passed local compilation and migration parsing, but their three PostgreSQL test definitions skipped without Docker; replacement exact-head physical execution remains pending. No runtime registration, live Kubernetes currentness, readiness activation, or signer activation is established. + +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. + ### 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). @@ -76,7 +84,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); [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); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [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) | [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) | [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. | +| `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.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/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts index 1a362013eb..8a4964119e 100644 --- a/services/account-service/build.gradle.kts +++ b/services/account-service/build.gradle.kts @@ -2,6 +2,7 @@ apply(from = "${rootDir}/gradle/proto-convention.gradle") plugins { + `java-test-fixtures` id("net.firedevops.firemud.secured-stateful-service-conventions") id("net.firedevops.firemud.aop-conventions") id("net.firedevops.firemud.jooq-conventions") @@ -15,4 +16,7 @@ dependencies { implementation(libs.spring.boot.starter.mail) implementation(libs.argon2) implementation(libs.stripe.java) + testImplementation(testFixtures(project(":account-service"))) + testCompileOnly(libs.spotbugs.annotations) + add("integrationTestCompileOnly", libs.spotbugs.annotations) } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java new file mode 100644 index 0000000000..c70b7ac97d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java @@ -0,0 +1,378 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.IssuanceFence; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.databind.json.JsonMapper; + +/** Actual existing-source capture for one initial creator, in the caller's owner transaction. */ +public final class AccountControlUiAuthority { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private final AccountDraftSourceCompositionService sources; + + public AccountControlUiAuthority(AccountDraftSourceCompositionService sources) { + this.sources = Objects.requireNonNull(sources); + } + + public Snapshot capture(UUID actor, UUID tenant, CapturedEnvironmentBoundary environment) { + var existing = sources.readExistingSources(environment, tenant); + requireNoApplicableDeadline(existing); + return snapshot(actor, tenant, existing); + } + + /** Discovers only the existing initial creator; primary authentication must still match it. */ + public Snapshot captureInitial(UUID tenant, CapturedEnvironmentBoundary environment) { + var existing = sources.readExistingSources(environment, tenant); + requireNoApplicableDeadline(existing); + return snapshot(existing.membership().accountUuid(), tenant, existing); + } + + private static void requireNoApplicableDeadline( + AccountDraftSourceCompositionService.ExistingSources existing) { + // Only the locked typed owner readback proves absence; opaque source bytes are not a lease. + var terms = Objects.requireNonNull(Objects.requireNonNull(existing.hostedTerms()).terms()); + if (terms.validUntil() != null || terms.disclosedDeadline() != null) { + throw new IllegalStateException( + "Deadline-qualified hosted terms cannot authorize this minimum commit producer"); + } + } + + private Snapshot snapshot( + UUID actor, UUID tenant, AccountDraftSourceCompositionService.ExistingSources existing) { + var member = existing.membership(); + if (!actor.equals(member.accountUuid()) + || !tenant.equals(member.tenantUuid()) + || !member.roleSource().roles().equals(List.of("tenantAdmin")) + || !member.pairSource().membershipExists() + || member.pairSource().lastTransitionInvalidated()) { + throw new IllegalStateException("Current authenticated initial creator authority required"); + } + var tuple = member.authorityTuple(); + var selected = java.util.Set.of(tenant.toString()); + if (!tuple.tenantAuthorityGeneration().keySet().equals(selected) + || !tuple.membershipAuthorityGeneration().keySet().equals(selected) + || !member.membershipVersion().keySet().equals(selected) + || member.authoritySnapshot().tenants().size() != 1 + || member.authoritySnapshot().memberships().size() != 1) { + throw new IllegalStateException("Exact single selected creator tenant authority required"); + } + Map authority = new LinkedHashMap<>(); + authority.put("issuerAuthGeneration", Long.parseLong(tuple.issuerAuthGeneration())); + authority.put("accountAuthorityGeneration", Long.parseLong(tuple.accountAuthorityGeneration())); + authority.put("tenantAuthorityGeneration", numeric(tuple.tenantAuthorityGeneration())); + authority.put("membershipAuthorityGeneration", numeric(tuple.membershipAuthorityGeneration())); + if (!tuple.privateRealmGrantVersions().isEmpty()) { + throw new IllegalStateException("Creator control does not acquire gameplay grants"); + } + authority.put("privateRealmGrantVersions", List.of()); + tuple + .accountSecurityCutoff() + .ifPresent( + cutoff -> + authority.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + Long.parseLong(cutoff.accountAuthorityGeneration()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + Long.parseLong(cutoff.outboxSequence())))); + tuple + .tenantBillingCutoff() + .ifPresent( + cutoffs -> { + Map values = new LinkedHashMap<>(); + cutoffs.forEach( + (id, cutoff) -> + values.put( + id, + Map.of( + "tenantAuthorityGeneration", + Long.parseLong(cutoff.tenantAuthorityGeneration()), + "tenantBillingSequence", + Long.parseLong(cutoff.tenantBillingSequence()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + Long.parseLong(cutoff.outboxSequence())))); + authority.put("tenantBillingCutoff", Map.copyOf(values)); + }); + var upstream = existing.issuerAccount(); + var issuanceFenceSource = requireIssuanceFenceSource(member); + byte[] issuer = upstream.canonicalIssuerProjection().toJson().getBytes(StandardCharsets.UTF_8); + byte[] account = + upstream.canonicalAccountProjection().toJson().getBytes(StandardCharsets.UTF_8); + byte[] membership = member.sourceEvent().canonicalJsonUtf8(); + var vector = new ArrayList(existing.hostedTerms().sourceEvidence()); + vector.add( + new SourceEvidence( + SourceKind.ISSUER, + "firemud-account-service", + Long.toString(upstream.issuer().generation()), + Long.toString(upstream.issuer().sourceVersion()), + upstream.issuer().checkpoint().outboxStreamKey(), + Long.toString(upstream.issuer().checkpoint().sequence()), + issuer)); + vector.add( + new SourceEvidence( + SourceKind.ACCOUNT, + actor.toString(), + Long.toString(upstream.account().generation()), + Long.toString(upstream.account().sourceVersion()), + upstream.account().checkpoint().outboxStreamKey(), + Long.toString(upstream.account().checkpoint().sequence()), + account)); + vector.add( + new SourceEvidence( + SourceKind.GLOBAL_ROLES, + actor.toString(), + Long.toString(upstream.account().generation()), + Long.toString(upstream.account().sourceVersion()), + upstream.account().checkpoint().outboxStreamKey(), + Long.toString(upstream.account().checkpoint().sequence()), + account)); + var tenantState = member.authoritySnapshot().tenants().getFirst(); + vector.add( + new SourceEvidence( + SourceKind.TENANT, + tenant.toString(), + Long.toString(tenantState.generation()), + Long.toString(tenantState.sourceVersion()), + null, + null, + canonical( + Map.of( + "creation", + member.creationSource(), + "checkpoints", + member.outboxCheckpoints(), + "events", + member.outboxSourceEvidence())))); + var membershipState = member.authoritySnapshot().memberships().getFirst(); + vector.add( + new SourceEvidence( + SourceKind.MEMBERSHIP, + actor + "/" + tenant, + Long.toString(membershipState.generation()), + Long.toString(membershipState.sourceVersion()), + null, + null, + canonical( + Map.of( + "event", + Base64.getEncoder().encodeToString(membership), + "membershipVersion", + member.membershipVersion(), + "roleSnapshotVersion", + member.roleSource().snapshotVersion(), + "roles", + member.roleSource().roles())))); + vector.sort(java.util.Comparator.comparing(SourceEvidence::key)); + byte[] evidence = + canonical( + Map.of( + "schemaVersion", + 1, + "accountId", + actor.toString(), + "tenantId", + tenant.toString(), + "sources", + vector.stream() + .map(value -> Base64.getEncoder().encodeToString(value.canonicalBytes())) + .toList())); + var checkpoints = + member.outboxCheckpoints().stream() + .map( + checkpoint -> { + Map value = new LinkedHashMap<>(); + value.put("outboxStreamKey", checkpoint.outboxStreamKey()); + value.put("outboxSequence", checkpoint.outboxSequence()); + member.outboxSourceEvidence().stream() + .filter(event -> event.outboxStreamKey().equals(checkpoint.outboxStreamKey())) + .findFirst() + .ifPresent( + event -> { + value.put("sourceEventId", event.eventId()); + value.put("sourceEventDigest", event.eventDigest()); + }); + return Map.copyOf(value); + }) + .toList(); + Map identity = + Map.of( + "sourceRowId", + upstream.account().accountSourceNumericId(), + "provenance", + upstream.account().accountUuidProvenance(), + "sourceNumericId", + upstream.account().accountSourceNumericId()); + return new Snapshot( + actor, + tenant, + Map.copyOf(authority), + numeric(member.membershipVersion()), + Long.parseLong(member.issuanceFence()), + issuanceFenceSource.sourceVersion(), + List.copyOf(vector), + evidence, + checkpoints, + identity); + } + + static IssuanceFence requireIssuanceFenceSource(CreatorControlCaptureSources member) { + var source = + Objects.requireNonNull( + Objects.requireNonNull(member).authoritySnapshot().issuanceFence(), + "Authenticated Account issuance fence source required"); + if (source.sourceVersion() <= 0L + || !Long.toString(source.value()).equals(member.issuanceFence())) { + throw new IllegalStateException("Authenticated Account issuance fence source required"); + } + return source; + } + + private static Map numeric(Map values) { + Map result = new LinkedHashMap<>(); + values.forEach((key, value) -> result.put(key, Long.parseLong(value))); + return Map.copyOf(result); + } + + public static byte[] canonical(Object value) { + try { + String original = JSON.writeValueAsString(value); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(original); + var exactNumbers = + JsonMapper.builder() + .enable(tools.jackson.databind.DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) + .enable(tools.jackson.databind.DeserializationFeature.USE_BIG_INTEGER_FOR_INTS) + .build(); + if (!sameValues( + exactNumbers.readValue(original, Object.class), + exactNumbers.readValue(canonical, Object.class))) { + throw new IllegalArgumentException("Canonical numeric authority must remain exact"); + } + return canonical; + } catch (java.io.IOException | RuntimeException exception) { + throw new IllegalArgumentException("Canonical control-ui value required"); + } + } + + private static boolean sameValues(Object original, Object canonical) { + if (original instanceof Number left && canonical instanceof Number right) { + return new java.math.BigDecimal(left.toString()) + .compareTo(new java.math.BigDecimal(right.toString())) + == 0; + } + if (original instanceof Map left && canonical instanceof Map right) { + return left.keySet().equals(right.keySet()) + && left.entrySet().stream() + .allMatch(entry -> sameValues(entry.getValue(), right.get(entry.getKey()))); + } + if (original instanceof List left && canonical instanceof List right) { + if (left.size() != right.size()) { + return false; + } + for (int index = 0; index < left.size(); index++) { + if (!sameValues(left.get(index), right.get(index))) { + return false; + } + } + return true; + } + return java.util.Objects.equals(original, canonical); + } + + public static final class Snapshot { + private final UUID actor; + private final UUID tenant; + private final Map tuple; + private final Map membership; + private final long fence; + private final long issuanceFenceSourceVersion; + private final List vector; + private final byte[] evidence; + private final List> checkpoints; + private final Map identity; + + private Snapshot( + UUID actor, + UUID tenant, + Map tuple, + Map membership, + long fence, + long issuanceFenceSourceVersion, + List vector, + byte[] evidence, + List> checkpoints, + Map identity) { + this.actor = actor; + this.tenant = tenant; + this.tuple = Map.copyOf(tuple); + this.membership = Map.copyOf(membership); + this.fence = fence; + this.issuanceFenceSourceVersion = issuanceFenceSourceVersion; + this.vector = List.copyOf(vector); + this.evidence = evidence.clone(); + this.checkpoints = List.copyOf(checkpoints); + this.identity = Map.copyOf(identity); + } + + public UUID actor() { + return actor; + } + + public UUID tenant() { + return tenant; + } + + public Map authorityTuple() { + return tuple; + } + + public Map membershipVersion() { + return membership; + } + + public long issuanceFence() { + return fence; + } + + public long issuanceFenceSourceVersion() { + return issuanceFenceSourceVersion; + } + + public List sources() { + return vector; + } + + public byte[] evidence() { + return evidence.clone(); + } + + public List> outboxCheckpoints() { + return checkpoints; + } + + public Map accountIdentitySource() { + return identity; + } + + @Override + public String toString() { + return "AccountControlUiAuthority[redacted]"; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java new file mode 100644 index 0000000000..d7a5c33684 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java @@ -0,0 +1,224 @@ +package net.firedevops.firemud.accountservice.authordraft; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.InitialAssociationReadback; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.EnvironmentBoundCurrentness; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.AuthorityScope; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.ScopeState; +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.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import org.jooq.DSLContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Account existing-source composition. No caller authentication, source provisioning, + * Draft reservation, commit order or owner mutation is provided. The caller retains its transaction + * through the intended local use; the returned observation cannot authorize a later commit. + */ +public final class AccountDraftSourceCompositionService { + private static final String ISSUER = "firemud-account-service"; + private final DSLContext dsl; + private final IndividualCreatorPartyRepository parties; + private final AccountTenantCreationBootstrapService memberships; + private final AccountHostedTermsService terms; + private final AccountAuthoritySourceEvidenceRepository upstream; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Owner transaction collaborators are retained privately.") + public AccountDraftSourceCompositionService( + DSLContext dsl, + IndividualCreatorPartyRepository parties, + AccountTenantCreationBootstrapService memberships, + AccountHostedTermsService terms, + AccountAuthoritySourceEvidenceRepository upstream) { + this.dsl = Objects.requireNonNull(dsl); + this.parties = Objects.requireNonNull(parties); + this.memberships = Objects.requireNonNull(memberships); + this.terms = Objects.requireNonNull(terms); + this.upstream = Objects.requireNonNull(upstream); + } + + /** The environment observation must have been obtained outside this owner transaction. */ + public ExistingSources readExistingSources( + CapturedEnvironmentBoundary environment, UUID canonicalTenantId) { + requireOwnerTransaction(); + Objects.requireNonNull(environment, "Owner-captured environment boundary required"); + if (canonicalTenantId == null || canonicalTenantId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical tenant UUID required"); + } + var scope = parties.lockExistingInitialAssociationScope(canonicalTenantId); + if (!canonicalTenantId.equals(scope.tenantId())) { + throw mismatch(); + } + var membership = + memberships.readExistingCreatorControlCaptureSources(scope.accountId(), canonicalTenantId); + if (!scope.accountId().equals(membership.accountUuid()) + || !canonicalTenantId.equals(membership.tenantUuid())) { + throw mismatch(); + } + // Preserve independently verified sequence-zero birth evidence as well as positive events. + var issuerAccount = upstream.readCurrentIssuerAccountSources(ISSUER, scope.accountId()); + requireUpstream(membership, issuerAccount); + var currentTerms = + terms.requireCurrentnessInOwnerTransaction(environment, scope.creatorPartyId()); + if (!scope.accountId().equals(currentTerms.terms().accountId()) + || !scope.creatorPartyId().equals(currentTerms.terms().creatorPartyId())) { + throw mismatch(); + } + var association = parties.readExistingInitialAssociation(canonicalTenantId); + var creator = association.creatorEvidence(); + var bootstrap = membership.bootstrapReceipt(); + if (!canonicalTenantId.equals(association.receipt().tenantId()) + || !scope.associationRequestId().equals(association.receipt().requestId()) + || !scope.creatorPartyId().equals(association.receipt().creatorPartyId()) + || !scope.accountId().equals(creator.initiatingAccountId()) + || !membership.creationSource().equals(creator.creationEvidence()) + || !creator.accountAuthorizationOperationId().equals(bootstrap.requestId()) + || !creator + .accountAuthorizationOperationId() + .equals(bootstrap.accountAuthorizationOperationId()) + || !creator.accountAuthorizationDigest().equals(bootstrap.accountAuthorizationDigest()) + || !creator.evidenceDigest().equals(bootstrap.creatorEvidenceDigest()) + || !Arrays.equals( + CreatorPartyEncoding.creation(creator), bootstrap.creatorEvidencePayload()) + || currentTerms.sourceEvidence().stream() + .filter(source -> source.kind() == SourceKind.CREATOR_PARTY) + .noneMatch( + source -> + source.scopeId().equals(association.partySource().creatorPartyId().toString()) + && Objects.equals( + source.generation(), + Long.toString(association.partySource().identityVersion())) + && source + .sourceVersion() + .equals(Long.toString(association.partySource().sourceVersion())) + && Arrays.equals( + source.evidence(), + CreatorPartyEncoding.party(association.partySource())))) { + throw mismatch(); + } + return new ExistingSources(membership, issuerAccount, association, currentTerms); + } + + private void requireUpstream( + CreatorControlCaptureSources membership, IssuerAccountSourceSnapshot source) { + var authority = membership.authoritySnapshot(); + if (!AuthorityScope.issuer(ISSUER).equals(source.issuer().scope()) + || !AuthorityScope.account(membership.accountUuid()).equals(source.account().scope()) + || !authority.issuanceFence().equals(source.issuanceFence()) + || !membership.issuanceFence().equals(Long.toString(source.issuanceFence().value()))) { + throw mismatch(); + } + requireSource( + membership, + authority.issuer(), + source.issuer(), + Objects.requireNonNull(source.canonicalIssuerProjection()).sourceEvent()); + requireSource( + membership, + authority.account(), + source.account(), + Objects.requireNonNull(source.canonicalAccountProjection()).sourceEvent()); + } + + private void requireSource( + CreatorControlCaptureSources membership, + ScopeState state, + CurrentSourceEvidence source, + Optional event) { + var checkpoint = source.checkpoint(); + var checkpoints = + membership.outboxCheckpoints().stream() + .filter(value -> value.outboxStreamKey().equals(checkpoint.outboxStreamKey())) + .toList(); + var events = + membership.outboxSourceEvidence().stream() + .filter(value -> value.outboxStreamKey().equals(checkpoint.outboxStreamKey())) + .toList(); + if (!state.scope().equals(source.scope()) + || state.generation() != source.generation() + || state.sourceVersion() != source.sourceVersion() + || !Objects.equals(state.issuanceFence(), source.issuanceFence()) + || checkpoints.size() != 1 + || !checkpoints.get(0).outboxSequence().equals(Long.toString(checkpoint.sequence())) + || (checkpoint.sequence() == 0L + ? !events.isEmpty() || event.isPresent() + : events.size() != 1 + || event.isEmpty() + || !events.get(0).outboxSequence().equals(Long.toString(checkpoint.sequence())) + || !events.get(0).eventId().equals(checkpoint.sourceEventId().orElseThrow()) + || !events.get(0).eventDigest().equals(checkpoint.sourceEventDigest().orElseThrow()) + || !events.get(0).canonicalEventJson().equals(event.orElseThrow()))) { + throw mismatch(); + } + } + + private void requireOwnerTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Writable READ_COMMITTED Account transaction required"); + } + dsl.connection( + connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable READ_COMMITTED Account transaction required"); + } + }); + } + + private static IllegalStateException mismatch() { + return new IllegalStateException( + "Existing Account creator source identities or currentness differ"); + } + + /** Immutable existing owner observations only; no authenticated actor or commit permission. */ + public static final class ExistingSources { + private final CreatorControlCaptureSources membership; + private final IssuerAccountSourceSnapshot issuerAccount; + private final InitialAssociationReadback association; + private final EnvironmentBoundCurrentness hostedTerms; + + private ExistingSources( + CreatorControlCaptureSources membership, + IssuerAccountSourceSnapshot issuerAccount, + InitialAssociationReadback association, + EnvironmentBoundCurrentness hostedTerms) { + this.membership = membership; + this.issuerAccount = issuerAccount; + this.association = association; + this.hostedTerms = hostedTerms; + } + + public CreatorControlCaptureSources membership() { + return membership; + } + + public IssuerAccountSourceSnapshot issuerAccount() { + return issuerAccount; + } + + public InitialAssociationReadback association() { + return association; + } + + public EnvironmentBoundCurrentness hostedTerms() { + return hostedTerms; + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java new file mode 100644 index 0000000000..3f34a89974 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java @@ -0,0 +1,1263 @@ +package net.firedevops.firemud.accountservice.config; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.IDN; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.net.URLEncoder; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +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.KeyStore; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.TrustManagerFactory; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Independently protected, default-inactive trust for Account's fixed public-JWKS Kubernetes + * ConfigMap calls. This is deliberately not a Spring component: lifecycle wiring must opt in. + */ +public final class AccountJwtJwksApiBinding { + public static final int MAX_BINDING_BYTES = 16 * 1024; + private static final int MAX_CA_BYTES = 128 * 1024; + private static final int MAX_BEARER_BYTES = 16 * 1024; + private static final int MAX_RESPONSE_BYTES = 1024 * 1024; + private static final int MAX_REQUEST_BYTES = 1024 * 1024; + private static final String BINDING_VERSION = "account-jwt-jwks-api-binding/v1"; + private static final String ACCOUNT_SERVICE_ACCOUNT = "account-service"; + private static final Path TRUST_ROOT = Path.of("/etc/firemud/account-jwt-api"); + private static final Path TRUST_BINDING_PATH = TRUST_ROOT.resolve("binding.json"); + private static final Path TRUST_CA_PATH = TRUST_ROOT.resolve("serving-ca.pem"); + + private static final Path TOKEN_ROOT = protectedTokenRoot(); + + private static final Path TOKEN_PATH = TOKEN_ROOT.resolve("token"); + + private static final Path CANONICAL_TOKEN_ROOT = canonicalProjectedTokenRoot(); + + private static final Pattern ENVIRONMENT = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern NAMESPACE = ENVIRONMENT; + 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 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 Pattern BEARER = Pattern.compile("[!-~]{1,16384}"); + private static final Set CONFIG_FIELDS = + Set.of( + "version", + "enabled", + "configRevision", + "environmentId", + "clusterId", + "apiServerUrl", + "tlsServerName", + "servingCaPath", + "servingCaSha256", + "bearerTokenPath", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedApiUsername", + "bindingDigest"); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "Account's bearer credential is read only from this fixed protected projected-token root.") + private static Path protectedTokenRoot() { + return Path.of("/var/run/secrets/firemud/account-jwt-api-token"); + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = + "This exact canonical root remains the only alternate projected-token mount accepted by the protected Account API boundary.") + private static Path canonicalProjectedTokenRoot() { + return Path.of("/run/secrets/firemud/account-jwt-api-token"); + } + + private final boolean enabled; + private final String protectedBindingPath; + private final Duration requestTimeout; + private final ProtectedState testProtectedState; + private final ProtectedPaths protectedPaths; + private final AtomicReference acceptedIdentity = new AtomicReference<>(); + + /** Creates an inert binding. No Spring activation or ambient Kubernetes configuration exists. */ + public AccountJwtJwksApiBinding() { + this(false, ""); + } + + /** + * Creates an explicitly selected binding. The selected file still has to authorize the exact + * Account endpoint, trust anchor, cluster/namespace incarnation, and authenticated principal. + */ + public AccountJwtJwksApiBinding(boolean enabled, String protectedBindingPath) { + this.enabled = enabled; + String configuredPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.protectedBindingPath = + TRUST_BINDING_PATH.toString().equals(configuredPath) ? configuredPath : ""; + this.requestTimeout = Duration.ofSeconds(8); + this.testProtectedState = null; + this.protectedPaths = + new ProtectedPaths( + TRUST_ROOT, TRUST_BINDING_PATH, TRUST_CA_PATH, TOKEN_ROOT, TOKEN_PATH, false); + } + + private AccountJwtJwksApiBinding(Duration requestTimeout, ProtectedState testProtectedState) { + this.enabled = true; + this.protectedBindingPath = ""; + this.requestTimeout = requestTimeout; + this.testProtectedState = testProtectedState; + this.protectedPaths = null; + } + + private AccountJwtJwksApiBinding(String bindingPath, ProtectedPaths protectedPaths) { + this.enabled = true; + this.protectedBindingPath = bindingPath; + this.requestTimeout = Duration.ofSeconds(8); + this.testProtectedState = null; + this.protectedPaths = protectedPaths; + } + + static AccountJwtJwksApiBinding forProtectedFilesTest( + Path bindingPath, Path trustRoot, Path caPath, Path tokenRoot, Path tokenPath) { + Objects.requireNonNull(bindingPath, "test binding path is required"); + Objects.requireNonNull(trustRoot, "test trust root is required"); + Objects.requireNonNull(caPath, "test CA path is required"); + Objects.requireNonNull(tokenRoot, "test token root is required"); + Objects.requireNonNull(tokenPath, "test token path is required"); + Path normalizedBinding = bindingPath.toAbsolutePath().normalize(); + Path normalizedTrustRoot = trustRoot.toAbsolutePath().normalize(); + Path normalizedCa = caPath.toAbsolutePath().normalize(); + Path normalizedTokenRoot = tokenRoot.toAbsolutePath().normalize(); + Path normalizedToken = tokenPath.toAbsolutePath().normalize(); + if (!normalizedBinding.equals(normalizedTrustRoot.resolve("binding.json")) + || !normalizedCa.equals(normalizedTrustRoot.resolve("serving-ca.pem")) + || !normalizedToken.equals(normalizedTokenRoot.resolve("token"))) { + throw new IllegalArgumentException("Protected Account JWT test paths are invalid"); + } + ProtectedPaths paths = + new ProtectedPaths( + normalizedTrustRoot, + normalizedBinding, + normalizedCa, + normalizedTokenRoot, + normalizedToken, + true); + return new AccountJwtJwksApiBinding(normalizedBinding.toString(), paths); + } + + /** + * Supplies trusted in-memory binding material only to package-local transport tests. It still + * exercises the production pinned-CA HTTPS sender and cannot install a custom HTTP client. + */ + static AccountJwtJwksApiBinding forTransportTest( + ParsedBinding binding, byte[] caBytes, String bearerToken, Duration requestTimeout) { + Objects.requireNonNull(binding, "transport test binding is required"); + Objects.requireNonNull(caBytes, "transport test CA is required"); + Objects.requireNonNull(requestTimeout, "transport test timeout is required"); + if (caBytes.length == 0 + || caBytes.length > MAX_CA_BYTES + || !sha256(caBytes).equals(binding.servingCaSha256()) + || !"https".equalsIgnoreCase(binding.apiServer().getScheme()) + || binding.apiServer().getHost() == null + || !binding.apiServer().getHost().equalsIgnoreCase(binding.tlsServerName()) + || !binding + .expectedApiUsername() + .equals("system:serviceaccount:" + binding.namespace() + ":" + ACCOUNT_SERVICE_ACCOUNT) + || bearerToken == null + || !BEARER.matcher(bearerToken).matches() + || requestTimeout.isZero() + || requestTimeout.isNegative() + || requestTimeout.compareTo(Duration.ofSeconds(8)) > 0) { + throw new IllegalArgumentException("Account JWT JWKS transport test binding is invalid"); + } + byte[] caSnapshot = caBytes.clone(); + Set readOnly = Set.of(PosixFilePermission.OWNER_READ); + FileIdentity bindingIdentity = testFileIdentity("test-binding", new byte[] {1}, readOnly); + FileIdentity caIdentity = testFileIdentity("test-ca", caSnapshot, readOnly); + FileIdentity bearerIdentity = + testFileIdentity( + binding.bearerTokenPath().toString(), + bearerToken.getBytes(StandardCharsets.UTF_8), + readOnly); + TrustIdentity identity = + new TrustIdentity( + bindingIdentity, + caIdentity, + credentialPolicy(bearerIdentity), + binding.bindingDigest(), + ""); + return new AccountJwtJwksApiBinding( + requestTimeout, + new ProtectedState(binding, caSnapshot, bearerToken, identity, bearerIdentity)); + } + + /** Returns non-secret pinned endpoint and identity fields after rechecking protected files. */ + public ParsedBinding current() { + if (!enabled || protectedBindingPath.isBlank()) { + throw new BindingRejectedException(); + } + try { + return acceptCurrentProtectedState().config(); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + /** Opens one fixed-endpoint operation with a single bounded bearer snapshot. */ + public ApiOperation beginOperation() { + if (!enabled || protectedBindingPath.isBlank()) { + throw new BindingRejectedException(); + } + try { + return new ApiOperation(acceptCurrentProtectedState()); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + private ApiResponse send(ProtectedState credentialSnapshot, ApiCall call, byte[] requestBody) { + return send(credentialSnapshot, call, requestBody, null); + } + + private ApiResponse send( + ProtectedState credentialSnapshot, + ApiCall call, + byte[] requestBody, + String protectedInventoryPath) { + Objects.requireNonNull(call, "Kubernetes API call is required"); + if (!enabled || protectedBindingPath.isBlank() || credentialSnapshot == null) { + throw new BindingRejectedException(); + } + if (requestBody != null && requestBody.length > MAX_REQUEST_BYTES) { + throw new BindingRejectedException(); + } + validateCallBody(call, requestBody); + ProtectedState state = recheckProtectedState(); + TrustIdentity baseline = acceptedIdentity.get(); + if (!baseline.equals(credentialSnapshot.identity()) + || !credentialSnapshot.bearerIdentity().equals(state.bearerIdentity())) { + throw new BindingRejectedException(); + } + + HttpClient client; + try { + client = createHttpClient(credentialSnapshot.caBytes()); + } catch (Exception ex) { + throw new BindingRejectedException(); + } + try (client) { + if ((call == ApiCall.READ_VALIDATOR_DEPLOYMENT + || call == ApiCall.LIST_VALIDATOR_PODS + || call == ApiCall.READ_VALIDATOR_REPLICA_SET) + != (protectedInventoryPath != null)) { + throw new BindingRejectedException(); + } + URI uri = + credentialSnapshot + .config() + .apiServer() + .resolve( + protectedInventoryPath == null + ? call.path(credentialSnapshot.config().namespace()) + : protectedInventoryPath); + HttpRequest.Builder request = + HttpRequest.newBuilder(uri) + .timeout(requestTimeout) + .header("Accept", "application/json") + .header("Authorization", "Bearer " + credentialSnapshot.bearerToken()); + if (call == ApiCall.PATCH_JWKS_CONFIG_MAP) { + request.header("Content-Type", "application/merge-patch+json"); + } else if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL) { + request.header("Content-Type", "application/json"); + } + if (requestBody == null) { + request.method(call.method(), HttpRequest.BodyPublishers.noBody()); + } else { + request.method(call.method(), HttpRequest.BodyPublishers.ofByteArray(requestBody)); + } + + // Catch changed or withdrawn trust after client construction and immediately before send. + ProtectedState beforeSend = recheckProtectedState(); + if (!baseline.equals(beforeSend.identity()) + || !credentialSnapshot.bearerIdentity().equals(beforeSend.bearerIdentity())) { + throw new BindingRejectedException(); + } + long responseDeadlineNanos = System.nanoTime() + requestTimeout.toNanos(); + try { + HttpResponse response = + client.send(request.build(), HttpResponse.BodyHandlers.ofInputStream()); + try (java.io.InputStream body = response.body()) { + ExecutorService bodyReader = + Executors.newSingleThreadExecutor( + task -> { + Thread thread = new Thread(task, "account-jwks-api-response-reader"); + thread.setDaemon(true); + return thread; + }); + Future bodyFuture = + bodyReader.submit(() -> readBounded(body, MAX_RESPONSE_BYTES)); + try { + long remainingNanos = responseDeadlineNanos - System.nanoTime(); + if (remainingNanos <= 0L) { + throw new TimeoutException(); + } + return new ApiResponse( + response.statusCode(), bodyFuture.get(remainingNanos, TimeUnit.NANOSECONDS)); + } catch (TimeoutException ex) { + bodyFuture.cancel(true); + throw new IOException("Kubernetes API response exceeded its deadline"); + } finally { + bodyReader.shutdownNow(); + } + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new ApiTransportException(); + } catch (Exception ex) { + throw new ApiTransportException(); + } + } + } + + private ProtectedState recheckProtectedState() { + try { + return acceptCurrentProtectedState(); + } catch (BindingRejectedException ex) { + throw ex; + } catch (Exception ex) { + throw new BindingRejectedException(); + } + } + + /** Strict parser is exposed for deterministic format tests, not as an activation path. */ + public static ParsedBinding parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BINDING_BYTES) { + throw new IllegalArgumentException("Account JWT JWKS API binding is unavailable"); + } + try { + String text = decodeUtf8(bytes); + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || !root.isObject() || root.size() != CONFIG_FIELDS.size()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + Map supplied = new LinkedHashMap<>(); + for (Map.Entry field : root.properties()) { + if (!CONFIG_FIELDS.contains(field.getKey()) + || supplied.putIfAbsent(field.getKey(), field.getValue()) != null) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + } + if (!supplied.keySet().equals(CONFIG_FIELDS) + || !"true".equals(requiredText(root, "enabled", 5)) + || !BINDING_VERSION.equals(requiredText(root, "version", 80))) { + throw new IllegalArgumentException("Account JWT JWKS API binding is disabled"); + } + + String revision = requiredText(root, "configRevision", 128); + String environmentId = requiredText(root, "environmentId", 63); + String clusterId = requiredText(root, "clusterId", 128); + String namespace = requiredText(root, "namespace", 63); + String clusterUid = canonicalUid(requiredText(root, "expectedClusterIncarnationUid", 36)); + String namespaceUid = canonicalUid(requiredText(root, "expectedNamespaceUid", 36)); + String apiUsername = requiredText(root, "expectedApiUsername", 256); + if (!REVISION.matcher(revision).matches() + || !ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !NAMESPACE.matcher(namespace).matches() + || !apiUsername.equals( + "system:serviceaccount:" + namespace + ":" + ACCOUNT_SERVICE_ACCOUNT)) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + + URI apiServer = parseApiServer(requiredText(root, "apiServerUrl", 512)); + String tlsServerName = requiredText(root, "tlsServerName", 253); + String asciiTlsName = canonicalDnsName(tlsServerName); + if (!asciiTlsName.equalsIgnoreCase(apiServer.getHost())) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is not pinned"); + } + String caPath = requiredText(root, "servingCaPath", 1024); + String caSha256 = requiredText(root, "servingCaSha256", 64); + String tokenPath = requiredText(root, "bearerTokenPath", 1024); + if (!SHA256.matcher(caSha256).matches()) { + throw new IllegalArgumentException("Account JWT JWKS API CA pin is malformed"); + } + Path servingCaPath = absoluteProtectedPath(caPath); + Path bearerTokenPath = absoluteProtectedPath(tokenPath); + String suppliedDigest = requiredText(root, "bindingDigest", 64); + if (!SHA256.matcher(suppliedDigest).matches() + || !suppliedDigest.equals(computeBindingDigest(root))) { + throw new IllegalArgumentException("Account JWT JWKS API binding digest is invalid"); + } + return new ParsedBinding( + revision, + environmentId, + clusterId, + apiServer, + asciiTlsName, + servingCaPath, + caSha256, + bearerTokenPath, + namespace, + clusterUid, + namespaceUid, + apiUsername, + suppliedDigest); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + } + + public static String computeBindingDigest(JsonNode protectedBinding) { + if (protectedBinding == null || !protectedBinding.isObject()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + try { + Map content = new LinkedHashMap<>(); + for (String field : CONFIG_FIELDS) { + if (!"bindingDigest".equals(field)) { + JsonNode value = protectedBinding.get(field); + if (value == null || !value.isValueNode()) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + content.put(field, value.asText()); + } + } + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8(STRICT_JSON.writeValueAsString(content)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (IOException | NoSuchAlgorithmException | RuntimeException ex) { + throw new IllegalArgumentException("Account JWT JWKS API binding digest is unavailable"); + } + } + + private ProtectedState readCurrentProtectedState() throws Exception { + if (testProtectedState != null) { + return testProtectedState; + } + Path bindingPath = absoluteProtectedPath(protectedBindingPath); + if (protectedPaths == null + || !bindingPath.equals(protectedPaths.bindingPath()) + || (!protectedPaths.testOnly() + && (!bindingPath.equals(TRUST_BINDING_PATH) + || !protectedPaths.trustRoot().equals(TRUST_ROOT) + || !protectedPaths.caPath().equals(TRUST_CA_PATH) + || !protectedPaths.tokenRoot().equals(TOKEN_ROOT) + || !protectedPaths.tokenPath().equals(TOKEN_PATH)))) { + throw new BindingRejectedException(); + } + Path canonicalTokenRoot = resolveTrustedTokenRoot(protectedPaths); + if (!protectedPaths.testOnly()) { + verifyProtectedDirectoryChain(TRUST_ROOT); + verifyProtectedDirectoryChain(canonicalTokenRoot); + } + ProtectedFile bindingFile = readProtectedFile(bindingPath, MAX_BINDING_BYTES); + ParsedBinding config = parseProtectedBytes(bindingFile.bytes()); + if (!config.servingCaPath().equals(protectedPaths.caPath()) + || !config.bearerTokenPath().equals(protectedPaths.tokenPath())) { + throw new BindingRejectedException(); + } + ProtectedFile caFile = readProtectedFile(config.servingCaPath(), MAX_CA_BYTES); + ProtectedFile tokenFile = + readBearerProtectedFile(config.bearerTokenPath(), protectedPaths.tokenRoot()); + String caDigest = sha256(caFile.bytes()); + if (!caDigest.equals(config.servingCaSha256())) { + throw new BindingRejectedException(); + } + String token = decodeUtf8(tokenFile.bytes()); + if (!BEARER.matcher(token).matches()) { + throw new BindingRejectedException(); + } + TrustIdentity identity = + new TrustIdentity( + bindingFile.identity(), + caFile.identity(), + credentialPolicy(tokenFile.identity()), + config.bindingDigest(), + canonicalTokenRoot.toString()); + return new ProtectedState(config, caFile.bytes(), token, identity, tokenFile.identity()); + } + + private static CredentialPolicyIdentity credentialPolicy(FileIdentity identity) { + return new CredentialPolicyIdentity( + identity.path(), identity.ownerUid(), identity.groupId(), identity.permissions()); + } + + private ProtectedState acceptCurrentProtectedState() throws Exception { + ProtectedState state = readCurrentProtectedState(); + TrustIdentity baseline = acceptedIdentity.get(); + if (baseline == null) { + acceptedIdentity.compareAndSet(null, state.identity()); + baseline = acceptedIdentity.get(); + } + if (baseline == null || !baseline.equals(state.identity())) { + throw new BindingRejectedException(); + } + return state; + } + + private static HttpClient createHttpClient(byte[] caBytes) throws Exception { + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + List certificates = + List.copyOf(certificateFactory.generateCertificates(new ByteArrayInputStream(caBytes))); + if (certificates.isEmpty() || certificates.size() > 16) { + throw new BindingRejectedException(); + } + KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + int index = 0; + for (Certificate certificate : certificates) { + if (!(certificate instanceof X509Certificate x509)) { + throw new BindingRejectedException(); + } + x509.checkValidity(); + if (x509.getBasicConstraints() < 0) { + throw new BindingRejectedException(); + } + trustStore.setCertificateEntry("account-jwks-ca-" + index++, x509); + } + TrustManagerFactory trustManagers = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustManagers.getTrustManagers(), null); + SSLParameters sslParameters = new SSLParameters(); + sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); + return HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(3)) + .followRedirects(HttpClient.Redirect.NEVER) + .version(HttpClient.Version.HTTP_1_1) + .sslContext(sslContext) + .sslParameters(sslParameters) + .proxy(DIRECT_ONLY_PROXY) + .build(); + } + + private static final ProxySelector DIRECT_ONLY_PROXY = + new ProxySelector() { + @Override + public List select(URI uri) { + return List.of(Proxy.NO_PROXY); + } + + @Override + public void connectFailed(URI uri, SocketAddress address, IOException failure) { + // No proxy exists; connection failures are handled by the bounded API call. + } + }; + + private static byte[] readBounded(java.io.InputStream input, int maximumBytes) + throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(Math.min(maximumBytes, 8192)); + byte[] buffer = new byte[8192]; + int total = 0; + while (true) { + int count = input.read(buffer); + if (count < 0) { + return output.toByteArray(); + } + total += count; + if (total > maximumBytes) { + throw new IOException("Kubernetes API response exceeded its bound"); + } + output.write(buffer, 0, count); + } + } + + private static void validateCallBody(ApiCall call, byte[] body) { + if (call == ApiCall.PATCH_JWKS_CONFIG_MAP) { + if (body == null || body.length == 0) { + throw new BindingRejectedException(); + } + try { + JsonNode patch = STRICT_JSON.readTree(decodeUtf8(body)); + JsonNode metadata = patch == null ? null : patch.get("metadata"); + JsonNode data = patch == null ? null : patch.get("data"); + if (patch == null + || !patch.isObject() + || patch.size() != 2 + || metadata == null + || !metadata.isObject() + || metadata.size() != 2 + || !validUid(text(metadata.get("uid"))) + || !validResourceVersion(text(metadata.get("resourceVersion"))) + || data == null + || !data.isObject() + || data.size() != 2 + || !data.has("jwks.json") + || !data.has("jwt-generation.json") + || !data.get("jwks.json").isTextual() + || !data.get("jwt-generation.json").isTextual() + || data.get("jwks.json").asText().isBlank() + || data.get("jwt-generation.json").asText().isBlank()) { + throw new BindingRejectedException(); + } + JsonNode jwks = STRICT_JSON.readTree(data.get("jwks.json").asText()); + JsonNode keys = jwks == null ? null : jwks.get("keys"); + if (jwks == null + || !jwks.isObject() + || jwks.size() != 1 + || keys == null + || !keys.isArray() + || keys.isEmpty()) { + throw new BindingRejectedException(); + } + for (JsonNode key : keys) { + if (!key.isObject() + || key.has("d") + || key.has("p") + || key.has("q") + || key.has("dp") + || key.has("dq") + || key.has("qi") + || key.has("oth") + || key.has("k")) { + throw new BindingRejectedException(); + } + } + } catch (BindingRejectedException ex) { + throw ex; + } catch (RuntimeException ex) { + throw new BindingRejectedException(); + } + return; + } + if (call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL) { + String expected = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}"; + if (body == null || !expected.equals(decodeUtf8(body))) { + throw new BindingRejectedException(); + } + return; + } + if (body != null) { + throw new BindingRejectedException(); + } + } + + private static ProtectedFile readProtectedFile(Path path, int maximumBytes) throws IOException { + return readProtectedFile(path, maximumBytes, false); + } + + private static ProtectedFile readBearerProtectedFile(Path configuredPath, Path trustedTokenRoot) + throws IOException { + Path absolute = configuredPath.toAbsolutePath().normalize(); + Path tokenRoot = trustedTokenRoot.toAbsolutePath().normalize(); + if (absolute.getParent() == null + || !absolute.equals(configuredPath) + || !absolute.equals(tokenRoot.resolve("token"))) { + throw new IOException("Protected Account JWT bearer file is unavailable"); + } + Path canonicalTokenRoot = tokenRoot.toRealPath(); + if (!canonicalTokenRoot.equals(tokenRoot) && !canonicalTokenRoot.equals(CANONICAL_TOKEN_ROOT)) { + throw new IOException("Protected Account JWT bearer projection root is invalid"); + } + verifyProtectedDirectory(canonicalTokenRoot); + + BasicFileAttributes linkBefore = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!linkBefore.isSymbolicLink()) { + throw new IOException("Protected Account JWT bearer file is unavailable"); + } + Object linkOwner = Files.getAttribute(absolute, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!(linkOwner instanceof Number linkUid) || linkUid.longValue() != 0L) { + throw new IOException("Protected Account JWT bearer file ownership is invalid"); + } + + Path target = absolute.toRealPath(); + Path versionDirectory = target.getParent(); + Path targetFileName = target.getFileName(); + Path versionDirectoryFileName = + versionDirectory == null ? null : versionDirectory.getFileName(); + if (!target.startsWith(canonicalTokenRoot) + || versionDirectory == null + || !canonicalTokenRoot.equals(versionDirectory.getParent()) + || targetFileName == null + || !"token".equals(targetFileName.toString()) + || versionDirectoryFileName == null + || !versionDirectoryFileName.toString().matches("\\.\\.[A-Za-z0-9._-]{1,128}")) { + throw new IOException("Protected Account JWT bearer projection is invalid"); + } + ProtectedFile targetFile = readProtectedFile(target, MAX_BEARER_BYTES, true); + Path targetAfter = absolute.toRealPath(); + BasicFileAttributes linkAfter = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Object linkOwnerAfter = Files.getAttribute(absolute, "unix:uid", LinkOption.NOFOLLOW_LINKS); + if (!target.equals(targetAfter) + || !sameLinkAttributes(linkBefore, linkAfter) + || !(linkOwnerAfter instanceof Number linkUidAfter) + || linkUidAfter.longValue() != 0L) { + throw new IOException("Protected Account JWT bearer file changed while reading"); + } + + FileIdentity targetIdentity = targetFile.identity(); + return new ProtectedFile( + targetFile.bytes(), + new FileIdentity( + absolute.toString(), + target + "|link=" + String.valueOf(linkBefore.fileKey()), + targetIdentity.size(), + targetIdentity.modifiedMillis(), + targetIdentity.ownerUid(), + targetIdentity.groupId(), + targetIdentity.permissions(), + targetIdentity.contentSha256())); + } + + private static ProtectedFile readProtectedFile( + Path path, int maximumBytes, boolean bearerCredential) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute) || !absolute.equals(absolute.toRealPath())) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > maximumBytes) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + FileSecurity beforeSecurity = fileSecurity(absolute); + verifyRootOwnedAndNonWritable(absolute); + if (bearerCredential) { + verifyBearerPermissions(absolute, beforeSecurity.permissions()); + } + 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 JWKS file changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + } + BasicFileAttributes after = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + FileSecurity afterSecurity = fileSecurity(absolute); + if (!sameAttributes(before, after) || !beforeSecurity.equals(afterSecurity)) { + throw new IOException("Protected Account JWT JWKS file changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + if (bearerCredential) { + verifyBearerPermissions(absolute, afterSecurity.permissions()); + } + return new ProtectedFile( + bytes, + new FileIdentity( + absolute.toString(), + String.valueOf(before.fileKey()), + before.size(), + before.lastModifiedTime().toMillis(), + afterSecurity.ownerUid(), + afterSecurity.groupId(), + afterSecurity.permissions(), + sha256(bytes))); + } + + private static FileSecurity fileSecurity(Path file) throws IOException { + Object owner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object group = Files.getAttribute(file, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!(owner instanceof Number ownerUid) || !(group instanceof Number groupId)) { + throw new IOException("Protected Account JWT JWKS file ownership is unavailable"); + } + return new FileSecurity( + ownerUid.longValue(), + groupId.longValue(), + Set.copyOf(Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS))); + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected Account JWT JWKS file is unavailable"); + } + verifyProtectedDirectory(parent); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + if (!(fileOwner instanceof Number fileUid) || fileUid.longValue() != 0L || writable(fileMode)) { + throw new IOException("Protected Account JWT JWKS file ownership is invalid"); + } + } + + private static void verifyProtectedDirectory(Path directory) throws IOException { + Path normalizedDirectory = directory.toAbsolutePath().normalize(); + Path realDirectory = normalizedDirectory.toRealPath(); + Object directoryOwner = + Files.getAttribute(realDirectory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set directoryMode = + Files.getPosixFilePermissions(realDirectory, LinkOption.NOFOLLOW_LINKS); + if (!realDirectory.equals(normalizedDirectory) + || !Files.isDirectory(realDirectory, LinkOption.NOFOLLOW_LINKS) + || !(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writableByUntrusted(directoryMode)) { + throw new IOException("Protected Account JWT JWKS directory ownership is invalid"); + } + } + + private static Path resolveTrustedTokenRoot(ProtectedPaths paths) throws IOException { + Path lexicalRoot = paths.tokenRoot().toAbsolutePath().normalize(); + Path canonicalRoot = lexicalRoot.toRealPath(); + if (paths.testOnly()) { + if (!canonicalRoot.equals(lexicalRoot)) { + throw new IOException("Protected Account JWT bearer root is unavailable"); + } + } else if (!lexicalRoot.equals(TOKEN_ROOT) + || (!canonicalRoot.equals(TOKEN_ROOT) && !canonicalRoot.equals(CANONICAL_TOKEN_ROOT))) { + throw new IOException("Protected Account JWT bearer root is unavailable"); + } + return canonicalRoot; + } + + private static void verifyProtectedDirectoryChain(Path directory) throws IOException { + Path normalized = directory.toAbsolutePath().normalize(); + Path canonical = normalized.toRealPath(); + if (!normalized.equals(canonical)) { + throw new IOException("Protected Account JWT JWKS directory ownership is invalid"); + } + for (Path current = canonical; current != null; current = current.getParent()) { + verifyProtectedDirectory(current); + } + } + + private static boolean writable(Set permissions) { + return permissions.contains(PosixFilePermission.OWNER_WRITE) + || permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static boolean writableByUntrusted(Set permissions) { + return permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static void verifyBearerPermissions(Path file, Set permissions) + throws IOException { + if (!permissions.contains(PosixFilePermission.OWNER_READ) + || !Files.isReadable(file) + || permissions.contains(PosixFilePermission.OTHERS_READ) + || permissions.contains(PosixFilePermission.OWNER_EXECUTE) + || permissions.contains(PosixFilePermission.GROUP_EXECUTE) + || permissions.contains(PosixFilePermission.OTHERS_EXECUTE)) { + throw new IOException("Protected Account JWT bearer file permissions are invalid"); + } + } + + private static boolean validUid(String value) { + return value != null && UID.matcher(value).matches(); + } + + private static boolean validResourceVersion(String value) { + return value != null && value.matches("[!-~]{1,256}"); + } + + private static boolean sameAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static boolean sameLinkAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return before.isSymbolicLink() == after.isSymbolicLink() + && before.isRegularFile() == after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static String requiredText(JsonNode object, String field, int maximumLength) { + JsonNode value = object.get(field); + if (value == null + || !value.isTextual() + || value.asText().isEmpty() + || value.asText().length() > maximumLength) { + throw new IllegalArgumentException("Account JWT JWKS API binding is malformed"); + } + return value.asText(); + } + + private static String text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + private static URI parseApiServer(String value) { + try { + URI uri = URI.create(value); + if (!"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getPort() < 1 + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || (uri.getRawPath() != null + && !uri.getRawPath().isEmpty() + && !"/".equals(uri.getRawPath()))) { + throw new IllegalArgumentException("Account JWT JWKS API endpoint is malformed"); + } + return URI.create("https://" + uri.getRawAuthority() + "/"); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Account JWT JWKS API endpoint is malformed"); + } + } + + private static String canonicalDnsName(String value) { + if (value == null || value.isBlank() || value.endsWith(".")) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + try { + String ascii = + IDN.toASCII(value, IDN.USE_STD3_ASCII_RULES).toLowerCase(java.util.Locale.ROOT); + if (ascii.length() > 253 || ascii.startsWith("[") || isIpLiteral(ascii)) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + return ascii; + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("Account JWT JWKS API TLS name is malformed"); + } + } + + private static boolean isIpLiteral(String value) { + return value.matches("[0-9.]+") || value.indexOf(':') >= 0; + } + + private static Path absoluteProtectedPath(String value) { + Path path = Path.of(value); + if (!path.isAbsolute() || !path.normalize().equals(path)) { + throw new IllegalArgumentException("Account JWT JWKS protected path is malformed"); + } + return path; + } + + private static String canonicalUid(String value) { + if (!UID.matcher(value).matches() || "00000000-0000-0000-0000-000000000000".equals(value)) { + throw new IllegalArgumentException("Account JWT JWKS API UID is malformed"); + } + return value; + } + + 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("Account JWT JWKS protected file is not UTF-8"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception ex) { + throw new IllegalStateException("Account JWT JWKS digest is unavailable"); + } + } + + private static FileIdentity testFileIdentity( + String path, byte[] bytes, Set permissions) { + return new FileIdentity( + path, "test-file-identity:" + path, bytes.length, 1L, 0L, 0L, permissions, sha256(bytes)); + } + + private record ProtectedFile(byte[] bytes, FileIdentity identity) {} + + private record FileSecurity(long ownerUid, long groupId, Set permissions) {} + + private record ProtectedState( + ParsedBinding config, + byte[] caBytes, + String bearerToken, + TrustIdentity identity, + FileIdentity bearerIdentity) {} + + private record TrustIdentity( + FileIdentity binding, + FileIdentity ca, + CredentialPolicyIdentity bearer, + String bindingDigest, + String bearerRootRealPath) {} + + private record CredentialPolicyIdentity( + String path, long ownerUid, long groupId, Set permissions) {} + + private record ProtectedPaths( + Path trustRoot, + Path bindingPath, + Path caPath, + Path tokenRoot, + Path tokenPath, + boolean testOnly) {} + + private record FileIdentity( + String path, + String fileKey, + long size, + long modifiedMillis, + long ownerUid, + long groupId, + Set permissions, + String contentSha256) {} + + public record ParsedBinding( + String configRevision, + String environmentId, + String clusterId, + URI apiServer, + String tlsServerName, + Path servingCaPath, + String servingCaSha256, + Path bearerTokenPath, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedApiUsername, + String bindingDigest) {} + + /** One operation-scoped credential lease; all its API calls use the same bearer snapshot. */ + public final class ApiOperation implements AutoCloseable { + private ProtectedState credentialSnapshot; + + private ApiOperation(ProtectedState credentialSnapshot) { + this.credentialSnapshot = credentialSnapshot; + } + + public ParsedBinding binding() { + if (credentialSnapshot == null) { + throw new BindingRejectedException(); + } + return credentialSnapshot.config(); + } + + public ApiResponse send(ApiCall call, byte[] requestBody) { + return AccountJwtJwksApiBinding.this.send(credentialSnapshot, call, requestBody); + } + + /** Reads one Deployment named by the independently protected validator inventory only. */ + public ApiResponse readValidatorDeployment( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, ApiCall.READ_VALIDATOR_DEPLOYMENT, inventory, validator, null); + } + + /** Lists Pods only by the protected validator selector in the pinned namespace. */ + public ApiResponse listValidatorPods( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, ApiCall.LIST_VALIDATOR_PODS, inventory, validator, continuationToken); + } + + /** Reads one ReplicaSet named by an observed Pod owner reference in the pinned namespace. */ + public ApiResponse readValidatorReplicaSet( + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String replicaSetName) { + return AccountJwtJwksApiBinding.this.sendInventoryRead( + credentialSnapshot, + ApiCall.READ_VALIDATOR_REPLICA_SET, + inventory, + validator, + null, + replicaSetName); + } + + @Override + public void close() { + credentialSnapshot = null; + } + } + + private ApiResponse sendInventoryRead( + ProtectedState credentialSnapshot, + ApiCall call, + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken) { + return sendInventoryRead( + credentialSnapshot, call, inventory, validator, continuationToken, null); + } + + private ApiResponse sendInventoryRead( + ProtectedState credentialSnapshot, + ApiCall call, + AccountJwtValidatorInventoryBinding.ProtectedInventory inventory, + AccountJwtValidatorInventoryBinding.ValidatorExpectation validator, + String continuationToken, + String replicaSetName) { + if (credentialSnapshot == null + || inventory == null + || validator == null + || !inventory.matchesApiBinding(credentialSnapshot.config()) + || inventory.validators().stream().noneMatch(expected -> expected == validator)) { + throw new BindingRejectedException(); + } + String path; + if (call == ApiCall.READ_VALIDATOR_DEPLOYMENT) { + if (continuationToken != null) { + throw new BindingRejectedException(); + } + path = + "/apis/apps/v1/namespaces/" + + inventory.namespace() + + "/deployments/" + + validator.deploymentName(); + } else if (call == ApiCall.LIST_VALIDATOR_PODS) { + String selector = + validator.selector().entrySet().stream() + .sorted(Map.Entry.comparingByKey()) + .map(entry -> entry.getKey() + "=" + entry.getValue()) + .collect(java.util.stream.Collectors.joining(",")); + path = + "/api/v1/namespaces/" + + inventory.namespace() + + "/pods?labelSelector=" + + queryEncode(selector) + + "&limit=250"; + if (continuationToken != null && !continuationToken.isEmpty()) { + if (continuationToken.length() > 2048 + || !continuationToken.matches("[A-Za-z0-9_./+=-]{1,2048}")) { + throw new BindingRejectedException(); + } + path += "&continue=" + queryEncode(continuationToken); + } + } else if (call == ApiCall.READ_VALIDATOR_REPLICA_SET) { + if (continuationToken != null + || replicaSetName == null + || !replicaSetName.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new BindingRejectedException(); + } + path = "/apis/apps/v1/namespaces/" + inventory.namespace() + "/replicasets/" + replicaSetName; + } else { + throw new BindingRejectedException(); + } + return send(credentialSnapshot, call, null, path); + } + + private static String queryEncode(String value) { + return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20"); + } + + public enum ApiCall { + REVIEW_AUTHENTICATED_PRINCIPAL("POST", "/apis/authentication.k8s.io/v1/selfsubjectreviews"), + READ_KUBE_SYSTEM_NAMESPACE("GET", "/api/v1/namespaces/kube-system"), + READ_TARGET_NAMESPACE("GET", null), + READ_JWKS_CONFIG_MAP("GET", null), + PATCH_JWKS_CONFIG_MAP("PATCH", null), + READ_VALIDATOR_DEPLOYMENT("GET", null), + LIST_VALIDATOR_PODS("GET", null), + READ_VALIDATOR_REPLICA_SET("GET", null); + + private final String method; + private final String fixedPath; + + ApiCall(String method, String fixedPath) { + this.method = method; + this.fixedPath = fixedPath; + } + + public String method() { + return method; + } + + private String path(String namespace) { + return switch (this) { + case REVIEW_AUTHENTICATED_PRINCIPAL, READ_KUBE_SYSTEM_NAMESPACE -> fixedPath; + case READ_TARGET_NAMESPACE -> "/api/v1/namespaces/" + namespace; + case READ_JWKS_CONFIG_MAP, PATCH_JWKS_CONFIG_MAP -> + "/api/v1/namespaces/" + namespace + "/configmaps/jwt-jwks"; + case READ_VALIDATOR_DEPLOYMENT, LIST_VALIDATOR_PODS, READ_VALIDATOR_REPLICA_SET -> + throw new BindingRejectedException(); + }; + } + } + + public record ApiResponse(int statusCode, byte[] body) { + public ApiResponse { + body = body == null ? new byte[0] : body.clone(); + } + + @Override + public byte[] body() { + return body.clone(); + } + } + + public static final class BindingRejectedException extends RuntimeException { + public BindingRejectedException() { + super("Account JWT JWKS API binding is unavailable or changed"); + } + } + + public static final class ApiTransportException extends RuntimeException { + public ApiTransportException() { + super("Account JWT JWKS Kubernetes API request failed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java new file mode 100644 index 0000000000..e9571dbea4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBinding.java @@ -0,0 +1,488 @@ +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.time.Clock; +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.common.json.Rfc8785CanonicalJson; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import tools.jackson.databind.json.JsonMapper; + +/** Independently protected, expiring trust for the non-authorizing readiness RPC only. */ +@Component +public final class AccountJwtReadinessTrustBinding { + public static final int MAX_FILE_BYTES = 8 * 1024; + private static final String VERSION = "account-jwt-readiness-trust-binding/v1"; + private static final String VALIDATOR_ID = "account-service"; + private static final String HARNESS_SERVICE_ACCOUNT = "account-jwt-readiness-harness"; + private static final Set REQUIRED_FIELDS = + Set.of( + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "expectedPeerUri", + "peerSpkiSha256Pins", + "validatorId", + "validatorInstanceId", + "validUntilEpochSecond", + "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 INSTANCE = 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; + private final Clock clock; + + @Autowired + public AccountJwtReadinessTrustBinding( + @Value("${firemud.account.jwt-readiness.validation.enabled:false}") boolean enabled, + @Value("${firemud.account.jwt-readiness.validation.protected-binding-path:}") + String protectedBindingPath) { + this(enabled, protectedBindingPath, Clock.systemUTC()); + } + + AccountJwtReadinessTrustBinding(boolean enabled, String protectedBindingPath, Clock clock) { + this.enabled = enabled; + this.protectedBindingPath = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.clock = Objects.requireNonNull(clock); + } + + /** Missing, disabled, malformed, expired, or mutable trust configuration denies access. */ + public Optional current() { + if (!enabled || protectedBindingPath.isBlank()) { + return Optional.empty(); + } + try { + return Optional.of(readProtectedFile(Path.of(protectedBindingPath), clock.instant())); + } catch (Exception ex) { + return Optional.empty(); + } + } + + static Binding parseProtectedBytes(byte[] bytes, long nowEpochSecond) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_FILE_BYTES) { + throw unavailable(); + } + Map fields = parseFields(decodeUtf8(bytes)); + if (!fields.keySet().equals(REQUIRED_FIELDS) || !"true".equals(fields.get("enabled"))) { + throw unavailable(); + } + + 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"); + String instanceId = fields.get("validatorInstanceId"); + long validUntil = parsePositiveLong(fields.get("validUntilEpochSecond")); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(revision).matches() + || !INSTANCE.matcher(instanceId).matches() + || !VALIDATOR_ID.equals(fields.get("validatorId")) + || nowEpochSecond <= 0L + || nowEpochSecond >= validUntil) { + throw unavailable(); + } + + String expectedUri = fields.get("expectedPeerUri"); + if (!expectedHarnessUri(namespace, expectedUri)) { + throw unavailable(); + } + List pins = parsePins(fields.get("peerSpkiSha256Pins")); + String digest = + computeBindingDigest( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + instanceId, + validUntil); + if (!digest.equals(fields.get("bindingDigest"))) { + throw unavailable(); + } + return new Binding( + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + expectedUri, + pins, + revision, + VALIDATOR_ID, + instanceId, + validUntil, + digest); + } + + private static Binding readProtectedFile(Path path, java.time.Instant now) throws IOException { + Path absolute = path.toAbsolutePath().normalize(); + if (Files.isSymbolicLink(absolute)) { + throw new IOException("Protected readiness binding is unavailable"); + } + BasicFileAttributes before = + Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() || before.size() <= 0 || before.size() > MAX_FILE_BYTES) { + throw new IOException("Protected readiness binding is unavailable"); + } + verifyRootOwnedAndNonWritable(absolute); + 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()) { + if (channel.read(buffer) < 0) { + throw new IOException("Protected readiness binding changed while reading"); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw new IOException("Protected readiness 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 readiness binding changed while reading"); + } + verifyRootOwnedAndNonWritable(absolute); + return parseProtectedBytes(bytes, now.getEpochSecond()); + } + + private static Map parseFields(String text) { + 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 unavailable(); + } + String key = line.substring(0, separator); + String value = line.substring(separator + 1); + if (!REQUIRED_FIELDS.contains(key) || fields.putIfAbsent(key, value) != null) { + throw unavailable(); + } + } + return fields; + } + + private static void verifyRootOwnedAndNonWritable(Path file) throws IOException { + Path parent = file.getParent(); + if (parent == null || Files.isSymbolicLink(file)) { + throw new IOException("Protected readiness binding is unavailable"); + } + Path realParent = parent.toRealPath(); + Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set fileMode = + Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS); + if (!(fileOwner instanceof Number fileUid) || fileUid.longValue() != 0L || writable(fileMode)) { + throw new IOException("Protected readiness binding ownership is invalid"); + } + for (Path directory = realParent; directory != null; directory = directory.getParent()) { + Object directoryOwner = Files.getAttribute(directory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set directoryMode = + Files.getPosixFilePermissions(directory, LinkOption.NOFOLLOW_LINKS); + if (!(directoryOwner instanceof Number directoryUid) + || directoryUid.longValue() != 0L + || writableByUntrusted(directoryMode)) { + throw new IOException("Protected readiness 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 boolean writableByUntrusted(Set permissions) { + return 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 unavailable(); + } + } + + private static List parsePins(String value) { + String[] parts = value.split(",", -1); + if (parts.length == 0 || parts.length > 8) { + throw unavailable(); + } + List pins = new ArrayList<>(parts.length); + for (String pin : parts) { + if (!SHA256.matcher(pin).matches() || pins.contains(pin)) { + throw unavailable(); + } + pins.add(pin); + } + return List.copyOf(pins); + } + + private static boolean expectedHarnessUri(String namespace, String uri) { + return ("spiffe://firemud/ns/" + namespace + "/sa/" + HARNESS_SERVICE_ACCOUNT).equals(uri); + } + + private static String canonicalUuid(String value) { + UUID uuid = UUID.fromString(value); + if (!uuid.toString().equals(value) || new UUID(0L, 0L).equals(uuid)) { + throw unavailable(); + } + return uuid.toString(); + } + + private static long parsePositiveLong(String value) { + try { + long result = Long.parseLong(value); + if (result <= 0L || !Long.toString(result).equals(value)) { + throw unavailable(); + } + return result; + } catch (NumberFormatException ex) { + throw unavailable(); + } + } + + public static String computeBindingDigest( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List pins, + String validatorInstanceId, + long validUntilEpochSecond) { + 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)); + binding.put("validatorId", VALIDATOR_ID); + binding.put("validatorInstanceId", validatorInstanceId); + binding.put("validUntilEpochSecond", validUntilEpochSecond); + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(binding)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException ex) { + throw new IllegalStateException("Readiness binding digest is unavailable"); + } + } + + public static PeerIdentity identifyPeer(java.security.cert.Certificate[] certificates) { + if (certificates == null || certificates.length == 0) { + throw new PeerIdentityRejectedException(); + } + if (!(certificates[0] instanceof X509Certificate certificate)) { + throw new PeerIdentityRejectedException(); + } + try { + certificate.checkValidity(); + Collection> subjectAlternativeNames = certificate.getSubjectAlternativeNames(); + if (subjectAlternativeNames == null) { + throw new PeerIdentityRejectedException(); + } + 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)) { + throw new PeerIdentityRejectedException(); + } + foundUri = uri; + } + if (uriCount != 1 || foundUri == null) { + throw new PeerIdentityRejectedException(); + } + String spki = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(certificate.getPublicKey().getEncoded())); + return new PeerIdentity(foundUri, spki); + } catch (CertificateException | NoSuchAlgorithmException ex) { + throw new PeerIdentityRejectedException(); + } + } + + private static IllegalArgumentException unavailable() { + return new IllegalArgumentException("Readiness trust binding is unavailable"); + } + + public static boolean matchesPeer( + java.security.cert.Certificate[] certificates, Binding binding) { + if (binding == null) { + return false; + } + try { + PeerIdentity peer = identifyPeer(certificates); + return binding.matches(peer); + } catch (RuntimeException rejected) { + return false; + } + } + + public record PeerIdentity(String uri, String spkiSha256) {} + + /** + * Configured per-validator-instance identity; this is not proof of pod UID or fleet inventory. + */ + public record Binding( + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String expectedPeerUri, + List peerSpkiSha256Pins, + String configRevision, + String validatorId, + String validatorInstanceId, + long validUntilEpochSecond, + String bindingDigest) { + public Binding { + Objects.requireNonNull(environmentId); + Objects.requireNonNull(clusterId); + Objects.requireNonNull(namespace); + Objects.requireNonNull(expectedClusterIncarnationUid); + Objects.requireNonNull(expectedNamespaceUid); + Objects.requireNonNull(expectedPeerUri); + peerSpkiSha256Pins = List.copyOf(peerSpkiSha256Pins); + Objects.requireNonNull(configRevision); + Objects.requireNonNull(validatorInstanceId); + Objects.requireNonNull(bindingDigest); + if (!ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !ENVIRONMENT.matcher(namespace).matches() + || !REVISION.matcher(configRevision).matches() + || !INSTANCE.matcher(validatorInstanceId).matches() + || !VALIDATOR_ID.equals(validatorId) + || peerSpkiSha256Pins.isEmpty() + || peerSpkiSha256Pins.size() > 8 + || validUntilEpochSecond <= 0L + || !SHA256.matcher(bindingDigest).matches() + || !expectedHarnessUri(namespace, expectedPeerUri) + || !peerSpkiSha256Pins.stream().allMatch(pin -> SHA256.matcher(pin).matches()) + || peerSpkiSha256Pins.stream().distinct().count() != peerSpkiSha256Pins.size()) { + throw unavailable(); + } + UUID clusterUid = UUID.fromString(expectedClusterIncarnationUid); + UUID namespaceUid = UUID.fromString(expectedNamespaceUid); + if (!clusterUid.toString().equals(expectedClusterIncarnationUid) + || !namespaceUid.toString().equals(expectedNamespaceUid) + || clusterUid.equals(new UUID(0L, 0L)) + || namespaceUid.equals(new UUID(0L, 0L))) { + throw unavailable(); + } + String expectedDigest = + computeBindingDigest( + configRevision, + environmentId, + clusterId, + namespace, + expectedClusterIncarnationUid, + expectedNamespaceUid, + expectedPeerUri, + peerSpkiSha256Pins, + validatorInstanceId, + validUntilEpochSecond); + if (!expectedDigest.equals(bindingDigest)) { + throw unavailable(); + } + } + + public boolean isCurrentAt(long nowEpochSecond) { + return nowEpochSecond > 0L && nowEpochSecond < validUntilEpochSecond; + } + + public boolean matches(PeerIdentity peer) { + if (peer == null || !expectedPeerUri.equals(peer.uri())) { + return false; + } + try { + byte[] actual = HexFormat.of().parseHex(peer.spkiSha256()); + boolean matched = false; + for (String pin : peerSpkiSha256Pins) { + matched |= MessageDigest.isEqual(actual, HexFormat.of().parseHex(pin)); + } + return matched; + } catch (IllegalArgumentException malformedPeer) { + return false; + } + } + } + + public static final class PeerIdentityRejectedException extends RuntimeException { + public PeerIdentityRejectedException() { + super("Readiness caller identity is unavailable"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java new file mode 100644 index 0000000000..dbf1c8270b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java @@ -0,0 +1,864 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.net.Inet6Address; +import java.net.InetAddress; +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.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Default-inactive, independently protected expected validator applicability and runtime pins. + * + *

This binding is an operator-installed input, never learned from Kubernetes labels, caller + * claims, a first read, or the readiness plan's partial applicability matrix. It provides no + * readiness, promotion, or per-validator acceptance authority. + */ +public final class AccountJwtValidatorInventoryBinding { + public static final int MAX_BINDING_BYTES = 32 * 1024; + public static final int MAX_RUNTIME_CONFIG_BYTES = 8 * 1024; + public static final Path PROTECTED_BINDING_PATH = + Path.of("/etc/firemud/account-jwt-api/validator-inventory.json"); + private static final Path PROTECTED_ROOT = Path.of("/etc/firemud/account-jwt-api"); + private static final String VERSION = "account-jwt-validator-inventory-binding/v2"; + private static final String RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG"; + private static final Set ROOT_FIELDS = + Set.of( + "version", + "enabled", + "configRevision", + "environmentId", + "clusterId", + "namespace", + "expectedClusterIncarnationUid", + "expectedNamespaceUid", + "apiBindingRevision", + "apiBindingDigest", + "validators", + "bindingDigest"); + private static final Set VALIDATOR_FIELDS = + Set.of( + "validatorId", + "deploymentName", + "deploymentUid", + "selector", + "replicas", + "containerName", + "image", + "jwksUri", + "maxCacheAgeSeconds", + "profiles", + "receiverServiceUri", + "receiverPort", + "receiverPods"); + private static final Set PROFILE_FIELDS = Set.of("tokenProfile", "audience"); + private static final Set RECEIVER_POD_FIELDS = + Set.of("podUid", "podIp", "leafSpkiSha256"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final Pattern DNS_LABEL = Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern ENVIRONMENT = DNS_LABEL; + private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern REVISION = CLUSTER; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + 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 Pattern LABEL_KEY = + Pattern.compile( + "[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?(?:/[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?"); + private static final Pattern LABEL_VALUE = + Pattern.compile("(?:[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,61}[A-Za-z0-9])?)?"); + private static final Pattern PROFILE = Pattern.compile("[a-z][a-z0-9-]{0,63}"); + private static final Pattern AUDIENCE = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}"); + private static final Pattern RECEIVER_SERVICE_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 boolean enabled; + private final String configuredPath; + private final AtomicReference acceptedFile = new AtomicReference<>(); + + /** Creates a disabled binding; production composition must opt in with the one fixed path. */ + public AccountJwtValidatorInventoryBinding() { + this(false, ""); + } + + public AccountJwtValidatorInventoryBinding(boolean enabled, String protectedBindingPath) { + this.enabled = enabled; + String path = protectedBindingPath == null ? "" : protectedBindingPath.trim(); + this.configuredPath = PROTECTED_BINDING_PATH.toString().equals(path) ? path : ""; + } + + /** Returns the exact immutable protected expectations, or empty when disabled/unavailable. */ + public java.util.Optional current() { + if (!enabled || configuredPath.isBlank()) { + return java.util.Optional.empty(); + } + try { + ProtectedFile file = readProtectedFile(PROTECTED_BINDING_PATH); + ProtectedInventory parsed = parseProtectedBytes(file.bytes()); + FileIdentity existing = acceptedFile.get(); + if (existing == null) { + acceptedFile.compareAndSet(null, file.identity()); + existing = acceptedFile.get(); + } + if (!file.identity().equals(existing)) { + throw unavailable(); + } + return java.util.Optional.of(parsed); + } catch (RuntimeException | IOException failure) { + return java.util.Optional.empty(); + } + } + + static ProtectedInventory parseProtectedBytes(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BINDING_BYTES) { + throw unavailable(); + } + try { + JsonNode root = JSON.readTree(decodeUtf8(bytes)); + requireObjectFields(root, ROOT_FIELDS); + if (!VERSION.equals(requiredText(root, "version", 96)) + || !"true".equals(requiredText(root, "enabled", 5))) { + throw unavailable(); + } + String revision = requiredText(root, "configRevision", 128); + String environmentId = requiredText(root, "environmentId", 63); + String clusterId = requiredText(root, "clusterId", 128); + String namespace = requiredText(root, "namespace", 63); + String clusterUid = canonicalUid(requiredText(root, "expectedClusterIncarnationUid", 36)); + String namespaceUid = canonicalUid(requiredText(root, "expectedNamespaceUid", 36)); + String apiRevision = requiredText(root, "apiBindingRevision", 128); + String apiDigest = requiredText(root, "apiBindingDigest", 64); + String digest = requiredText(root, "bindingDigest", 64); + if (!REVISION.matcher(revision).matches() + || !ENVIRONMENT.matcher(environmentId).matches() + || !CLUSTER.matcher(clusterId).matches() + || !DNS_LABEL.matcher(namespace).matches() + || !REVISION.matcher(apiRevision).matches() + || !SHA256.matcher(apiDigest).matches() + || !SHA256.matcher(digest).matches() + || !digest.equals(computeBindingDigest(root))) { + throw unavailable(); + } + List validators = parseValidators(root.get("validators")); + if (validators.isEmpty() || validators.size() > 32) { + throw unavailable(); + } + return new ProtectedInventory( + revision, + environmentId, + clusterId, + namespace, + clusterUid, + namespaceUid, + apiRevision, + apiDigest, + digest, + validators); + } catch (IllegalArgumentException failure) { + throw unavailable(); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + public static String computeBindingDigest(JsonNode root) { + try { + requireObjectFields(root, ROOT_FIELDS); + Map value = new LinkedHashMap<>(); + for (String field : ROOT_FIELDS) { + if (!"bindingDigest".equals(field)) { + JsonNode node = root.get(field); + value.put(field, JSON.readValue(JSON.writeValueAsString(node), Object.class)); + } + } + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException | RuntimeException failure) { + throw unavailable(); + } + } + + private static List parseValidators(JsonNode node) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > 32) { + throw unavailable(); + } + List result = new ArrayList<>(); + Set ids = new LinkedHashSet<>(); + Set deployments = new LinkedHashSet<>(); + Set expectedPodUids = new LinkedHashSet<>(); + Set expectedPodIps = new LinkedHashSet<>(); + Set expectedPodSpkis = new LinkedHashSet<>(); + for (JsonNode validator : node) { + requireObjectFields(validator, VALIDATOR_FIELDS); + String id = requiredText(validator, "validatorId", 63); + String deployment = requiredText(validator, "deploymentName", 63); + String deploymentUid = canonicalUid(requiredText(validator, "deploymentUid", 36)); + String container = requiredText(validator, "containerName", 63); + String image = requiredText(validator, "image", 512); + String jwksUri = canonicalJwksUri(requiredText(validator, "jwksUri", 512)); + int replicas = exactInt(validator.get("replicas"), 1, 128); + int maximumCacheAge = exactInt(validator.get("maxCacheAgeSeconds"), 1, 300); + if (!DNS_LABEL.matcher(id).matches() + || !DNS_LABEL.matcher(deployment).matches() + || !DNS_LABEL.matcher(container).matches() + || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}") + || !ids.add(id) + || !deployments.add(deployment)) { + throw unavailable(); + } + Map selector = parseSelector(validator.get("selector")); + List profiles = parseProfiles(validator.get("profiles")); + if (profiles.isEmpty()) { + throw unavailable(); + } + List receiverPods = + parseReceiverPods(validator.get("receiverPods"), replicas); + for (ReceiverPodPin pin : receiverPods) { + // Validator workloads are distinct expected instances in this closed LOGIN matrix. A + // shared leaf key would make the TLS peer prove only possession by either Pod, not the + // exact Pod UID selected by the owner-observed inventory. + if (!expectedPodUids.add(pin.podUid()) + || !expectedPodIps.add(pin.podIp()) + || !expectedPodSpkis.add(pin.leafSpkiSha256())) { + throw unavailable(); + } + } + String runtimeConfig = canonicalRuntimeConfig(jwksUri, maximumCacheAge, profiles); + if (runtimeConfig.getBytes(StandardCharsets.UTF_8).length > MAX_RUNTIME_CONFIG_BYTES) { + throw unavailable(); + } + result.add( + new ValidatorExpectation( + id, + deployment, + deploymentUid, + selector, + replicas, + container, + image, + jwksUri, + maximumCacheAge, + profiles, + runtimeConfig, + canonicalReceiverServiceUri(requiredText(validator, "receiverServiceUri", 256)), + exactInt(validator.get("receiverPort"), 1, 65535), + receiverPods)); + } + return List.copyOf(result); + } + + private static List parseReceiverPods(JsonNode node, int replicas) { + if (node == null || !node.isArray() || node.size() != replicas || node.size() > 128) { + throw unavailable(); + } + List pins = new ArrayList<>(); + Set podUids = new LinkedHashSet<>(); + Set podIps = new LinkedHashSet<>(); + Set podSpkis = new LinkedHashSet<>(); + String previousUid = null; + for (JsonNode pod : node) { + requireObjectFields(pod, RECEIVER_POD_FIELDS); + String uid = canonicalUid(requiredText(pod, "podUid", 36)); + String ip = canonicalPodIp(requiredText(pod, "podIp", 45)); + String spki = requiredText(pod, "leafSpkiSha256", 64); + if (!SHA256.matcher(spki).matches() + || !podUids.add(uid) + || !podIps.add(ip) + || !podSpkis.add(spki) + || (previousUid != null && previousUid.compareTo(uid) >= 0)) { + throw unavailable(); + } + previousUid = uid; + pins.add(new ReceiverPodPin(uid, ip, spki)); + } + return List.copyOf(pins); + } + + private static String canonicalReceiverServiceUri(String value) { + if (!RECEIVER_SERVICE_URI.matcher(value).matches()) { + throw unavailable(); + } + return value; + } + + public static String canonicalPodIp(String value) { + if (value == null || value.isBlank() || value.indexOf('%') >= 0) { + throw unavailable(); + } + try { + if (value.indexOf(':') < 0) { + String[] components = value.split("\\.", -1); + if (components.length != 4) { + throw unavailable(); + } + for (String component : components) { + if (component.isEmpty() + || (component.length() > 1 && component.charAt(0) == '0') + || !component.matches("[0-9]{1,3}") + || Integer.parseInt(component) > 255) { + throw unavailable(); + } + } + if ("0.0.0.0".equals(value) || "255.255.255.255".equals(value)) { + throw unavailable(); + } + return value; + } + if (!value.matches("[0-9A-Fa-f:]+")) { + throw unavailable(); + } + InetAddress address = InetAddress.getByName(value); + if (!(address instanceof Inet6Address) + || !canonicalIpv6(address.getAddress()).equals(value)) { + throw unavailable(); + } + return value; + } catch (IOException | NumberFormatException failure) { + throw unavailable(); + } + } + + private static String canonicalIpv6(byte[] bytes) { + if (bytes.length != 16) { + throw unavailable(); + } + int[] groups = new int[8]; + for (int index = 0; index < groups.length; index++) { + groups[index] = + Byte.toUnsignedInt(bytes[index * 2]) << 8 | Byte.toUnsignedInt(bytes[index * 2 + 1]); + } + int bestStart = -1; + int bestLength = 1; + for (int index = 0; index < groups.length; ) { + if (groups[index] != 0) { + index++; + continue; + } + int end = index; + while (end < groups.length && groups[end] == 0) { + end++; + } + if (end - index > bestLength) { + bestStart = index; + bestLength = end - index; + } + index = end; + } + StringBuilder canonical = new StringBuilder(); + for (int index = 0; index < groups.length; ) { + if (index == bestStart) { + canonical.append("::"); + index += bestLength; + continue; + } + if (canonical.length() > 0 && canonical.charAt(canonical.length() - 1) != ':') { + canonical.append(':'); + } + canonical.append(Integer.toHexString(groups[index])); + index++; + } + return canonical.toString(); + } + + private static Map parseSelector(JsonNode node) { + if (node == null || !node.isObject() || node.isEmpty() || node.size() > 16) { + throw unavailable(); + } + Map selector = new LinkedHashMap<>(); + for (Map.Entry entry : node.properties()) { + if (!LABEL_KEY.matcher(entry.getKey()).matches() + || !entry.getValue().isTextual() + || !LABEL_VALUE.matcher(entry.getValue().asText()).matches()) { + throw unavailable(); + } + selector.put(entry.getKey(), entry.getValue().asText()); + } + return Map.copyOf(selector); + } + + private static List parseProfiles(JsonNode node) { + if (node == null || !node.isArray() || node.isEmpty() || node.size() > 32) { + throw unavailable(); + } + List profiles = new ArrayList<>(); + Set unique = new LinkedHashSet<>(); + for (JsonNode profile : node) { + requireObjectFields(profile, PROFILE_FIELDS); + String name = requiredText(profile, "tokenProfile", 64); + String audience = requiredText(profile, "audience", 256); + if (!PROFILE.matcher(name).matches() + || !AUDIENCE.matcher(audience).matches() + || !unique.add(name + "\u0000" + audience)) { + throw unavailable(); + } + profiles.add(new ProfileExpectation(name, audience)); + } + profiles.sort( + Comparator.comparing(ProfileExpectation::tokenProfile) + .thenComparing(ProfileExpectation::audience)); + return List.copyOf(profiles); + } + + private static String canonicalRuntimeConfig( + String jwksUri, int maxCacheAgeSeconds, List profiles) { + try { + List> profileValues = + profiles.stream() + .map( + profile -> + Map.of( + "tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .toList(); + Map runtime = + Map.of( + "algorithm", + "RS256", + "jwksUri", + jwksUri, + "maxCacheAgeSeconds", + maxCacheAgeSeconds, + "profiles", + profileValues); + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(runtime)), + StandardCharsets.UTF_8); + } catch (IOException | RuntimeException failure) { + throw unavailable(); + } + } + + private static String canonicalJwksUri(String value) { + try { + java.net.URI uri = java.net.URI.create(value); + if (!"https".equalsIgnoreCase(uri.getScheme()) + || uri.getHost() == null + || uri.getRawUserInfo() != null + || uri.getRawQuery() != null + || uri.getRawFragment() != null + || !"/.well-known/jwks.json".equals(uri.getRawPath())) { + throw unavailable(); + } + return uri.toASCIIString(); + } catch (RuntimeException failure) { + throw unavailable(); + } + } + + private static ProtectedFile readProtectedFile(Path path) throws IOException { + if (!path.equals(PROTECTED_BINDING_PATH) + || Files.isSymbolicLink(path) + || !path.equals(path.toRealPath())) { + throw unavailable(); + } + verifyProtectedDirectoryChain(PROTECTED_ROOT); + BasicFileAttributes before = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Set mode = Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + Object owner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object group = Files.getAttribute(path, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() + || before.size() <= 0 + || before.size() > MAX_BINDING_BYTES + || !(owner instanceof Number uid) + || uid.longValue() != 0L + || !(group instanceof Number gid) + || writable(mode) + || !mode.contains(PosixFilePermission.OWNER_READ) + || mode.contains(PosixFilePermission.OTHERS_READ)) { + throw unavailable(); + } + byte[] bytes = new byte[(int) before.size()]; + try (SeekableByteChannel channel = + Files.newByteChannel(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (channel.read(buffer) < 0) { + throw unavailable(); + } + } + if (channel.read(ByteBuffer.allocate(1)) != -1) { + throw unavailable(); + } + } + BasicFileAttributes after = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + Set afterMode = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + Object afterOwner = Files.getAttribute(path, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Object afterGroup = Files.getAttribute(path, "unix:gid", LinkOption.NOFOLLOW_LINKS); + if (!sameAttributes(before, after) + || !mode.equals(afterMode) + || !Objects.equals(owner, afterOwner) + || !Objects.equals(group, afterGroup)) { + throw unavailable(); + } + FileIdentity identity = + new FileIdentity( + String.valueOf(before.fileKey()), + before.size(), + before.lastModifiedTime().toMillis(), + uid.longValue(), + gid.longValue(), + Set.copyOf(mode), + sha256(bytes)); + return new ProtectedFile(bytes, identity); + } + + private static void verifyProtectedDirectory(Path directory) throws IOException { + if (!directory.equals(directory.toRealPath()) + || !Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS)) { + throw unavailable(); + } + Object owner = Files.getAttribute(directory, "unix:uid", LinkOption.NOFOLLOW_LINKS); + Set mode = + Files.getPosixFilePermissions(directory, LinkOption.NOFOLLOW_LINKS); + if (!(owner instanceof Number uid) + || uid.longValue() != 0L + || mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE)) { + throw unavailable(); + } + } + + static void verifyProtectedDirectoryChain(Path directory) throws IOException { + verifyProtectedDirectoryChain( + directory, AccountJwtValidatorInventoryBinding::verifyProtectedDirectory); + } + + static void verifyProtectedDirectoryChain(Path directory, ProtectedDirectoryVerifier verifier) + throws IOException { + Path normalized = directory.toAbsolutePath().normalize(); + Path canonical = normalized.toRealPath(); + if (!normalized.equals(canonical)) { + throw unavailable(); + } + for (Path current = canonical; current != null; current = current.getParent()) { + verifier.verify(current); + } + } + + @FunctionalInterface + interface ProtectedDirectoryVerifier { + void verify(Path directory) throws IOException; + } + + private static void requireObjectFields(JsonNode node, Set expected) { + if (node == null || !node.isObject() || node.size() != expected.size()) { + throw unavailable(); + } + for (Map.Entry field : node.properties()) { + if (!expected.contains(field.getKey()) + || field.getValue() == null + || field.getValue().isNull()) { + throw unavailable(); + } + } + } + + private static String requiredText(JsonNode node, String field, int maximumLength) { + JsonNode value = node.get(field); + if (value == null + || !value.isTextual() + || value.asText().isBlank() + || value.asText().length() > maximumLength) { + throw unavailable(); + } + return value.asText(); + } + + private static int exactInt(JsonNode node, int minimum, int maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToInt()) { + throw unavailable(); + } + int value = node.intValue(); + if (value < minimum || value > maximum) { + throw unavailable(); + } + return value; + } + + private static String canonicalUid(String uid) { + if (!UID.matcher(uid).matches() || uid.startsWith("00000000-")) { + throw unavailable(); + } + return uid; + } + + 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 failure) { + throw unavailable(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw unavailable(); + } + } + + private static boolean sameAttributes(BasicFileAttributes before, BasicFileAttributes after) { + return after.isRegularFile() + && Objects.equals(before.fileKey(), after.fileKey()) + && before.size() == after.size() + && before.lastModifiedTime().equals(after.lastModifiedTime()); + } + + private static boolean writable(Set mode) { + return mode.contains(PosixFilePermission.OWNER_WRITE) + || mode.contains(PosixFilePermission.GROUP_WRITE) + || mode.contains(PosixFilePermission.OTHERS_WRITE); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Protected Account validator inventory binding is unavailable"); + } + + private record FileIdentity( + String fileKey, + long size, + long modifiedMillis, + long ownerUid, + long groupId, + Set permissions, + String contentSha256) {} + + private record ProtectedFile(byte[] bytes, FileIdentity identity) {} + + /** An immutable, file-backed expected inventory; no public constructor or mutation exists. */ + public static final class ProtectedInventory { + private final String configRevision; + private final String environmentId; + private final String clusterId; + private final String namespace; + private final String expectedClusterIncarnationUid; + private final String expectedNamespaceUid; + private final String apiBindingRevision; + private final String apiBindingDigest; + private final String bindingDigest; + private final List validators; + + private ProtectedInventory( + String configRevision, + String environmentId, + String clusterId, + String namespace, + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String bindingDigest, + List validators) { + this.configRevision = configRevision; + this.environmentId = environmentId; + this.clusterId = clusterId; + this.namespace = namespace; + this.expectedClusterIncarnationUid = expectedClusterIncarnationUid; + this.expectedNamespaceUid = expectedNamespaceUid; + this.apiBindingRevision = apiBindingRevision; + this.apiBindingDigest = apiBindingDigest; + this.bindingDigest = bindingDigest; + this.validators = List.copyOf(validators); + } + + public boolean matchesApiBinding(AccountJwtJwksApiBinding.ParsedBinding binding) { + return binding != null + && configRevision != null + && environmentId.equals(binding.environmentId()) + && clusterId.equals(binding.clusterId()) + && namespace.equals(binding.namespace()) + && expectedClusterIncarnationUid.equals(binding.expectedClusterIncarnationUid()) + && expectedNamespaceUid.equals(binding.expectedNamespaceUid()) + && apiBindingRevision.equals(binding.configRevision()) + && apiBindingDigest.equals(binding.bindingDigest()); + } + + public String configRevision() { + return configRevision; + } + + public String environmentId() { + return environmentId; + } + + public String clusterId() { + return clusterId; + } + + public String namespace() { + return namespace; + } + + public String expectedClusterIncarnationUid() { + return expectedClusterIncarnationUid; + } + + public String expectedNamespaceUid() { + return expectedNamespaceUid; + } + + public String apiBindingRevision() { + return apiBindingRevision; + } + + public String apiBindingDigest() { + return apiBindingDigest; + } + + public String bindingDigest() { + return bindingDigest; + } + + public List validators() { + return validators; + } + } + + public static final class ValidatorExpectation { + private final String validatorId; + private final String deploymentName; + private final String deploymentUid; + private final Map selector; + private final int replicas; + private final String containerName; + private final String image; + private final String jwksUri; + private final int maxCacheAgeSeconds; + private final List profiles; + private final String canonicalRuntimeConfig; + private final String receiverServiceUri; + private final int receiverPort; + private final List receiverPods; + + private ValidatorExpectation( + String validatorId, + String deploymentName, + String deploymentUid, + Map selector, + int replicas, + String containerName, + String image, + String jwksUri, + int maxCacheAgeSeconds, + List profiles, + String canonicalRuntimeConfig, + String receiverServiceUri, + int receiverPort, + List receiverPods) { + this.validatorId = validatorId; + this.deploymentName = deploymentName; + this.deploymentUid = deploymentUid; + this.selector = Map.copyOf(selector); + this.replicas = replicas; + this.containerName = containerName; + this.image = image; + this.jwksUri = jwksUri; + this.maxCacheAgeSeconds = maxCacheAgeSeconds; + this.profiles = List.copyOf(profiles); + this.canonicalRuntimeConfig = canonicalRuntimeConfig; + this.receiverServiceUri = receiverServiceUri; + this.receiverPort = receiverPort; + this.receiverPods = List.copyOf(receiverPods); + } + + public String validatorId() { + return validatorId; + } + + public String deploymentName() { + return deploymentName; + } + + public String deploymentUid() { + return deploymentUid; + } + + public Map selector() { + return selector; + } + + public int replicas() { + return replicas; + } + + public String containerName() { + return containerName; + } + + public String image() { + return image; + } + + public String jwksUri() { + return jwksUri; + } + + public int maxCacheAgeSeconds() { + return maxCacheAgeSeconds; + } + + public List profiles() { + return profiles; + } + + public String canonicalRuntimeConfig() { + return canonicalRuntimeConfig; + } + + public String receiverServiceUri() { + return receiverServiceUri; + } + + public int receiverPort() { + return receiverPort; + } + + public List receiverPods() { + return receiverPods; + } + } + + public record ReceiverPodPin(String podUid, String podIp, String leafSpkiSha256) {} + + public record ProfileExpectation(String tokenProfile, String audience) {} +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBinding.java new file mode 100644 index 0000000000..83ad16d083 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBinding.java @@ -0,0 +1,29 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.regex.Pattern; + +/** Keyed, versioned credential-request identity persisted with one gameplay LOGIN operation. */ +public record AccountGameplayCredentialRequestBinding( + int digestSchemaVersion, String digestKeyId, String credentialRequestDigest) { + private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,32}"); + private static final Pattern HMAC_SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public AccountGameplayCredentialRequestBinding { + if (digestSchemaVersion != 1) { + throw new IllegalArgumentException("Unsupported credential digest schema version"); + } + if (digestKeyId == null || !KEY_ID.matcher(digestKeyId).matches()) { + throw new IllegalArgumentException("Credential digest key identifier is malformed"); + } + Objects.requireNonNull(credentialRequestDigest, "Credential request digest is required"); + if (!HMAC_SHA256.matcher(credentialRequestDigest).matches()) { + throw new IllegalArgumentException("Credential request digest is malformed"); + } + } + + @Override + public String toString() { + return "AccountGameplayCredentialRequestBinding[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java new file mode 100644 index 0000000000..d099d926e4 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentity.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.accountservice.repository; + +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; + +/** + * Immutable pending-issuance identity data; this value is not signing or authorization evidence. + */ +public record AccountGameplayDelegationPendingIdentity( + UUID operationId, + UUID requestId, + UUID accountId, + String callerWorkload, + UUID callerContextId, + AccountGameplayCredentialRequestBinding credentialRequestBinding, + String requestDigest, + UUID tokenJti, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond) { + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + + public AccountGameplayDelegationPendingIdentity { + Objects.requireNonNull(operationId); + Objects.requireNonNull(requestId); + Objects.requireNonNull(accountId); + Objects.requireNonNull(callerContextId); + Objects.requireNonNull(credentialRequestBinding); + Objects.requireNonNull(tokenJti); + if (requestDigest == null || !SHA256.matcher(requestDigest).matches()) { + throw new IllegalArgumentException("Request digest is malformed"); + } + if (callerWorkload == null || callerWorkload.length() > 256) { + throw new IllegalArgumentException("Caller workload is malformed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java new file mode 100644 index 0000000000..515bde1777 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java @@ -0,0 +1,1298 @@ +package net.firedevops.firemud.accountservice.repository; + +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.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +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.PromotionOperationEvidence; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Immutable Account-owned evidence for the fixed public JWT ConfigMap projection. + * + *

Every write re-locks the current desired-state row, generation operation, and exact generation + * result through {@link AccountJwtSignerDesiredStateRepository} before touching these rows. The + * repository records intent before external CAS, and its receipts/observations never authorize + * PREPARED, activation, token issuance, or readiness. + */ +@Repository +public class AccountJwtJwksPublicationRepository { + public static final String PUBLIC_JWKS_NAME = "jwt-jwks"; + public static final String JWKS_DATA_KEY = "jwks.json"; + public static final String GENERATION_MARKER_DATA_KEY = "jwt-generation.json"; + public static final int MAX_JWKS_BYTES = 256 * 1024; + public static final int MAX_MARKER_BYTES = 16 * 1024; + + private static final String INTENT_TABLE = "account_jwt_jwks_prepublication_intents"; + private static final String RECEIPT_TABLE = "account_jwt_jwks_publication_receipts"; + private static final String MOUNT_TABLE = "account_jwt_jwks_mount_observations"; + private static final String CUSTODY_MODE = "INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK"; + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtJwksPublicationRepository( + DSLContext dsl, AccountJwtSignerDesiredStateRepository desiredStateRepository) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required"); + } + + /** + * Returns the current operation's immutable intent, locking its entire owner chain first. A + * missing intent stays missing; reads never create a publication request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentIntent(Binding binding, TrustFence trust) { + requireWritableAccountTransaction(); + GenerationResult result = readAndLockCurrentResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(result.operationId(), true); + if (intent == null) { + return Optional.empty(); + } + verifyIntentMatches(result, request, intent); + return Optional.of(intent); + } + + /** + * Persists the exact Account-constructed public projection before remote ConfigMap CAS. Only an + * exact same-operation retry can read back the existing row; a changed prior object, public + * bytes, API trust identity, generation result, or active fence is a conflict. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PrepublicationIntent recordPrepublicationIntent( + Binding binding, + TrustFence trust, + GenerationResult expectedResult, + GenerationRequest expectedRequest, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String jwksJson, + String generationMarkerJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedResult, "Exact current generation result is required"); + Objects.requireNonNull(expectedRequest, "Exact current generation request is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireDigest(expectedSnapshotDigest, "expected ConfigMap snapshot digest"); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + + GenerationResult currentResult = readAndLockCurrentResult(binding, trust); + GenerationRequest currentRequest = + desiredStateRepository.readCurrentGenerationRequest(binding, trust); + requireExactGeneration(expectedResult, currentResult, expectedRequest, currentRequest); + PrepublicationIntent candidate = + PrepublicationIntent.create( + currentResult, + currentRequest, + apiBindingDigest, + apiConfigRevision, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + jwksJson, + generationMarkerJson); + + PrepublicationIntent existing = selectIntent(currentResult.operationId(), true); + if (existing != null) { + verifyIntentMatches(currentResult, currentRequest, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account JWT JWKS publication intent changed for the same operation"); + } + return existing; + } + + insertIntent(candidate); + PrepublicationIntent readback = selectIntent(currentResult.operationId(), true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS publication intent did not read back exactly"); + } + return readback; + } + + /** Returns the current operation's persisted intent and optional exact API readback receipt. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPublication(Binding binding, TrustFence trust) { + requireWritableAccountTransaction(); + GenerationResult result = readAndLockCurrentResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(result.operationId(), true); + if (intent == null) { + return Optional.empty(); + } + verifyIntentMatches(result, request, intent); + PublicationReceipt receipt = selectReceipt(result.operationId(), true); + if (receipt != null) { + verifyReceiptMatches(intent, receipt); + } + MountObservation mount = selectMountObservation(result.operationId(), true); + if (mount != null) { + if (receipt == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWKS observation has no Account publication receipt"); + } + verifyMountMatches(intent, receipt, mount); + } + return Optional.of( + new PublicationEvidence(intent, Optional.ofNullable(receipt), Optional.ofNullable(mount))); + } + + /** + * Recovery-only read of the immutable publication that authorized the exact PREPARED source + * generation. Ordinary current-publication reads remain unavailable while PREPARED. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PromotionPublicationEvidence readPreparedPublicationForRecovery( + Binding binding, TrustFence trust) { + requireWritableAccountTransaction(); + PreparedGenerationEvidence prepared = + desiredStateRepository.readPreparedGenerationForRecovery(binding, trust); + GenerationResult result = prepared.generationResult(); + PrepublicationIntent intent = selectIntent(result.operationId(), false); + PublicationReceipt receipt = selectReceipt(result.operationId(), false); + MountObservation mount = selectMountObservation(result.operationId(), false); + if (intent == null || receipt == null || mount == null) { + throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( + "Prepared generation has no exact public prepublication/readback/mount evidence"); + } + verifyPreparedIntentMatches(prepared, intent); + verifyReceiptMatches(intent, receipt); + verifyMountMatches(intent, receipt, mount); + PromotionOperationEvidence promotion = prepared.promotion(); + if (!promotion.prepublicationIntentDigest().equals(intent.intentDigest()) + || !promotion.prepublicationReceiptDigest().equals(receipt.receiptDigest()) + || !promotion.mountedObservationDigest().equals(mount.observationDigest()) + || !promotion.publicConfigMapUid().equals(intent.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(receipt.observedResourceVersion()) + || !promotion.apiBindingDigest().equals(intent.apiBindingDigest()) + || !promotion.apiConfigRevision().equals(intent.apiConfigRevision()) + || !promotion.expectedPublicJwksJson().equals(intent.jwksJson())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Prepared promotion no longer matches its immutable prepublication evidence"); + } + return new PromotionPublicationEvidence(intent, receipt, mount); + } + + /** + * Persists only an exact GET readback from the protected CAS client. No Kubernetes response body, + * bearer token, or private key is stored. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PublicationReceipt recordPublicationReceipt( + Binding binding, + TrustFence trust, + UUID operationId, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String returnedResourceVersion, + String jwksJson, + String generationMarkerJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(returnedResourceVersion, "observed ConfigMap resourceVersion"); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + + GenerationResult result = readAndLockCurrentResult(binding, trust); + if (!result.operationId().equals(operationId)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Account JWT JWKS receipt is not for the current generation operation"); + } + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + PrepublicationIntent intent = selectIntent(operationId, true); + if (intent == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS publication intent is missing"); + } + verifyIntentMatches(result, request, intent); + if (!intent.apiBindingDigest().equals(apiBindingDigest) + || !intent.apiConfigRevision().equals(apiConfigRevision) + || !intent.configMapUid().equals(configMapUid) + || !intent.jwksJson().equals(jwksJson) + || !intent.generationMarkerJson().equals(generationMarkerJson)) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Account JWT JWKS readback does not match the protected publication intent"); + } + + PublicationReceipt candidate = PublicationReceipt.create(intent, returnedResourceVersion); + PublicationReceipt existing = selectReceipt(operationId, true); + if (existing != null) { + verifyReceiptMatches(intent, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Account JWT JWKS readback changed for the same operation"); + } + return existing; + } + insertReceipt(candidate); + PublicationReceipt readback = selectReceipt(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt did not read back exactly"); + } + return readback; + } + + /** + * Records a local mounted private/public correspondence result only after the exact same + * operation has a persisted API publication receipt. This observation remains non-authorizing. + */ + @Transactional(propagation = Propagation.MANDATORY) + public MountObservation recordMountedCorrespondence( + Binding binding, + TrustFence trust, + UUID operationId, + String generationMarkerDigest, + String mountedPublicDataDigest, + String localPublicKeyFingerprint) { + requireWritableAccountTransaction(); + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(generationMarkerDigest, "mounted generation marker digest"); + requireDigest(mountedPublicDataDigest, "mounted public projection digest"); + requireDigest(localPublicKeyFingerprint, "mounted public-key fingerprint"); + + GenerationResult result = readAndLockCurrentResult(binding, trust); + if (!result.operationId().equals(operationId)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Mounted JWT correspondence is not for the current generation operation"); + } + PrepublicationIntent intent = selectIntent(operationId, true); + PublicationReceipt receipt = selectReceipt(operationId, true); + if (intent == null || receipt == null) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence has no Account publication receipt"); + } + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + verifyIntentMatches(result, request, intent); + verifyReceiptMatches(intent, receipt); + if (!intent.generationMarkerDigest().equals(generationMarkerDigest) + || !intent.publicDataDigest().equals(mountedPublicDataDigest) + || !result.publicKeyFingerprint().equals(localPublicKeyFingerprint)) { + throw new AccountJwtSignerDesiredStateRepository.BindingMismatchException( + "Mounted JWT correspondence does not match Account's exact publication"); + } + + MountObservation candidate = MountObservation.create(intent, receipt); + MountObservation existing = selectMountObservation(operationId, true); + if (existing != null) { + verifyMountMatches(intent, receipt, existing); + if (!existing.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Mounted JWT correspondence changed for the same operation"); + } + return existing; + } + insertMountObservation(candidate, binding); + MountObservation readback = selectMountObservation(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence did not read back exactly"); + } + return readback; + } + + private GenerationResult readAndLockCurrentResult(Binding binding, TrustFence trust) { + GenerationResult result = desiredStateRepository.readCurrentGenerationResult(binding, trust); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED + || !request.operationId().equals(result.operationId()) + || !request.operationDigest().equals(result.operationDigest()) + || !request.generationReceiptDigest().equals(result.receiptDigest()) + || !request.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !request.publicJwkJson().equals(result.publicJwkJson()) + || !request.trustFence().equals(trust)) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT publication is not bound to a complete current generation result"); + } + return result; + } + + private static void requireExactGeneration( + GenerationResult expectedResult, + GenerationResult currentResult, + GenerationRequest expectedRequest, + GenerationRequest currentRequest) { + if (!expectedResult.equals(currentResult) || !expectedRequest.equals(currentRequest)) { + throw new AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException( + "Account JWT publication candidate is not the exact current generation result"); + } + } + + private PrepublicationIntent selectIntent(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "desired_state_version, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, api_binding_digest, api_config_revision, " + + "config_map_name, config_map_uid, expected_resource_version, expected_snapshot_digest, " + + "target_generation, target_kid, public_key_fingerprint, expected_durable_active_json, " + + "expected_published_active_json, jwks_json, generation_marker_json, public_data_digest, " + + "generation_marker_digest, intent_digest FROM " + + INTENT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeIntent(row); + } + + private PublicationReceipt selectReceipt(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, config_map_uid, expected_resource_version, " + + "observed_resource_version, public_data_digest, receipt_digest FROM " + + RECEIPT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeReceipt(row); + } + + private MountObservation selectMountObservation(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, intent_digest, publication_receipt_digest, " + + "generation_marker_digest, public_data_digest, public_key_fingerprint, " + + "observation_digest FROM " + + MOUNT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeMountObservation(row); + } + + private void insertIntent(PrepublicationIntent intent) { + int inserted = + dsl.execute( + "INSERT INTO " + + INTENT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "desired_state_version, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, api_binding_digest, api_config_revision, " + + "config_map_name, config_map_uid, expected_resource_version, expected_snapshot_digest, " + + "target_generation, target_kid, public_key_fingerprint, expected_durable_active_json, " + + "expected_published_active_json, jwks_json, generation_marker_json, public_data_digest, " + + "generation_marker_digest, intent_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'jwt-jwks', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + intent.operationId(), + intent.binding().environmentId(), + intent.binding().clusterId(), + intent.binding().namespace(), + CUSTODY_MODE, + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + UUID.fromString(intent.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(intent.trustFence().expectedNamespaceUid()), + intent.trustFence().bindingDigest(), + intent.trustFence().configRevision(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + UUID.fromString(intent.configMapUid()), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + Long.parseLong(intent.targetGeneration()), + intent.targetKid(), + intent.publicKeyFingerprint(), + activeJson(intent.expectedDurableActive()), + activeJson(intent.expectedPublishedActive()), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + intent.intentDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS intent insert was ambiguous"); + } + } + + private void insertReceipt(PublicationReceipt receipt) { + int inserted = + dsl.execute( + "INSERT INTO " + + RECEIPT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, config_map_uid, expected_resource_version, " + + "observed_resource_version, public_data_digest, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.operationId(), + receipt.binding().environmentId(), + receipt.binding().clusterId(), + receipt.binding().namespace(), + receipt.binding().mode().value(), + receipt.intentDigest(), + UUID.fromString(receipt.configMapUid()), + receipt.expectedResourceVersion(), + receipt.observedResourceVersion(), + receipt.publicDataDigest(), + receipt.receiptDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS receipt insert was ambiguous"); + } + } + + private void insertMountObservation(MountObservation observation, Binding binding) { + int inserted = + dsl.execute( + "INSERT INTO " + + MOUNT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "intent_digest, publication_receipt_digest, " + + "generation_marker_digest, public_data_digest, public_key_fingerprint, " + + "observation_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + observation.operationId(), + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.mode().value(), + observation.intentDigest(), + observation.publicationReceiptDigest(), + observation.generationMarkerDigest(), + observation.publicDataDigest(), + observation.publicKeyFingerprint(), + observation.observationDigest()); + if (inserted != 1) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account mounted JWT correspondence insert was ambiguous"); + } + } + + private PrepublicationIntent decodeIntent(Record row) { + try { + Binding binding = + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + parseCustodyMode(row.get("custody_mode", String.class))); + return new PrepublicationIntent( + row.get("operation_id", UUID.class), + binding, + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + row.get("generation_receipt_digest", String.class), + positive(row.get("desired_state_version", Long.class), "desired-state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("api_binding_digest", String.class), + row.get("api_config_revision", String.class), + row.get("config_map_name", String.class), + row.get("config_map_uid", UUID.class).toString(), + row.get("expected_resource_version", String.class), + row.get("expected_snapshot_digest", String.class), + Long.toString(positive(row.get("target_generation", Long.class), "target generation")), + row.get("target_kid", String.class), + row.get("public_key_fingerprint", String.class), + parseActive(row.get("expected_durable_active_json", String.class)), + parseActive(row.get("expected_published_active_json", String.class)), + row.get("jwks_json", String.class), + row.get("generation_marker_json", String.class), + row.get("public_data_digest", String.class), + row.get("generation_marker_digest", String.class), + row.get("intent_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS intent is malformed", ex); + } + } + + private PublicationReceipt decodeReceipt(Record row) { + try { + return new PublicationReceipt( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + parseCustodyMode(row.get("custody_mode", String.class))), + row.get("intent_digest", String.class), + row.get("config_map_uid", UUID.class).toString(), + row.get("expected_resource_version", String.class), + row.get("observed_resource_version", String.class), + row.get("public_data_digest", String.class), + row.get("receipt_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt is malformed", ex); + } + } + + private MountObservation decodeMountObservation(Record row) { + try { + return new MountObservation( + row.get("operation_id", UUID.class), + row.get("intent_digest", String.class), + row.get("publication_receipt_digest", String.class), + row.get("generation_marker_digest", String.class), + row.get("public_data_digest", String.class), + row.get("public_key_fingerprint", String.class), + row.get("observation_digest", String.class)); + } catch (RuntimeException ex) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account mounted JWT correspondence is malformed", ex); + } + } + + private static void verifyIntentMatches( + GenerationResult result, GenerationRequest request, PrepublicationIntent intent) { + if (!intent.operationId().equals(result.operationId()) + || !intent.binding().equals(result.binding()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.trustFence().equals(result.trustFence()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(request.expectedActive()) + || !intent.expectedPublishedActive().equals(request.expectedPublishedActive()) + || !PUBLIC_JWKS_NAME.equals(intent.configMapName()) + || !PrepublicationIntent.digest(intent).equals(intent.intentDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS intent no longer matches its current generation result"); + } + } + + private static void verifyPreparedIntentMatches( + PreparedGenerationEvidence prepared, PrepublicationIntent intent) { + GenerationResult result = prepared.generationResult(); + PromotionOperationEvidence promotion = prepared.promotion(); + if (!intent.operationId().equals(result.operationId()) + || !intent.binding().equals(result.binding()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || intent.desiredStateVersion() != result.desiredStateVersion() + || !intent.trustFence().equals(result.trustFence()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(promotion.expectedPreviousActive()) + || !intent.expectedPublishedActive().equals(promotion.expectedPublishedActive()) + || !PUBLIC_JWKS_NAME.equals(intent.configMapName()) + || !PrepublicationIntent.digest(intent).equals(intent.intentDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Prepared Account JWKS intent does not match the exact source generation"); + } + } + + private static void verifyReceiptMatches( + PrepublicationIntent intent, PublicationReceipt receipt) { + if (!receipt.operationId().equals(intent.operationId()) + || !receipt.binding().equals(intent.binding()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !receipt.configMapUid().equals(intent.configMapUid()) + || !receipt.expectedResourceVersion().equals(intent.expectedResourceVersion()) + || !receipt.publicDataDigest().equals(intent.publicDataDigest()) + || !PublicationReceipt.digest(receipt).equals(receipt.receiptDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Account JWT JWKS receipt is not bound to its immutable intent"); + } + } + + private static void verifyMountMatches( + PrepublicationIntent intent, PublicationReceipt receipt, MountObservation observation) { + if (!observation.operationId().equals(intent.operationId()) + || !observation.intentDigest().equals(intent.intentDigest()) + || !observation.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !observation.generationMarkerDigest().equals(intent.generationMarkerDigest()) + || !observation.publicDataDigest().equals(intent.publicDataDigest()) + || !observation.publicKeyFingerprint().equals(intent.publicKeyFingerprint()) + || !MountObservation.digest(observation).equals(observation.observationDigest())) { + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "Mounted JWT correspondence is not bound to its exact Account publication"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException( + "Account JWT JWKS persistence requires the owning Account transaction"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("Account JWT JWKS persistence transaction must be writable"); + } + } + + private static byte[] canonicalJson(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (IOException ex) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account JWT JWKS canonicalization is unavailable"); + } + } + + private static AccountJwtSignerDesiredStateRepository.CustodyMode parseCustodyMode(String value) { + for (AccountJwtSignerDesiredStateRepository.CustodyMode candidate : + AccountJwtSignerDesiredStateRepository.CustodyMode.values()) { + if (candidate.value().equals(value)) { + return candidate; + } + } + throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException( + "JWT signer custody mode is unsupported"); + } + + 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", ex); + } + } + + private static void requireDigest(String value, String field) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireRevision(String value, String field) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(); + } + } catch (RuntimeException ex) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed", ex); + } + } + + private static void requireResourceVersion(String value, String field) { + if (value == null || !RESOURCE_VERSION.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireBounded(String value, int limit, String field) { + if (value == null || value.isBlank() || value.getBytes(StandardCharsets.UTF_8).length > limit) { + throw new IllegalArgumentException("JWT signer " + field + " is missing or oversized"); + } + } + + private static long positive(Long value, String field) { + if (value == null || value <= 0L) { + throw new IllegalArgumentException("JWT signer " + field + " is not positive"); + } + return value; + } + + private static String activeJson(Optional active) { + Map value = new LinkedHashMap<>(); + value.put("present", active.isPresent()); + active.ifPresent( + signer -> { + value.put("generation", signer.generation()); + value.put("kid", signer.kid()); + }); + return new String(canonicalJson(value), StandardCharsets.UTF_8); + } + + private static Optional parseActive(String json) { + try { + tools.jackson.databind.JsonNode node = JSON.readTree(json); + if (node == null || !node.isObject() || !node.has("present")) { + throw new IllegalArgumentException(); + } + if (node.size() == 1 + && node.get("present").isBoolean() + && !node.get("present").booleanValue()) { + return Optional.empty(); + } + if (node.size() == 3 + && node.get("present").isBoolean() + && node.get("present").booleanValue() + && node.get("generation").isTextual() + && node.get("kid").isTextual()) { + return Optional.of( + new ActiveSigner(node.get("generation").textValue(), node.get("kid").textValue())); + } + throw new IllegalArgumentException(); + } catch (Exception ex) { + throw new IllegalArgumentException("JWT signer active fence is malformed", ex); + } + } + + /** Fixed non-secret Account intent recorded before an external ConfigMap CAS. */ + public record PrepublicationIntent( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest, + String intentDigest) { + public PrepublicationIntent { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + Objects.requireNonNull(binding, "Account JWT signer binding is required"); + requireDigest(operationDigest, "operation digest"); + requireDigest(generationRequestDigest, "generation request digest"); + requireDigest(generationReceiptDigest, "generation receipt digest"); + if (desiredStateVersion <= 1L) { + throw new IllegalArgumentException("JWT signer desired-state version is invalid"); + } + Objects.requireNonNull(trustFence, "JWT signer trust fence is required"); + requireDigest(apiBindingDigest, "protected ConfigMap API binding digest"); + requireRevision(apiConfigRevision, "protected ConfigMap API configuration revision"); + if (!PUBLIC_JWKS_NAME.equals(configMapName)) { + throw new IllegalArgumentException("JWT signer public ConfigMap name is not fixed"); + } + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireDigest(expectedSnapshotDigest, "expected ConfigMap snapshot digest"); + if (targetGeneration == null || !targetGeneration.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("JWT signer target generation is malformed"); + } + if (targetKid == null || !targetKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("JWT signer target kid is malformed"); + } + requireDigest(publicKeyFingerprint, "public-key fingerprint"); + expectedDurableActive = Objects.requireNonNull(expectedDurableActive); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + requireDigest(publicDataDigest, "public data digest"); + requireDigest(generationMarkerDigest, "generation marker digest"); + requireDigest(intentDigest, "prepublication intent digest"); + if (!publicDataDigest.equals( + AccountJwtJwksPublicationRepository.publicDataDigest(jwksJson, generationMarkerJson)) + || !generationMarkerDigest.equals(digestUtf8(generationMarkerJson))) { + throw new IllegalArgumentException("JWT signer public projection digest is invalid"); + } + if (!intentDigest.equals( + digest( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest))) { + throw new IllegalArgumentException("JWT signer prepublication intent digest is invalid"); + } + } + + public static PrepublicationIntent create( + GenerationResult result, + GenerationRequest request, + String apiBindingDigest, + String apiConfigRevision, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String jwksJson, + String generationMarkerJson) { + return create( + result.operationId(), + result.binding(), + result.operationDigest(), + result.generationRequestDigest(), + result.receiptDigest(), + result.desiredStateVersion(), + result.trustFence(), + apiBindingDigest, + apiConfigRevision, + PUBLIC_JWKS_NAME, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + result.targetGeneration(), + result.targetKid(), + result.publicKeyFingerprint(), + request.expectedActive(), + request.expectedPublishedActive(), + jwksJson, + generationMarkerJson, + AccountJwtJwksPublicationRepository.publicDataDigest(jwksJson, generationMarkerJson), + digestUtf8(generationMarkerJson)); + } + + public static PrepublicationIntent create( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest) { + String intentDigest = + digest( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest); + return new PrepublicationIntent( + operationId, + binding, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + trustFence, + apiBindingDigest, + apiConfigRevision, + configMapName, + configMapUid, + expectedResourceVersion, + expectedSnapshotDigest, + targetGeneration, + targetKid, + publicKeyFingerprint, + expectedDurableActive, + expectedPublishedActive, + jwksJson, + generationMarkerJson, + publicDataDigest, + generationMarkerDigest, + intentDigest); + } + + static String digest(PrepublicationIntent value) { + return digest( + value.operationId(), + value.binding(), + value.operationDigest(), + value.generationRequestDigest(), + value.generationReceiptDigest(), + value.desiredStateVersion(), + value.trustFence(), + value.apiBindingDigest(), + value.apiConfigRevision(), + value.configMapName(), + value.configMapUid(), + value.expectedResourceVersion(), + value.expectedSnapshotDigest(), + value.targetGeneration(), + value.targetKid(), + value.publicKeyFingerprint(), + value.expectedDurableActive(), + value.expectedPublishedActive(), + value.jwksJson(), + value.generationMarkerJson(), + value.publicDataDigest(), + value.generationMarkerDigest()); + } + + private static String digest( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + TrustFence trustFence, + String apiBindingDigest, + String apiConfigRevision, + String configMapName, + String configMapUid, + String expectedResourceVersion, + String expectedSnapshotDigest, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + Optional expectedDurableActive, + Optional expectedPublishedActive, + String jwksJson, + String generationMarkerJson, + String publicDataDigest, + String generationMarkerDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-prepublication-intent/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("environmentId", binding.environmentId()); + preimage.put("clusterId", binding.clusterId()); + preimage.put("namespace", binding.namespace()); + preimage.put("custodyMode", CUSTODY_MODE); + preimage.put("operationDigest", operationDigest); + preimage.put("generationRequestDigest", generationRequestDigest); + preimage.put("generationReceiptDigest", generationReceiptDigest); + preimage.put("desiredStateVersion", desiredStateVersion); + preimage.put("expectedClusterIncarnationUid", trustFence.expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", trustFence.expectedNamespaceUid()); + preimage.put("trustBindingDigest", trustFence.bindingDigest()); + preimage.put("trustConfigRevision", trustFence.configRevision()); + preimage.put("apiBindingDigest", apiBindingDigest); + preimage.put("apiConfigRevision", apiConfigRevision); + preimage.put("configMapName", configMapName); + preimage.put("configMapUid", configMapUid); + preimage.put("expectedResourceVersion", expectedResourceVersion); + preimage.put("expectedSnapshotDigest", expectedSnapshotDigest); + preimage.put("targetGeneration", targetGeneration); + preimage.put("targetKid", targetKid); + preimage.put("publicKeyFingerprint", publicKeyFingerprint); + preimage.put( + "expectedDurableActive", expectedDurableActive.map(ActiveSigner::generation).orElse("")); + preimage.put( + "expectedDurableActiveKid", expectedDurableActive.map(ActiveSigner::kid).orElse("")); + preimage.put( + "expectedPublishedActive", + expectedPublishedActive.map(ActiveSigner::generation).orElse("")); + preimage.put( + "expectedPublishedActiveKid", expectedPublishedActive.map(ActiveSigner::kid).orElse("")); + preimage.put("jwksJson", jwksJson); + preimage.put("generationMarkerJson", generationMarkerJson); + preimage.put("publicDataDigest", publicDataDigest); + preimage.put("generationMarkerDigest", generationMarkerDigest); + return sha256(canonicalJson(preimage)); + } + } + + /** Exact ConfigMap readback; it proves publication only, never activation/readiness. */ + public record PublicationReceipt( + UUID operationId, + Binding binding, + String intentDigest, + String configMapUid, + String expectedResourceVersion, + String observedResourceVersion, + String publicDataDigest, + String receiptDigest) { + public PublicationReceipt { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + Objects.requireNonNull(binding, "Account JWT signer binding is required"); + requireDigest(intentDigest, "prepublication intent digest"); + requireUuid(configMapUid, "public ConfigMap UID"); + requireResourceVersion(expectedResourceVersion, "expected ConfigMap resourceVersion"); + requireResourceVersion(observedResourceVersion, "observed ConfigMap resourceVersion"); + requireDigest(publicDataDigest, "published public data digest"); + requireDigest(receiptDigest, "publication receipt digest"); + if (expectedResourceVersion.equals(observedResourceVersion)) { + throw new IllegalArgumentException("Account JWT ConfigMap resourceVersion did not advance"); + } + if (!receiptDigest.equals( + digest( + operationId, + binding, + intentDigest, + configMapUid, + expectedResourceVersion, + observedResourceVersion, + publicDataDigest))) { + throw new IllegalArgumentException("Account JWT publication receipt digest is invalid"); + } + } + + public static PublicationReceipt create( + PrepublicationIntent intent, String observedResourceVersion) { + String receiptDigest = + digest( + intent.operationId(), + intent.binding(), + intent.intentDigest(), + intent.configMapUid(), + intent.expectedResourceVersion(), + observedResourceVersion, + intent.publicDataDigest()); + return new PublicationReceipt( + intent.operationId(), + intent.binding(), + intent.intentDigest(), + intent.configMapUid(), + intent.expectedResourceVersion(), + observedResourceVersion, + intent.publicDataDigest(), + receiptDigest); + } + + static String digest(PublicationReceipt value) { + return digest( + value.operationId(), + value.binding(), + value.intentDigest(), + value.configMapUid(), + value.expectedResourceVersion(), + value.observedResourceVersion(), + value.publicDataDigest()); + } + + private static String digest( + UUID operationId, + Binding binding, + String intentDigest, + String configMapUid, + String expectedResourceVersion, + String observedResourceVersion, + String publicDataDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-publication-receipt/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("environmentId", binding.environmentId()); + preimage.put("clusterId", binding.clusterId()); + preimage.put("namespace", binding.namespace()); + preimage.put("custodyMode", CUSTODY_MODE); + preimage.put("intentDigest", intentDigest); + preimage.put("configMapUid", configMapUid); + preimage.put("expectedResourceVersion", expectedResourceVersion); + preimage.put("observedResourceVersion", observedResourceVersion); + preimage.put("publicDataDigest", publicDataDigest); + return sha256(canonicalJson(preimage)); + } + } + + /** Non-secret Account-local observation of the published private/public mounted projection. */ + public record MountObservation( + UUID operationId, + String intentDigest, + String publicationReceiptDigest, + String generationMarkerDigest, + String publicDataDigest, + String publicKeyFingerprint, + String observationDigest) { + public MountObservation { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + requireDigest(intentDigest, "prepublication intent digest"); + requireDigest(publicationReceiptDigest, "publication receipt digest"); + requireDigest(generationMarkerDigest, "generation marker digest"); + requireDigest(publicDataDigest, "mounted public data digest"); + requireDigest(publicKeyFingerprint, "mounted public-key fingerprint"); + requireDigest(observationDigest, "mounted observation digest"); + if (!observationDigest.equals( + digest( + operationId, + intentDigest, + publicationReceiptDigest, + generationMarkerDigest, + publicDataDigest, + publicKeyFingerprint))) { + throw new IllegalArgumentException("Mounted JWT observation digest is invalid"); + } + } + + public static MountObservation create(PrepublicationIntent intent, PublicationReceipt receipt) { + String observationDigest = + digest( + intent.operationId(), + intent.intentDigest(), + receipt.receiptDigest(), + intent.generationMarkerDigest(), + intent.publicDataDigest(), + intent.publicKeyFingerprint()); + return new MountObservation( + intent.operationId(), + intent.intentDigest(), + receipt.receiptDigest(), + intent.generationMarkerDigest(), + intent.publicDataDigest(), + intent.publicKeyFingerprint(), + observationDigest); + } + + static String digest(MountObservation value) { + return digest( + value.operationId(), + value.intentDigest(), + value.publicationReceiptDigest(), + value.generationMarkerDigest(), + value.publicDataDigest(), + value.publicKeyFingerprint()); + } + + private static String digest( + UUID operationId, + String intentDigest, + String publicationReceiptDigest, + String generationMarkerDigest, + String publicDataDigest, + String publicKeyFingerprint) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-jwks-mounted-correspondence/v1"); + preimage.put("operationId", operationId.toString()); + preimage.put("intentDigest", intentDigest); + preimage.put("publicationReceiptDigest", publicationReceiptDigest); + preimage.put("generationMarkerDigest", generationMarkerDigest); + preimage.put("publicDataDigest", publicDataDigest); + preimage.put("publicKeyFingerprint", publicKeyFingerprint); + return sha256(canonicalJson(preimage)); + } + } + + public record PublicationEvidence( + PrepublicationIntent intent, + Optional receipt, + Optional mountedCorrespondence) { + public PublicationEvidence { + Objects.requireNonNull(intent); + receipt = Objects.requireNonNull(receipt); + mountedCorrespondence = Objects.requireNonNull(mountedCorrespondence); + } + } + + public record PromotionPublicationEvidence( + PrepublicationIntent intent, + PublicationReceipt receipt, + MountObservation mountedCorrespondence) { + public PromotionPublicationEvidence { + Objects.requireNonNull(intent); + Objects.requireNonNull(receipt); + Objects.requireNonNull(mountedCorrespondence); + verifyReceiptMatches(intent, receipt); + verifyMountMatches(intent, receipt, mountedCorrespondence); + } + } + + /** Canonical digest of all observed ConfigMap data used as the pre-CAS compare fence. */ + public static String snapshotDigest(Map data) { + Objects.requireNonNull(data, "ConfigMap data is required"); + if (data.size() > 128) { + throw new IllegalArgumentException("JWT public ConfigMap data has too many entries"); + } + long totalBytes = 0L; + Map bounded = new LinkedHashMap<>(); + for (Map.Entry entry : data.entrySet()) { + if (entry.getKey() == null + || entry.getKey().isBlank() + || entry.getKey().length() > 253 + || entry.getValue() == null) { + throw new IllegalArgumentException("JWT public ConfigMap data is malformed"); + } + totalBytes += entry.getKey().getBytes(StandardCharsets.UTF_8).length; + totalBytes += entry.getValue().getBytes(StandardCharsets.UTF_8).length; + if (totalBytes > 1024L * 1024L) { + throw new IllegalArgumentException("JWT public ConfigMap data is oversized"); + } + bounded.put(entry.getKey(), entry.getValue()); + } + return sha256(canonicalJson(bounded)); + } + + public static String publicDataDigest(String jwksJson, String generationMarkerJson) { + requireBounded(jwksJson, MAX_JWKS_BYTES, "public JWKS"); + requireBounded(generationMarkerJson, MAX_MARKER_BYTES, "public generation marker"); + Map data = new LinkedHashMap<>(); + data.put(JWKS_DATA_KEY, jwksJson); + data.put(GENERATION_MARKER_DATA_KEY, generationMarkerJson); + return sha256(canonicalJson(data)); + } + + private static String digestUtf8(String value) { + return sha256(value.getBytes(StandardCharsets.UTF_8)); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java new file mode 100644 index 0000000000..a388fbe206 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java @@ -0,0 +1,4289 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +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.AccountJwtReadinessTrustBinding.PeerIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState; +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.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerSelector; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.PodTarget; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException; +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 net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.PodObservation; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ValidatorObservation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.SignedProbeDigest; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Durable, operation-scoped readiness-probe planning and result evidence for Account's interim + * mounted signer. + * + *

This repository never advances signer lifecycle state. It can record only a validator + * observation already authenticated and verified by the owner-internal readiness service. Every + * operation re-locks and compares the existing desired-state, generation, JWKS publication, and + * mounted-correspondence authorities; probe plans are evidence attached to that owner operation, + * not a second key authority. + */ +@Repository +public class AccountJwtReadinessProbeRepository { + public static final int MAX_VALIDATOR_CACHE_AGE_SECONDS = 300; + public static final int PROBE_LIFETIME_SECONDS = 300; + public static final int MAX_ENTRIES_PER_OPERATION = 256; + public static final int MAX_POD_RECEIPTS_PER_OPERATION = 256; + public static final String INVENTORY_STATUS = "PARTIAL_UNCONFIRMED"; + public static final int INVENTORY_PLAN_VERSION = 2; + + private static final String PLAN_TABLE = "account_jwt_readiness_probe_plans"; + private static final String ENTRY_TABLE = "account_jwt_readiness_probe_entries"; + private static final String DELIVERY_CLAIM_TABLE = "account_jwt_readiness_delivery_claims"; + private static final String EXPECTED_POD_TABLE = "account_jwt_readiness_validator_pods"; + private static final String POD_RECEIPT_TABLE = "account_jwt_readiness_pod_receipts"; + private static final String VALIDATOR_ID = "account-service"; + private static final String CANARY_PROFILE = "account-jwt-readiness-canary"; + private static final String CANARY_AUDIENCE = "firemud-account-jwt-readiness"; + private static final String CONTROL_UI_PROFILE = ControlUiJwtProfileValidator.PROFILE; + private static final String CONTROL_UI_AUDIENCE = ControlUiJwtProfileValidator.AUDIENCE; + private static final String PLAYER_BOOTSTRAP_PROFILE = PlayerBootstrapJwtProfileValidator.PROFILE; + private static final String PLAYER_BOOTSTRAP_AUDIENCE = + PlayerBootstrapJwtProfileValidator.AUDIENCE; + private static final String REPRESENTATIVE_PROFILE = GameSessionAccountDelegationProfile.PROFILE; + private static final String REPRESENTATIVE_AUDIENCE = + GameSessionAccountDelegationProfile.AUDIENCE; + private static final List PRODUCTION_PROFILE_CASES = + List.of( + new ProfileCase(CONTROL_UI_PROFILE, CONTROL_UI_AUDIENCE), + new ProfileCase(PLAYER_BOOTSTRAP_PROFILE, PLAYER_BOOTSTRAP_AUDIENCE), + new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE)); + private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final AccountJwtSignerDesiredStateRepository desiredStateRepository; + private final AccountJwtJwksPublicationRepository publicationRepository; + private final AccountJwtValidatorInventoryRepository inventoryRepository; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators and constructs an in-memory repository; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtReadinessProbeRepository( + DSLContext dsl, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository) { + this( + dsl, + desiredStateRepository, + publicationRepository, + new AccountJwtValidatorInventoryRepository(dsl)); + } + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates trusted Spring collaborators; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtReadinessProbeRepository( + DSLContext dsl, + AccountJwtSignerDesiredStateRepository desiredStateRepository, + AccountJwtJwksPublicationRepository publicationRepository, + AccountJwtValidatorInventoryRepository inventoryRepository) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + this.desiredStateRepository = + Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required"); + this.publicationRepository = + Objects.requireNonNull(publicationRepository, "JWKS publication repository is required"); + this.inventoryRepository = + Objects.requireNonNull(inventoryRepository, "Inventory repository is required"); + } + + /** + * Creates one immutable plan from the exact current Account operation and publication evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan planCurrent(Binding binding, TrustFence trust, Instant plannedAt) { + return planCurrent(binding, trust, plannedAt, Optional.empty()); + } + + /** + * Reads the exact current operation context before protected inventory I/O. The caller must + * return to an Account transaction and recheck this context before persisting or consuming the + * resulting snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ObservationContext readCurrentInventoryObservationContext( + Binding binding, TrustFence trust) { + requireAccountTransaction(); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + ReadinessProbePlan existing = selectPlan(current.request().operationId(), false); + if (existing != null) { + requirePlanMatchesCurrent(readbackPlan(existing, false), current); + } + return observationContext(current); + } + + /** Reads the selected context only while its exact current V2 inventory plan remains current. */ + @Transactional(propagation = Propagation.MANDATORY) + public ObservationContext readCurrentInventoryObservationContext( + Binding binding, TrustFence trust, UUID operationId) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION || !plan.validatorInventoryComplete()) { + throw new ReceiverUnavailableException(); + } + return observationContext(current); + } + + /** + * Creates a still-partial plan bound to the exact Account-owned immutable inventory snapshot. The + * live inventory observation does not establish per-Pod acceptance or promotion evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan planCurrent( + Binding binding, TrustFence trust, Instant plannedAt, InventorySnapshot inventorySnapshot) { + return planCurrent( + binding, trust, plannedAt, Optional.of(Objects.requireNonNull(inventorySnapshot))); + } + + private ReadinessProbePlan planCurrent( + Binding binding, + TrustFence trust, + Instant plannedAt, + Optional inventorySnapshot) { + requireWritableAccountTransaction(); + Objects.requireNonNull(plannedAt, "Probe plan time is required"); + long plannedEpoch = exactEpochSecond(plannedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + UUID operationId = current.request().operationId(); + ReadinessProbePlan existing = selectPlan(operationId, true); + if (existing != null) { + requirePlanMatchesCurrent(existing, current); + if (inventorySnapshot.isPresent()) { + String requestedDigest = inventorySnapshot.orElseThrow().digest(); + if (!existing.inventorySnapshotDigest().equals(Optional.of(requestedDigest))) { + throw new InventoryPlanConflictException(); + } + inventoryRepository.readRequired(requestedDigest, binding, trust); + } + return readbackPlan(existing, true); + } + + Optional snapshotDigest = Optional.empty(); + if (inventorySnapshot.isPresent()) { + InventorySnapshot snapshot = inventorySnapshot.orElseThrow(); + requireObservationContext(current, snapshot); + requireInventorySnapshotWithinPlanWindow(snapshot, plannedEpoch); + AccountJwtValidatorInventoryRepository.StoredSnapshot stored = + inventoryRepository.persistOrReadback(snapshot, binding, trust); + snapshotDigest = Optional.of(stored.digest()); + } + ReadinessProbePlan candidate = + newPlan(current, plannedEpoch, inventorySnapshot, snapshotDigest); + insertPlan(candidate); + for (ProbeEntry entry : candidate.entries()) { + insertEntry(entry, candidate.planVersion()); + } + if (inventorySnapshot.isPresent()) { + for (ExpectedPod expectedPod : expectedPods(candidate, inventorySnapshot.orElseThrow())) { + insertExpectedPod(expectedPod); + } + } + ReadinessProbePlan readback = selectPlan(operationId, true); + if (readback == null) { + throw new StorageUnavailableException("Account JWT readiness probe plan did not read back"); + } + requirePlanMatchesCurrent(readback, current); + if (!candidate.equals(readback)) { + throw new QuarantinedStateException("Account JWT readiness probe plan changed on readback"); + } + return readback; + } + + private static void requireInventorySnapshotWithinPlanWindow( + InventorySnapshot snapshot, long plannedEpoch) { + long observedEpoch; + try { + observedEpoch = snapshot.observedAt().getEpochSecond(); + } catch (RuntimeException failure) { + throw new InventoryPlanConflictException(); + } + if (observedEpoch <= 0L + || observedEpoch > plannedEpoch + || plannedEpoch - observedEpoch > MAX_VALIDATOR_CACHE_AGE_SECONDS) { + throw new InventoryPlanConflictException(); + } + } + + /** + * Durably claims the one transient delivery attempt for this exact current plan before signing. A + * claim is never cleared or reused: a lost response or interrupted attempt remains quarantined. + */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim claimSingleDelivery( + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .Binding + binding, + TrustFence trust, + ReadinessProbePlan expectedPlan, + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding + readinessBinding, + PeerIdentity peer, + Instant claimedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedPlan, "Exact persisted readiness plan is required"); + Objects.requireNonNull(readinessBinding, "Authenticated readiness binding is required"); + Objects.requireNonNull(peer, "TLS-authenticated readiness peer is required"); + long claimedEpoch = exactEpochSecond(claimedAt); + if (!readinessBinding.isCurrentAt(claimedEpoch) + || !readinessBinding.matches(peer) + || !binding.environmentId().equals(readinessBinding.environmentId()) + || !binding.clusterId().equals(readinessBinding.clusterId()) + || !binding.namespace().equals(readinessBinding.namespace()) + || !trust + .expectedClusterIncarnationUid() + .equals(readinessBinding.expectedClusterIncarnationUid()) + || !trust.expectedNamespaceUid().equals(readinessBinding.expectedNamespaceUid())) { + throw new DeliveryClaimRejectedException(); + } + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedPlan.operationId().toString()); + ReadinessProbePlan stored = requireStoredPlan(current); + ReadinessProbePlan currentPlan = readbackPlan(stored, true); + if (!currentPlan.equals(expectedPlan)) { + throw new StaleOperationException( + "Readiness delivery claim does not match the exact current plan"); + } + if (claimedEpoch < currentPlan.notBeforeEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (claimedEpoch >= currentPlan.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + if (currentPlan.entries().isEmpty() + || currentPlan.entries().size() > MAX_ENTRIES_PER_OPERATION + || currentPlan.entries().stream() + .anyMatch( + entry -> + entry.state() != ProbeState.PLANNED + || entry.signingAttemptedAtEpochSecond().isPresent() + || entry.compactTokenSha256().isPresent() + || entry.verificationReceipt().isPresent())) { + throw new DeliveryAlreadyClaimedException(); + } + if (selectDeliveryClaim(currentPlan.operationId(), true) != null) { + throw new DeliveryAlreadyClaimedException(); + } + + DeliveryClaim candidate = + DeliveryClaim.create(currentPlan, trust, readinessBinding, peer, claimedEpoch); + insertDeliveryClaim(candidate); + DeliveryClaim readback = selectDeliveryClaim(candidate.rotationOperationId(), true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account readiness single-delivery claim did not read back exactly"); + } + return readback; + } + + /** Rechecks the immutable one-shot claim immediately before any pending-key signing. */ + @Transactional(propagation = Propagation.MANDATORY) + public DeliveryClaim requireCurrentDeliveryClaim( + Binding binding, + TrustFence trust, + ReadinessProbePlan expectedPlan, + DeliveryClaim expectedClaim, + Instant checkedAt) { + requireAccountTransaction(); + Objects.requireNonNull(expectedPlan, "Exact persisted readiness plan is required"); + Objects.requireNonNull(expectedClaim, "Durable single-delivery claim is required"); + long checkedEpoch = exactEpochSecond(checkedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedPlan.operationId().toString()); + ReadinessProbePlan plan = readbackPlan(requireStoredPlan(current), true); + DeliveryClaim persisted = selectDeliveryClaim(plan.operationId(), true); + if (!plan.equals(expectedPlan) + || persisted == null + || !persisted.equals(expectedClaim) + || !persisted.planDigest().equals(plan.planDigest()) + || !persisted.materializerTrustBindingDigest().equals(trust.bindingDigest()) + || !persisted.materializerTrustConfigRevision().equals(trust.configRevision()) + || !persisted.expectedClusterUid().equals(trust.expectedClusterIncarnationUid()) + || !persisted.expectedNamespaceUid().equals(trust.expectedNamespaceUid()) + || !persisted.targetGeneration().equals(plan.targetGeneration()) + || !persisted.targetKid().equals(plan.targetKid())) { + throw new DeliveryAlreadyClaimedException(); + } + if (checkedEpoch < plan.notBeforeEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (checkedEpoch >= plan.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + return persisted; + } + + /** + * Reads the exact current generation and public publication before PREPARED so the caller can + * authorize that same generation's preparation. The static applicability matrix and immutable + * Deployment inventory snapshot alone are not per-Pod acceptance evidence; partial plans cannot + * satisfy promotion. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPromotionPrerequisites( + Binding binding, TrustFence trust, UUID rotationOperationId) { + return readCurrentPromotionPrerequisites(binding, trust, rotationOperationId, null); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentPromotionPrerequisites( + Binding binding, + TrustFence trust, + UUID rotationOperationId, + InventorySnapshot liveInventory) { + // This is a nonmutating proof read, but it joins the writable lifecycle transaction because + // the existing owner evidence readers lock their rows to fence the adjacent PREPARED CAS. + requireWritableAccountTransaction(); + requireOperationId(rotationOperationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(rotationOperationId)) { + throw new StaleOperationException( + "Readiness prerequisite proof is not for Account's current operation"); + } + ReadinessProbePlan plan = selectPlan(rotationOperationId, false); + if (plan == null) { + throw new MissingPlanException("Current signer generation has no readiness plan"); + } + ReadinessProbePlan stored = readbackPlan(plan, false); + requirePlanMatchesCurrent(stored, current); + if (readinessPlanOutOfWindow(stored)) { + return Optional.empty(); + } + if (!stored.validatorInventoryComplete()) { + return Optional.empty(); + } + if (stored.planVersion() != INVENTORY_PLAN_VERSION || liveInventory == null) { + return Optional.empty(); + } + requireLiveInventoryMatches(stored, binding, trust, liveInventory, observationContext(current)); + if (!hasCompletePodReceiptClosure(stored)) { + return Optional.empty(); + } + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication = + promotionPublicationEvidence(current.publication()); + return Optional.of( + new ReadinessPromotionProof( + stored, + current.result(), + publication, + "protected-validator-inventory:" + liveInventory.digest(), + liveInventory.digest())); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readPromotionProof( + Binding binding, TrustFence trust, UUID rotationOperationId) { + return readPromotionProof(binding, trust, rotationOperationId, null); + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional readPromotionProof( + Binding binding, + TrustFence trust, + UUID rotationOperationId, + InventorySnapshot liveInventory) { + // Recovery evidence is likewise a locked, nonmutating read inside the writable reconciliation + // transaction; do not split these reads into an unlocked read-only snapshot. + requireWritableAccountTransaction(); + requireOperationId(rotationOperationId); + var prepared = desiredStateRepository.readPreparedGenerationForRecovery(binding, trust); + var generation = prepared.generationResult(); + var promotion = prepared.promotion(); + if (!generation.operationId().equals(rotationOperationId) + || !promotion.generationOperationId().equals(rotationOperationId) + || !promotion.binding().equals(binding) + || !promotion.trustFence().equals(trust)) { + throw new StaleOperationException( + "Readiness promotion proof does not match the exact PREPARED generation"); + } + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication = + publicationRepository.readPreparedPublicationForRecovery(binding, trust); + ReadinessProbePlan plan = selectPlan(rotationOperationId, false); + if (plan == null) { + throw new MissingPlanException("Prepared signer generation has no readiness plan"); + } + ReadinessProbePlan stored = readbackPlan(plan, false); + requirePreparedPlanMatches(stored, generation, promotion, publication); + boolean dispatched = promotion.privatePromotionDispatched(); + if (!dispatched && readinessPlanOutOfWindow(stored)) { + return Optional.empty(); + } + if (!stored.validatorInventoryComplete()) { + return Optional.empty(); + } + if (stored.planVersion() != INVENTORY_PLAN_VERSION) { + return Optional.empty(); + } + String inventoryDigest; + if (dispatched) { + inventoryDigest = stored.inventorySnapshotDigest().orElseThrow(); + if (!matchesStoredV2Inventory(stored)) { + return Optional.empty(); + } + } else { + if (liveInventory == null) { + return Optional.empty(); + } + requireLiveInventoryMatches( + stored, + binding, + trust, + liveInventory, + observationContext( + generation.operationId(), generation.operationDigest(), stored.expectedFence())); + inventoryDigest = liveInventory.digest(); + } + if (!hasCompletePodReceiptClosure(stored)) { + return Optional.empty(); + } + ReadinessPromotionProof proof = + new ReadinessPromotionProof( + stored, + generation, + publication, + "protected-validator-inventory:" + inventoryDigest, + inventoryDigest); + if (!promotion.readinessEvidenceDigest().equals(proof.readinessEvidenceDigest())) { + throw new QuarantinedStateException( + "Recovered readiness proof differs from the immutable PREPARED evidence"); + } + return Optional.of(proof); + } + + private boolean readinessPlanOutOfWindow(ReadinessProbePlan plan) { + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null) { + throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( + "Account readiness database clock readback is unavailable"); + } + return databaseNow < plan.notBeforeEpochSecond() || databaseNow >= plan.expiresAtEpochSecond(); + } + + /** Reads one plan only while its original generation and publication evidence remain current. */ + @Transactional(propagation = Propagation.MANDATORY) + public ReadinessProbePlan readCurrentPlan(Binding binding, TrustFence trust, UUID operationId) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(operationId)) { + throw new StaleOperationException( + "Readiness probe plan is not for Account's current operation"); + } + ReadinessProbePlan stored = selectPlan(operationId, true); + if (stored == null) { + throw new MissingPlanException("Account JWT readiness probe plan is missing"); + } + requirePlanMatchesCurrent(stored, current); + return readbackPlan(stored, true); + } + + /** Reads one exact current probe selected by the complete key and its immutable JTI. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry readCurrentEntry( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti) { + requireAccountTransaction(); + requireOperationId(operationId); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != 1) { + throw new ReceiverUnavailableException(); + } + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || !entry.jti().equals(jti) + || !entry.planDigest().equals(plan.planDigest())) { + throw new StaleOperationException("Readiness probe selector is not the exact current entry"); + } + return entry; + } + + /** + * Records only the exact authenticated, cryptographically verified observation for one current + * ISSUED entry. A matching VERIFIED retry reads back the original immutable receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordVerified( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + VerifiedProbeObservation observation) { + requireWritableAccountTransaction(); + requireOperationId(operationId); + Objects.requireNonNull(observation, "Authenticated verification observation is required"); + long observedAt = exactEpochSecond(Instant.ofEpochSecond(observation.observedAtEpochSecond())); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != 1) { + throw new ReceiverUnavailableException(); + } + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || !entry.jti().equals(jti) + || !entry.planDigest().equals(plan.planDigest()) + || !entry.targetGeneration().equals(plan.targetGeneration()) + || !entry.targetKid().equals(plan.targetKid()) + || !entry.expectedActive().equals(plan.expectedFence().durableActive()) + || !entry.expectedActive().equals(plan.expectedFence().publishedActive()) + || entry.registryVersion() != 1 + || !entry.compactTokenSha256().equals(Optional.of(observation.compactTokenSha256())) + || !entry.targetKid().equals(observation.verifiedKid())) { + throw new StaleOperationException( + "Verified readiness probe does not match the exact current operation entry"); + } + requireNotExpired(entry, observedAt); + if (observedAt < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + + if (entry.state() == ProbeState.VERIFIED) { + VerificationReceipt existing = + entry + .verificationReceipt() + .orElseThrow( + () -> + new QuarantinedStateException( + "Verified readiness entry has no immutable receipt")); + requireMatchingObservation(existing, observation); + return entry; + } + if (entry.state() != ProbeState.ISSUED || entry.verificationReceipt().isPresent()) { + throw new AmbiguousDeliveryException("Readiness probe is not the exact current ISSUED entry"); + } + + long resultEntryVersion = Math.addExact(entry.entryVersion(), 1L); + VerificationReceipt receipt = verificationReceipt(plan, entry, observation, resultEntryVersion); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'VERIFIED', entry_version = ?, verification_receipt_version = ?, " + + "verification_source_entry_version = ?, verified_at_epoch_seconds = ?, " + + "verified_kid = ?, validator_instance_id = ?, validator_binding_digest = ?, " + + "validator_config_revision = ?, validator_peer_uri = ?, " + + "validator_peer_spki_sha256 = ?, verification_receipt_sha256 = ? " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND jti = ? AND plan_digest = ? " + + "AND state = 'ISSUED' AND entry_version = ? AND target_generation = ? " + + "AND target_kid = ? AND compact_token_sha256 = ? " + + "AND verification_receipt_sha256 IS NULL " + + "AND CURRENT_TIMESTAMP >= to_timestamp(planned_issued_at_epoch_seconds) " + + "AND CURRENT_TIMESTAMP < to_timestamp(expires_at_epoch_seconds)", + receipt.resultEntryVersion(), + receipt.receiptVersion(), + receipt.sourceEntryVersion(), + receipt.observedAtEpochSecond(), + receipt.verifiedKid(), + receipt.validatorInstanceId(), + receipt.validatorBindingDigest(), + receipt.validatorConfigRevision(), + receipt.validatorPeerUri(), + receipt.validatorPeerSpkiSha256(), + receipt.receiptSha256(), + operationId, + validatorId, + tokenProfile, + audience, + probeKind.name(), + jti, + plan.planDigest(), + entry.entryVersion(), + Long.parseLong(plan.targetGeneration()), + plan.targetKid(), + observation.compactTokenSha256()); + if (changed != 1) { + throw new VersionConflictException("Readiness VERIFIED transition lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != ProbeState.VERIFIED + || readback.entryVersion() != receipt.resultEntryVersion() + || readback.verificationReceipt().filter(receipt::equals).isEmpty()) { + throw new QuarantinedStateException("Verified readiness receipt did not read back exactly"); + } + return readback; + } + + /** + * Pins the exact signed-token hash before delivery. A row with this pin but no ISSUED result is + * ambiguous after a crash and must be quarantined; it is never signed or delivered again. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordSigningAttempt( + Binding binding, TrustFence trust, SignedProbeDigest signed, Instant attemptedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(signed, "Mounted signer result is required"); + long attemptedEpoch = exactEpochSecond(attemptedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, signed.operationId()); + ReadinessProbePlan plan = requireStoredPlan(current); + ProbeEntry entry = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + requireSignedResultMatches(plan, entry, signed); + requireNotExpired(entry, attemptedEpoch); + if (attemptedEpoch < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (entry.state() != ProbeState.PLANNED + || entry.compactTokenSha256().isPresent() + || entry.signingAttemptedAtEpochSecond().isPresent()) { + throw new AmbiguousDeliveryException("Readiness probe already has a signing attempt"); + } + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET signing_attempted_at_epoch_seconds = ?, compact_token_sha256 = ?, " + + "entry_version = entry_version + 1 WHERE rotation_operation_id = ? " + + "AND validator_id = ? AND token_profile = ? AND audience = ? AND probe_kind = ? " + + "AND plan_digest = ? AND state = 'PLANNED' AND entry_version = ? " + + "AND compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL", + attemptedEpoch, + signed.compactTokenSha256(), + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind().name(), + plan.planDigest(), + entry.entryVersion()); + if (changed != 1) { + throw new VersionConflictException("Readiness probe signing attempt lost its exact CAS"); + } + ProbeEntry readback = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + if (readback == null + || readback.state() != ProbeState.PLANNED + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256())) + || !readback.signingAttemptedAtEpochSecond().equals(Optional.of(attemptedEpoch))) { + throw new QuarantinedStateException( + "Readiness probe signing attempt did not read back exactly"); + } + return readback; + } + + /** Durably records ISSUED before the exact compact probe reaches its transient consumer. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordIssued( + Binding binding, TrustFence trust, SignedProbeDigest signed, Instant issuedAt) { + requireWritableAccountTransaction(); + Objects.requireNonNull(signed, "Mounted signer result is required"); + long issuedEpoch = exactEpochSecond(issuedAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, signed.operationId()); + ReadinessProbePlan plan = requireStoredPlan(current); + ProbeEntry entry = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + requireSignedResultMatches(plan, entry, signed); + requireNotExpired(entry, issuedEpoch); + if (issuedEpoch < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + if (entry.state() == ProbeState.ISSUED) { + if (!entry.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256()))) { + throw new IdempotencyConflictException("Issued readiness probe hash changed"); + } + return entry; + } + if (entry.state() != ProbeState.PLANNED + || !entry.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256())) + || entry.signingAttemptedAtEpochSecond().isEmpty()) { + throw new AmbiguousDeliveryException("Readiness probe is not pinned for exact delivery"); + } + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'ISSUED', entry_version = entry_version + 1 " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND plan_digest = ? " + + "AND state = 'PLANNED' AND entry_version = ? AND compact_token_sha256 = ? " + + "AND signing_attempted_at_epoch_seconds IS NOT NULL", + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind().name(), + plan.planDigest(), + entry.entryVersion(), + signed.compactTokenSha256()); + if (changed != 1) { + throw new VersionConflictException("Readiness probe ISSUED transition lost its exact CAS"); + } + ProbeEntry readback = + selectEntry( + plan.operationId(), + signed.validatorId(), + signed.tokenProfile(), + signed.audience(), + signed.probeKind(), + true); + if (readback == null + || readback.state() != ProbeState.ISSUED + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.compactTokenSha256().equals(Optional.of(signed.compactTokenSha256()))) { + throw new QuarantinedStateException("Issued readiness probe did not read back exactly"); + } + return readback; + } + + /** Quarantines a pinned PLANNED attempt after delivery or persistence became ambiguous. */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry abortAmbiguousAttempt( + Binding binding, + TrustFence trust, + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + Instant terminalAt) { + requireWritableAccountTransaction(); + long terminalEpoch = exactEpochSecond(terminalAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + requireStoredPlan(current); + ProbeEntry entry = + selectEntry(operationId, validatorId, tokenProfile, audience, probeKind, true); + if (entry == null + || entry.state() != ProbeState.PLANNED + || entry.compactTokenSha256().isEmpty()) { + throw new AmbiguousDeliveryException("No ambiguous pinned readiness attempt exists"); + } + return transitionTerminal(entry, ProbeState.ABORTED, terminalEpoch); + } + + /** Aborts only entries belonging to the exact current Account operation. */ + @Transactional(propagation = Propagation.MANDATORY) + public List abortCurrent( + Binding binding, TrustFence trust, UUID operationId, Instant terminalAt) { + requireWritableAccountTransaction(); + long terminalEpoch = exactEpochSecond(terminalAt); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + List result = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ProbeEntry currentEntry = selectEntry(entry, true); + if (currentEntry.state() == ProbeState.PLANNED + || currentEntry.state() == ProbeState.ISSUED + || currentEntry.state() == ProbeState.VERIFIED) { + result.add(transitionTerminal(currentEntry, ProbeState.ABORTED, terminalEpoch)); + } else { + result.add(currentEntry); + } + } + return List.copyOf(result); + } + + /** Expires only this exact current operation after its immutable entry expiry. */ + @Transactional(propagation = Propagation.MANDATORY) + public List expireCurrent( + Binding binding, TrustFence trust, UUID operationId, Instant now) { + requireWritableAccountTransaction(); + long nowEpoch = exactEpochSecond(now); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, operationId.toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + List result = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ProbeEntry currentEntry = selectEntry(entry, true); + if ((currentEntry.state() == ProbeState.PLANNED + || currentEntry.state() == ProbeState.ISSUED + || currentEntry.state() == ProbeState.VERIFIED) + && nowEpoch >= currentEntry.expiresAtEpochSecond()) { + result.add(transitionTerminal(currentEntry, ProbeState.EXPIRED, nowEpoch)); + } else { + result.add(currentEntry); + } + } + return List.copyOf(result); + } + + /** + * Bounded cleanup of terminal entries for one explicit operation. It never queries or scans + * another operation and retains all non-secret identity/hash/terminal evidence. + */ + @Transactional(propagation = Propagation.MANDATORY) + public List cleanTerminalEntries(UUID operationId, int maximumEntries) { + requireWritableAccountTransaction(); + requireOperationId(operationId); + if (maximumEntries < 1 || maximumEntries > MAX_ENTRIES_PER_OPERATION) { + throw new IllegalArgumentException("Readiness cleanup bound is outside its fixed limit"); + } + Result terminalRows = + dsl.fetch( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? AND state IN ('ABORTED', 'EXPIRED') " + + "ORDER BY validator_id, token_profile, audience, probe_kind LIMIT ? FOR UPDATE", + operationId, + maximumEntries); + if (terminalRows.size() > maximumEntries) { + throw new QuarantinedStateException("Readiness cleanup exceeded its exact operation bound"); + } + List cleaned = new ArrayList<>(); + for (Record row : terminalRows) { + ProbeEntry entry = decodeEntry(row); + cleaned.add(transitionTerminal(entry, ProbeState.CLEANED, null)); + } + return List.copyOf(cleaned); + } + + private ProbeEntry transitionTerminal(ProbeEntry entry, ProbeState target, Long transitionEpoch) { + if (target == ProbeState.EXPIRED && transitionEpoch == null) { + throw new IllegalArgumentException("Expiry time is required"); + } + String outcome = + target == ProbeState.CLEANED ? entry.terminalOutcome().orElseThrow() : target.name(); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = ?, terminal_outcome = ?, entry_version = entry_version + 1 " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND state = ? AND entry_version = ?", + target.name(), + outcome, + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name(), + entry.state().name(), + entry.entryVersion()); + if (changed != 1) { + throw new VersionConflictException("Readiness terminal transition lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != target + || readback.entryVersion() != entry.entryVersion() + 1 + || !readback.terminalOutcome().equals(Optional.of(outcome))) { + throw new QuarantinedStateException( + "Readiness terminal transition did not read back exactly"); + } + return readback; + } + + private ReadinessProbePlan newPlan( + CurrentEvidence current, + long plannedAtEpochSecond, + Optional inventorySnapshot, + Optional inventorySnapshotDigest) { + long notBefore = add(plannedAtEpochSecond, MAX_VALIDATOR_CACHE_AGE_SECONDS); + long expiresAt = add(notBefore, PROBE_LIFETIME_SECONDS); + int planVersion = inventorySnapshot.isPresent() ? INVENTORY_PLAN_VERSION : 1; + boolean inventoryComplete = + inventorySnapshot + .map(AccountJwtReadinessProbeRepository::inventoryPlanComplete) + .orElse(false); + String matrixJson = + inventorySnapshot + .map(snapshot -> applicabilityMatrixJson(snapshot, inventoryComplete)) + .orElseGet(AccountJwtReadinessProbeRepository::applicabilityMatrixJson); + String matrixDigest = sha256(matrixJson.getBytes(StandardCharsets.UTF_8)); + List entries = + (inventorySnapshot.isPresent() + ? inventoryEntries(current, inventorySnapshot.orElseThrow(), notBefore, expiresAt) + : legacyEntries(current, notBefore, expiresAt)) + .stream().sorted(PROBE_ENTRY_ORDER).toList(); + String planDigest = + planDigest( + current, + matrixJson, + matrixDigest, + planVersion, + inventoryComplete, + plannedAtEpochSecond, + notBefore, + expiresAt, + entries, + inventorySnapshotDigest); + List boundEntries = + entries.stream().map(entry -> entry.withPlanDigest(planDigest)).toList(); + return ReadinessProbePlan.fromCurrent( + current, + matrixJson, + matrixDigest, + inventoryComplete, + MAX_VALIDATOR_CACHE_AGE_SECONDS, + plannedAtEpochSecond, + notBefore, + expiresAt, + planDigest, + boundEntries, + inventorySnapshotDigest, + planVersion); + } + + private static List legacyEntries( + CurrentEvidence current, long notBefore, long expiresAt) { + return List.of( + newEntry( + current, + VALIDATOR_ID, + ProbeKind.CANARY, + CANARY_PROFILE, + CANARY_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + CONTROL_UI_PROFILE, + CONTROL_UI_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + PLAYER_BOOTSTRAP_PROFILE, + PLAYER_BOOTSTRAP_AUDIENCE, + notBefore, + expiresAt), + newEntry( + current, + VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + REPRESENTATIVE_PROFILE, + REPRESENTATIVE_AUDIENCE, + notBefore, + expiresAt)); + } + + private static List inventoryEntries( + CurrentEvidence current, InventorySnapshot snapshot, long notBefore, long expiresAt) { + List entries = new ArrayList<>(); + for (ValidatorObservation validator : snapshot.validators()) { + entries.add( + newEntry( + current, + validator.validatorId(), + ProbeKind.CANARY, + CANARY_PROFILE, + CANARY_AUDIENCE, + notBefore, + expiresAt)); + for (ProfileCase profile : PRODUCTION_PROFILE_CASES) { + entries.add( + newEntry( + current, + validator.validatorId(), + ProbeKind.REPRESENTATIVE, + profile.tokenProfile(), + profile.audience(), + notBefore, + expiresAt)); + } + } + if (entries.isEmpty() || entries.size() > MAX_ENTRIES_PER_OPERATION) { + throw new InventoryPlanConflictException(); + } + return List.copyOf(entries); + } + + private static ProbeEntry newEntry( + CurrentEvidence current, + String validatorId, + ProbeKind kind, + String profile, + String audience, + long notBefore, + long expiresAt) { + return new ProbeEntry( + current.request().operationId(), + "0".repeat(64), + validatorId, + profile, + audience, + kind, + UUID.randomUUID(), + current.request().targetGeneration(), + current.request().targetKid(), + current.state().durableActive(), + 1, + 1, + notBefore, + expiresAt, + ProbeState.PLANNED, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + } + + private void insertPlan(ReadinessProbePlan plan) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", plan.operationId()); + fields.put("environment_id", plan.binding().environmentId()); + fields.put("cluster_id", plan.binding().clusterId()); + fields.put("kubernetes_namespace", plan.binding().namespace()); + fields.put("custody_mode", plan.binding().mode().value()); + fields.put("operation_digest", plan.operationDigest()); + fields.put("generation_request_digest", plan.generationRequestDigest()); + fields.put("generation_receipt_digest", plan.generationReceiptDigest()); + fields.put("desired_state_version", plan.desiredStateVersion()); + fields.put( + "expected_cluster_incarnation_uid", + UUID.fromString(plan.trustFence().expectedClusterIncarnationUid())); + fields.put("expected_namespace_uid", UUID.fromString(plan.trustFence().expectedNamespaceUid())); + fields.put("trust_binding_digest", plan.trustFence().bindingDigest()); + fields.put("trust_config_revision", plan.trustFence().configRevision()); + fields.put("target_generation", Long.parseLong(plan.targetGeneration())); + fields.put("target_kid", plan.targetKid()); + fields.put("target_public_key_fingerprint", plan.targetPublicKeyFingerprint()); + fields.put( + "expected_active_generation", + plan.expectedFence() + .durableActive() + .map(value -> Long.parseLong(value.generation())) + .orElse(null)); + fields.put( + "expected_active_kid", + plan.expectedFence().durableActive().map(ActiveSigner::kid).orElse(null)); + fields.put( + "expected_published_generation", + plan.expectedFence() + .publishedActive() + .map(value -> Long.parseLong(value.generation())) + .orElse(null)); + fields.put( + "expected_published_kid", + plan.expectedFence().publishedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("publication_intent_digest", plan.publicationIntentDigest()); + fields.put("publication_receipt_digest", plan.publicationReceiptDigest()); + fields.put("mounted_observation_digest", plan.mountedObservationDigest()); + fields.put("applicability_matrix_json", plan.applicabilityMatrixJson()); + fields.put("applicability_matrix_digest", plan.applicabilityMatrixDigest()); + fields.put("validator_inventory_complete", plan.validatorInventoryComplete()); + fields.put("inventory_snapshot_digest", plan.inventorySnapshotDigest().orElse(null)); + fields.put("maximum_cache_age_seconds", plan.maximumCacheAgeSeconds()); + fields.put("planned_at_epoch_seconds", plan.plannedAtEpochSecond()); + fields.put("not_before_epoch_seconds", plan.notBeforeEpochSecond()); + fields.put("expires_at_epoch_seconds", plan.expiresAtEpochSecond()); + fields.put("plan_version", plan.planVersion()); + fields.put("plan_digest", plan.planDigest()); + insertOne(dsl, PLAN_TABLE, fields); + } + + private void insertDeliveryClaim(DeliveryClaim claim) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", claim.rotationOperationId()); + fields.put("plan_digest", claim.planDigest()); + fields.put("expected_cluster_incarnation_uid", UUID.fromString(claim.expectedClusterUid())); + fields.put("expected_namespace_uid", UUID.fromString(claim.expectedNamespaceUid())); + fields.put("materializer_trust_binding_digest", claim.materializerTrustBindingDigest()); + fields.put("materializer_trust_config_revision", claim.materializerTrustConfigRevision()); + fields.put("target_generation", Long.parseLong(claim.targetGeneration())); + fields.put("target_kid", claim.targetKid()); + fields.put( + "expected_active_generation", + claim.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null)); + fields.put("expected_active_kid", claim.expectedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("readiness_binding_digest", claim.readinessBindingDigest()); + fields.put("readiness_config_revision", claim.readinessConfigRevision()); + fields.put( + "readiness_binding_valid_until_epoch_seconds", + claim.readinessBindingValidUntilEpochSecond()); + fields.put("validator_id", claim.validatorId()); + fields.put("validator_instance_id", claim.validatorInstanceId()); + fields.put("validator_peer_uri", claim.validatorPeerUri()); + fields.put("validator_peer_spki_sha256", claim.validatorPeerSpkiSha256()); + fields.put("claimed_at_epoch_seconds", claim.claimedAtEpochSecond()); + fields.put("expires_at_epoch_seconds", claim.expiresAtEpochSecond()); + fields.put("claim_digest", claim.claimDigest()); + insertOne(dsl, DELIVERY_CLAIM_TABLE, fields); + } + + private DeliveryClaim selectDeliveryClaim(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + DELIVERY_CLAIM_TABLE + + " WHERE rotation_operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + if (row == null) { + return null; + } + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + DeliveryClaim result = + new DeliveryClaim( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("materializer_trust_binding_digest", String.class), + row.get("materializer_trust_config_revision", String.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + decodeActive(activeGeneration, activeKid), + row.get("readiness_binding_digest", String.class), + row.get("readiness_config_revision", String.class), + row.get("readiness_binding_valid_until_epoch_seconds", Long.class), + row.get("validator_id", String.class), + row.get("validator_instance_id", String.class), + row.get("validator_peer_uri", String.class), + row.get("validator_peer_spki_sha256", String.class), + row.get("claimed_at_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + row.get("claim_digest", String.class)); + if (!result.claimDigest().equals(deliveryClaimDigest(result))) { + throw new QuarantinedStateException("Account readiness delivery claim digest is invalid"); + } + return result; + } + + private void insertEntry(ProbeEntry entry, int planVersion) { + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", entry.rotationOperationId()); + fields.put("plan_digest", entry.planDigest()); + fields.put("validator_id", entry.validatorId()); + fields.put("token_profile", entry.tokenProfile()); + fields.put("audience", entry.audience()); + fields.put("probe_kind", entry.probeKind().name()); + fields.put("jti", entry.jti()); + fields.put("target_generation", Long.parseLong(entry.targetGeneration())); + fields.put("target_kid", entry.targetKid()); + fields.put( + "expected_active_generation", + entry.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null)); + fields.put("expected_active_kid", entry.expectedActive().map(ActiveSigner::kid).orElse(null)); + fields.put("registry_version", entry.registryVersion()); + fields.put("entry_version", entry.entryVersion()); + fields.put("planned_issued_at_epoch_seconds", entry.plannedIssuedAtEpochSecond()); + fields.put("expires_at_epoch_seconds", entry.expiresAtEpochSecond()); + fields.put("state", entry.state().name()); + fields.put("entry_plan_version", planVersion); + fields.put("terminal_outcome", null); + fields.put("signing_attempted_at_epoch_seconds", null); + fields.put("compact_token_sha256", null); + insertOne(dsl, ENTRY_TABLE, fields); + } + + private void insertExpectedPod(ExpectedPod expected) { + PodTarget target = expected.target(); + target.requireRoutablePodIdentity(); + Map fields = new LinkedHashMap<>(); + fields.put("rotation_operation_id", expected.rotationOperationId()); + fields.put("plan_digest", expected.planDigest()); + fields.put("validator_id", expected.validatorId()); + fields.put("token_profile", expected.tokenProfile()); + fields.put("audience", expected.audience()); + fields.put("probe_kind", expected.probeKind().name()); + fields.put("jti", expected.jti()); + fields.put("inventory_snapshot_digest", target.inventorySnapshotDigest()); + fields.put("environment_id", target.environmentId()); + fields.put("cluster_id", target.clusterId()); + fields.put("cluster_incarnation_uid", UUID.fromString(target.clusterIncarnationUid())); + fields.put("kubernetes_namespace", target.namespace()); + fields.put("namespace_uid", UUID.fromString(target.namespaceUid())); + fields.put("api_binding_revision", target.apiBindingRevision()); + fields.put("api_binding_digest", target.apiBindingDigest()); + fields.put("inventory_binding_revision", target.inventoryBindingRevision()); + fields.put("inventory_binding_digest", target.inventoryBindingDigest()); + fields.put("deployment_uid", UUID.fromString(target.deploymentUid())); + fields.put("pod_uid", UUID.fromString(target.podUid())); + fields.put("pod_ip", target.podIp()); + fields.put("image", target.image()); + fields.put("verifier_config_sha256", target.verifierConfigSha256()); + fields.put("applicability_matrix_digest", target.applicabilityMatrixDigest()); + fields.put("expected_outcome", target.expectation().name()); + fields.put("exact_pod_endpoint", target.exactPodEndpoint().map(URI::toString).orElse(null)); + fields.put("canonical_service_uri", target.canonicalServiceUri().orElse(null)); + fields.put("expected_pod_leaf_spki_sha256", target.podLeafSpkiSha256().orElse(null)); + insertOne(dsl, EXPECTED_POD_TABLE, fields); + } + + /** Reads the immutable, exact per-Pod plan rows for one current V2 entry. */ + @Transactional(propagation = Propagation.MANDATORY) + public List readCurrentExpectedPods( + Binding binding, TrustFence trust, ProbeEntry expectedEntry) { + throw new ReceiverUnavailableException(); + } + + /** Reads exact expected Pod rows only after a fresh independent owner observation. */ + @Transactional(propagation = Propagation.MANDATORY) + public List readCurrentExpectedPods( + Binding binding, + TrustFence trust, + ProbeEntry expectedEntry, + InventorySnapshot liveInventory) { + requireAccountTransaction(); + Objects.requireNonNull(expectedEntry, "Exact readiness entry is required"); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedEntry.rotationOperationId().toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.planDigest().equals(expectedEntry.planDigest())) { + throw new ReceiverUnavailableException(); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + ProbeEntry stored = + selectEntry( + expectedEntry.rotationOperationId(), + expectedEntry.validatorId(), + expectedEntry.tokenProfile(), + expectedEntry.audience(), + expectedEntry.probeKind(), + true); + if (stored == null + || !stored.equals(expectedEntry) + || stored.state() != ProbeState.ISSUED + || stored.compactTokenSha256().isEmpty()) { + throw new StaleOperationException("Readiness receiver entry changed before invocation"); + } + plan.inventorySnapshotDigest() + .ifPresent(digest -> inventoryRepository.readRequired(digest, binding, trust)); + List expectedPods = selectExpectedPods(stored, true); + if (expectedPods.isEmpty() || expectedPods.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness V2 entry has no bounded expected Pod set"); + } + return expectedPods; + } + + /** + * Reads only the owner-retained coordinates and one Pod target for the authenticated V2 receiver + * lookup. The caller's tuple is a selector: every returned coordinate is projected from locked + * current owner rows, never copied from the request. + */ + @Transactional(propagation = Propagation.MANDATORY) + public OwnerProbeEvidence readCurrentProbeOwner( + Binding binding, + TrustFence trust, + AccountJwtReadinessProbeOwnerSelector selector, + InventorySnapshot liveInventory, + String authenticatedWorkloadNamespace) { + requireAccountTransaction(); + Objects.requireNonNull(selector, "Exact readiness probe selector is required"); + if (authenticatedWorkloadNamespace == null || authenticatedWorkloadNamespace.isBlank()) { + throw new ReceiverUnavailableException(); + } + CurrentEvidence current = lockCurrentEvidence(binding, trust); + if (!current.request().operationId().equals(selector.rotationOperationId())) { + throw new ReceiverUnavailableException(); + } + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.operationId().equals(selector.rotationOperationId()) + || !plan.operationDigest().equals(selector.operationDigest()) + || !plan.planDigest().equals(selector.planDigest()) + || plan.planVersion() != selector.planVersion() + || plan.expiresAtEpochSecond() != selector.planExpiresAtEpochSecond() + || !plan.targetGeneration().equals(selector.targetGeneration()) + || !plan.targetKid().equals(selector.targetKid()) + || !plan.expectedFence().durableActive().equals(selector.expectedActive()) + || !plan.expectedFence().publishedActive().equals(selector.expectedActive())) { + throw new ReceiverUnavailableException(); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + AccountJwtReadinessProbeOwnerSelector.LocalIdentity local = selector.localIdentity(); + if (!local.sourceInventoryRevision().equals(liveInventory.inventoryBindingRevision()) + || !local.sourceInventoryDigest().equals(liveInventory.inventoryBindingDigest())) { + throw new ReceiverUnavailableException(); + } + if (readinessPlanOutOfWindow(plan)) { + throw new ReceiverUnavailableException(); + } + + ProbeEntry entry = + selectEntry( + selector.rotationOperationId(), + selector.validatorId(), + selector.tokenProfile(), + selector.audience(), + selector.probeKind(), + true); + if (entry == null + || entry.state() != ProbeState.ISSUED + || entry.verificationReceipt().isPresent() + || !entry.rotationOperationId().equals(selector.rotationOperationId()) + || !entry.planDigest().equals(plan.planDigest()) + || !entry.jti().equals(selector.jti()) + || entry.registryVersion() != selector.registryVersion() + || entry.entryVersion() != selector.entryVersion() + || !entry.targetGeneration().equals(selector.targetGeneration()) + || !entry.targetKid().equals(selector.targetKid()) + || !entry.expectedActive().equals(selector.expectedActive()) + || entry.plannedIssuedAtEpochSecond() != selector.issuedAtEpochSecond() + || entry.expiresAtEpochSecond() != selector.expiresAtEpochSecond() + || !entry.compactTokenSha256().equals(Optional.of(selector.compactTokenSha256()))) { + throw new ReceiverUnavailableException(); + } + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null + || databaseNow < entry.plannedIssuedAtEpochSecond() + || databaseNow >= entry.expiresAtEpochSecond()) { + throw new ReceiverUnavailableException(); + } + + List expectedPods = selectExpectedPods(entry, true); + if (expectedPods.isEmpty() || expectedPods.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new ReceiverUnavailableException(); + } + List selectedPods = + expectedPods.stream() + .filter(value -> value.target().podUid().equals(selector.localIdentity().podUid())) + .toList(); + if (selectedPods.size() != 1) { + throw new ReceiverUnavailableException(); + } + ExpectedPod expectedPod = selectedPods.getFirst(); + PodTarget target = expectedPod.target(); + target.requireRoutablePodIdentity(); + if (!target.validatorId().equals(selector.validatorId()) + || !expectedPod.rotationOperationId().equals(selector.rotationOperationId()) + || !expectedPod.planDigest().equals(plan.planDigest()) + || !expectedPod.jti().equals(entry.jti()) + || target.expectation() != selector.expectedOutcome() + || !target.namespace().equals(authenticatedWorkloadNamespace) + || !local.validatorId().equals(target.validatorId()) + || !local.deploymentUid().equals(target.deploymentUid()) + || !local.podUid().equals(target.podUid()) + || !local.podIp().equals(target.podIp()) + || !local.directPodEndpoint().equals(target.exactPodEndpoint().orElseThrow().toString()) + || !local.canonicalServiceUri().equals(target.canonicalServiceUri().orElseThrow()) + || !local.image().equals(target.image()) + || !local.verifierConfigSha256().equals(target.verifierConfigSha256()) + || !local.applicabilityMatrixDigest().equals(plan.applicabilityMatrixDigest()) + || !local.serverLeafSpkiSha256().equals(target.podLeafSpkiSha256().orElseThrow())) { + throw new ReceiverUnavailableException(); + } + return new OwnerProbeEvidence(plan, entry, expectedPod); + } + + /** + * Records one owner-authenticated production verifier result for one exact expected Pod. A + * logical entry remains ISSUED until every immutable expected Pod has a matching unique receipt. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ProbeEntry recordPodAcceptance( + Binding binding, + TrustFence trust, + ProbeEntry expectedEntry, + ExpectedPod expectedPod, + AuthenticatedAcceptance acceptance, + InventorySnapshot liveInventory) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedEntry, "Exact readiness entry is required"); + Objects.requireNonNull(expectedPod, "Exact expected Pod row is required"); + Objects.requireNonNull(acceptance, "Owner-authenticated receiver result is required"); + CurrentEvidence current = lockCurrentEvidence(binding, trust); + requireCurrentOperation(current, expectedEntry.rotationOperationId().toString()); + ReadinessProbePlan plan = requireStoredPlan(current); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || !plan.planDigest().equals(expectedEntry.planDigest()) + || !expectedPod.rotationOperationId().equals(plan.operationId()) + || !expectedPod.planDigest().equals(plan.planDigest()) + || !expectedPod.validatorId().equals(expectedEntry.validatorId()) + || !expectedPod.tokenProfile().equals(expectedEntry.tokenProfile()) + || !expectedPod.audience().equals(expectedEntry.audience()) + || expectedPod.probeKind() != expectedEntry.probeKind() + || !expectedPod.jti().equals(expectedEntry.jti())) { + throw new StaleOperationException("Readiness Pod receipt is outside the exact current entry"); + } + requireLiveInventoryMatches(plan, binding, trust, liveInventory, observationContext(current)); + ProbeEntry entry = + selectEntry( + expectedEntry.rotationOperationId(), + expectedEntry.validatorId(), + expectedEntry.tokenProfile(), + expectedEntry.audience(), + expectedEntry.probeKind(), + true); + if (entry == null + || entry.compactTokenSha256().isEmpty() + || !entry.rotationOperationId().equals(expectedEntry.rotationOperationId()) + || !entry.planDigest().equals(expectedEntry.planDigest()) + || !entry.validatorId().equals(expectedEntry.validatorId()) + || !entry.tokenProfile().equals(expectedEntry.tokenProfile()) + || !entry.audience().equals(expectedEntry.audience()) + || entry.probeKind() != expectedEntry.probeKind() + || !entry.jti().equals(expectedEntry.jti()) + || !entry.targetGeneration().equals(expectedEntry.targetGeneration()) + || !entry.targetKid().equals(expectedEntry.targetKid()) + || !entry.expectedActive().equals(expectedEntry.expectedActive()) + || entry.registryVersion() != expectedEntry.registryVersion() + || entry.plannedIssuedAtEpochSecond() != expectedEntry.plannedIssuedAtEpochSecond() + || entry.expiresAtEpochSecond() != expectedEntry.expiresAtEpochSecond()) { + throw new AmbiguousDeliveryException("Readiness Pod receipt requires its exact ISSUED entry"); + } + boolean alreadyVerified = entry.state() == ProbeState.VERIFIED; + if ((!alreadyVerified && entry.state() != ProbeState.ISSUED) + || (!alreadyVerified && !entry.equals(expectedEntry)) + || (alreadyVerified + && (entry.entryVersion() <= 1L + || entry + .verificationReceipt() + .filter(value -> value.receiptVersion() == 2) + .isEmpty()))) { + throw new AmbiguousDeliveryException("Readiness Pod receipt requires its exact ISSUED entry"); + } + List expectedPods = selectExpectedPods(entry, true); + ExpectedPod persistedPod = + expectedPods.stream() + .filter(value -> value.target().podUid().equals(expectedPod.target().podUid())) + .findFirst() + .orElseThrow(ReceiverUnavailableException::new); + if (!persistedPod.equals(expectedPod)) { + throw new QuarantinedStateException("Readiness Pod target changed after its immutable plan"); + } + PodTarget target = persistedPod.target(); + target.requireRoutablePodIdentity(); + long observedAt = acceptance.observedAtEpochSecond(); + if (!acceptance.podUid().equals(target.podUid()) + || !acceptance + .actualPodEndpoint() + .equals(target.exactPodEndpoint().orElseThrow().toString()) + || !acceptance.image().equals(target.image()) + || !acceptance.verifierConfigSha256().equals(target.verifierConfigSha256()) + || !acceptance.actualServiceUri().equals(target.canonicalServiceUri().orElseThrow()) + || !acceptance.actualPeerSpkiSha256().equals(target.podLeafSpkiSha256().orElseThrow()) + || !acceptance.jti().equals(entry.jti()) + || !acceptance.compactTokenSha256().equals(entry.compactTokenSha256().orElseThrow()) + || acceptance.result() != target.expectation() + || !entry.targetKid().equals(acceptance.verifiedKid())) { + throw new IdempotencyConflictException( + "Authenticated receiver evidence differs from the exact protected Pod target"); + } + requireNotExpired(entry, observedAt); + if (observedAt < entry.plannedIssuedAtEpochSecond()) { + throw new CacheAgeNotElapsedException(); + } + + PodReceipt candidate = + podReceipt( + entry, + persistedPod, + acceptance, + alreadyVerified ? entry.entryVersion() - 1L : entry.entryVersion()); + PodReceipt existing = selectPodReceipt(candidate, true); + if (alreadyVerified) { + List retainedReceipts = selectPodReceipts(entry, true); + ProbeEntry sourceEntry = sourceEntryForVerifiedClosure(entry); + VerificationReceipt recomputed = + podReceiptClosure(plan, sourceEntry, expectedPods, retainedReceipts); + if (existing == null + || !existing.equals(candidate) + || retainedReceipts.size() != expectedPods.size() + || entry.verificationReceipt().filter(recomputed::equals).isEmpty()) { + throw new IdempotencyConflictException( + "A completed readiness Pod receipt retry differs from its immutable evidence"); + } + return entry; + } + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "A per-Pod readiness receipt already exists with different evidence"); + } + } else { + insertPodReceipt(candidate); + PodReceipt readback = selectPodReceipt(candidate, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException("Readiness Pod receipt did not read back exactly"); + } + } + + List receipts = selectPodReceipts(entry, true); + if (receipts.size() != expectedPods.size()) { + if (receipts.size() > expectedPods.size()) { + throw new QuarantinedStateException("Readiness Pod receipt set exceeds its exact target"); + } + ProbeEntry partial = selectEntry(entry, true); + if (partial == null || partial.state() != ProbeState.ISSUED) { + throw new QuarantinedStateException("Partial per-Pod receipt changed its logical entry"); + } + return partial; + } + VerificationReceipt closure = podReceiptClosure(plan, entry, expectedPods, receipts); + long resultEntryVersion = Math.addExact(entry.entryVersion(), 1L); + VerificationReceipt finalReceipt = + new VerificationReceipt( + closure.receiptVersion(), + entry.entryVersion(), + resultEntryVersion, + closure.observedAtEpochSecond(), + closure.receiptSha256(), + closure.verifiedKid(), + closure.validatorInstanceId(), + closure.validatorBindingDigest(), + closure.validatorConfigRevision(), + closure.validatorPeerUri(), + closure.validatorPeerSpkiSha256(), + closure.podReceiptCount(), + closure.podReceiptClosureSha256()); + int changed = + dsl.execute( + "UPDATE " + + ENTRY_TABLE + + " SET state = 'VERIFIED', entry_version = ?, verification_receipt_version = ?, " + + "verification_source_entry_version = ?, verified_at_epoch_seconds = ?, " + + "verified_kid = ?, validator_instance_id = ?, validator_binding_digest = ?, " + + "validator_config_revision = ?, validator_peer_uri = ?, " + + "validator_peer_spki_sha256 = ?, verification_receipt_sha256 = ?, " + + "pod_receipt_count = ?, pod_receipt_closure_sha256 = ? " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND jti = ? AND plan_digest = ? " + + "AND entry_plan_version = 2 AND state = 'ISSUED' AND entry_version = ? " + + "AND target_generation = ? AND target_kid = ? AND compact_token_sha256 = ? " + + "AND verification_receipt_sha256 IS NULL " + + "AND CURRENT_TIMESTAMP >= to_timestamp(planned_issued_at_epoch_seconds) " + + "AND CURRENT_TIMESTAMP < to_timestamp(expires_at_epoch_seconds)", + finalReceipt.resultEntryVersion(), + finalReceipt.receiptVersion(), + finalReceipt.sourceEntryVersion(), + finalReceipt.observedAtEpochSecond(), + finalReceipt.verifiedKid(), + finalReceipt.validatorInstanceId(), + finalReceipt.validatorBindingDigest(), + finalReceipt.validatorConfigRevision(), + finalReceipt.validatorPeerUri(), + finalReceipt.validatorPeerSpkiSha256(), + finalReceipt.receiptSha256(), + finalReceipt.podReceiptCount(), + finalReceipt.podReceiptClosureSha256(), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name(), + entry.jti(), + entry.planDigest(), + entry.entryVersion(), + Long.parseLong(entry.targetGeneration()), + entry.targetKid(), + entry.compactTokenSha256().orElseThrow()); + if (changed != 1) { + throw new VersionConflictException("Readiness per-Pod closure lost its exact CAS"); + } + ProbeEntry readback = selectEntry(entry, true); + if (readback == null + || readback.state() != ProbeState.VERIFIED + || readback.entryVersion() != finalReceipt.resultEntryVersion() + || readback.verificationReceipt().filter(finalReceipt::equals).isEmpty()) { + throw new QuarantinedStateException("Readiness per-Pod closure did not read back exactly"); + } + return readback; + } + + private List selectExpectedPods(ProbeEntry entry, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + EXPECTED_POD_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? ORDER BY pod_uid" + + (lock ? " FOR KEY SHARE" : ""), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name()); + List expected = new ArrayList<>(rows.size()); + for (Record row : rows) { + String endpoint = row.get("exact_pod_endpoint", String.class); + expected.add( + new ExpectedPod( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("jti", UUID.class), + new PodTarget( + row.get("inventory_snapshot_digest", String.class), + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("cluster_incarnation_uid", UUID.class).toString(), + row.get("kubernetes_namespace", String.class), + row.get("namespace_uid", UUID.class).toString(), + row.get("api_binding_revision", String.class), + row.get("api_binding_digest", String.class), + row.get("inventory_binding_revision", String.class), + row.get("inventory_binding_digest", String.class), + row.get("validator_id", String.class), + row.get("deployment_uid", UUID.class).toString(), + row.get("pod_uid", UUID.class).toString(), + row.get("pod_ip", String.class), + row.get("image", String.class), + row.get("verifier_config_sha256", String.class), + row.get("applicability_matrix_digest", String.class), + ProbeExpectation.valueOf(row.get("expected_outcome", String.class)), + Optional.ofNullable(endpoint).map(URI::create), + Optional.ofNullable(row.get("canonical_service_uri", String.class)), + Optional.ofNullable(row.get("expected_pod_leaf_spki_sha256", String.class))))); + } + return List.copyOf(expected); + } + + private void requireLiveInventoryMatches( + ReadinessProbePlan plan, + Binding binding, + TrustFence trust, + InventorySnapshot liveInventory, + ObservationContext expectedContext) { + Objects.requireNonNull(liveInventory, "Fresh protected live inventory is required"); + requireFreshLiveInventory(liveInventory); + String expectedDigest = + plan.inventorySnapshotDigest().orElseThrow(ReceiverUnavailableException::new); + AccountJwtValidatorInventoryRepository.StoredSnapshot stored = + inventoryRepository.readRequired(expectedDigest, binding, trust); + if (liveInventory.observationContext().filter(expectedContext::equals).isEmpty() + || !expectedDigest.equals(liveInventory.digest()) + || !stored.digest().equals(liveInventory.digest()) + || !stored.environmentId().equals(liveInventory.environmentId()) + || !stored.clusterId().equals(liveInventory.clusterId()) + || !stored.clusterIncarnationUid().equals(liveInventory.clusterIncarnationUid()) + || !stored.namespace().equals(liveInventory.namespace()) + || !stored.namespaceUid().equals(liveInventory.namespaceUid()) + || !stored.apiBindingRevision().equals(liveInventory.apiBindingRevision()) + || !stored.apiBindingDigest().equals(liveInventory.apiBindingDigest()) + || !stored.inventoryBindingRevision().equals(liveInventory.inventoryBindingRevision()) + || !stored.inventoryBindingDigest().equals(liveInventory.inventoryBindingDigest()) + || !MessageDigest.isEqual(stored.canonicalBytes(), liveInventory.canonicalBytes())) { + throw new ReceiverUnavailableException(); + } + } + + private static void requireObservationContext( + CurrentEvidence current, InventorySnapshot snapshot) { + if (snapshot.observationContext().filter(observationContext(current)::equals).isEmpty()) { + throw new InventoryPlanConflictException(); + } + } + + private static ObservationContext observationContext(CurrentEvidence current) { + return observationContext( + current.request().operationId(), + current.request().operationDigest(), + new SignerFence(current.state().durableActive(), current.state().publishedActive())); + } + + private static ObservationContext observationContext( + UUID operationId, String operationDigest, SignerFence expectedFence) { + if (!expectedFence.durableActive().equals(expectedFence.publishedActive())) { + throw new StaleOperationException("JWT active signer fence changed during inventory proof"); + } + ObservationPurpose purpose = + expectedFence.durableActive().isEmpty() + ? ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES + : ObservationPurpose.STRICT_READY; + return new ObservationContext(purpose, operationId, operationDigest); + } + + private void requireFreshLiveInventory(InventorySnapshot snapshot) { + long observedAt = snapshot.observedAt().getEpochSecond(); + Long databaseNow = + dsl.resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class); + if (databaseNow == null) { + throw new StorageUnavailableException("Account validator inventory clock is unavailable"); + } + if (observedAt <= 0L + || observedAt > databaseNow + || databaseNow - observedAt > MAX_VALIDATOR_CACHE_AGE_SECONDS) { + throw new ReceiverUnavailableException(); + } + } + + private boolean hasCompletePodReceiptClosure(ReadinessProbePlan plan) { + if (plan.planVersion() != INVENTORY_PLAN_VERSION || !plan.validatorInventoryComplete()) { + return false; + } + int totalReceipts = 0; + for (ProbeEntry entry : plan.entries()) { + if (entry.state() != ProbeState.VERIFIED) { + return false; + } + VerificationReceipt receipt = entry.verificationReceipt().orElseThrow(); + if (receipt.receiptVersion() != 2) { + throw new QuarantinedStateException( + "V2 readiness entry has no per-Pod verification closure receipt"); + } + List expectedPods = selectExpectedPods(entry, true); + List podReceipts = selectPodReceipts(entry, true); + if (expectedPods.isEmpty() || expectedPods.size() != receipt.podReceiptCount()) { + throw new QuarantinedStateException( + "V2 readiness receipt count differs from its exact expected Pod inventory"); + } + if (podReceipts.size() < expectedPods.size()) { + return false; + } + if (podReceipts.size() != expectedPods.size()) { + throw new QuarantinedStateException( + "V2 readiness receipt set exceeds its exact expected Pod inventory"); + } + ProbeEntry sourceEntry = sourceEntryForVerifiedClosure(entry); + VerificationReceipt recomputed = + podReceiptClosure(plan, sourceEntry, expectedPods, podReceipts); + if (!recomputed.equals(receipt)) { + throw new QuarantinedStateException( + "V2 readiness entry closure differs from retained per-Pod receipts"); + } + totalReceipts = Math.addExact(totalReceipts, podReceipts.size()); + if (totalReceipts > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness Pod receipt closure exceeds its bound"); + } + } + return totalReceipts > 0; + } + + private void insertPodReceipt(PodReceipt receipt) { + dsl.execute( + "INSERT INTO " + + POD_RECEIPT_TABLE + + " (rotation_operation_id, plan_digest, validator_id, token_profile, audience, " + + "probe_kind, pod_uid, receipt_version, jti, source_entry_version, " + + "compact_token_sha256, target_generation, target_kid, expected_active_generation, " + + "expected_active_kid, outcome, observed_pod_uid, observed_image, " + + "observed_verifier_config_sha256, verified_kid, receiver_endpoint, " + + "receiver_service_uri, receiver_peer_spki_sha256, observed_at_epoch_seconds, receipt_sha256) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) " + + "DO NOTHING", + receipt.rotationOperationId(), + receipt.planDigest(), + receipt.validatorId(), + receipt.tokenProfile(), + receipt.audience(), + receipt.probeKind().name(), + UUID.fromString(receipt.podUid()), + 1, + receipt.jti(), + receipt.sourceEntryVersion(), + receipt.compactTokenSha256(), + Long.parseLong(receipt.targetGeneration()), + receipt.targetKid(), + receipt.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null), + receipt.expectedActive().map(ActiveSigner::kid).orElse(null), + receipt.outcome().name(), + UUID.fromString(receipt.observedPodUid()), + receipt.image(), + receipt.verifierConfigSha256(), + receipt.verifiedKid(), + receipt.receiverEndpoint().toString(), + receipt.receiverServiceUri(), + receipt.receiverPeerSpkiSha256(), + receipt.observedAtEpochSecond(), + receipt.receiptSha256()); + } + + private PodReceipt selectPodReceipt(PodReceipt key, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + POD_RECEIPT_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? AND pod_uid = ?" + + (lock ? " FOR UPDATE" : ""), + key.rotationOperationId(), + key.validatorId(), + key.tokenProfile(), + key.audience(), + key.probeKind().name(), + UUID.fromString(key.podUid())); + return row == null ? null : decodePodReceipt(row); + } + + private List selectPodReceipts(ProbeEntry entry, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + POD_RECEIPT_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ? ORDER BY pod_uid" + + (lock ? " FOR UPDATE" : ""), + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name()); + List receipts = new ArrayList<>(rows.size()); + for (Record row : rows) { + receipts.add(decodePodReceipt(row)); + } + return List.copyOf(receipts); + } + + private static PodReceipt decodePodReceipt(Record row) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + PodReceipt receipt = + new PodReceipt( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("pod_uid", UUID.class).toString(), + row.get("jti", UUID.class), + row.get("source_entry_version", Long.class), + row.get("compact_token_sha256", String.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + decodeActive(activeGeneration, activeKid), + ProbeExpectation.valueOf(row.get("outcome", String.class)), + row.get("observed_pod_uid", UUID.class).toString(), + row.get("observed_image", String.class), + row.get("observed_verifier_config_sha256", String.class), + row.get("verified_kid", String.class), + URI.create(row.get("receiver_endpoint", String.class)), + row.get("receiver_service_uri", String.class), + row.get("receiver_peer_spki_sha256", String.class), + row.get("observed_at_epoch_seconds", Long.class), + row.get("receipt_sha256", String.class)); + if (!receipt.receiptSha256().equals(podReceiptDigest(receipt))) { + throw new QuarantinedStateException("Immutable per-Pod readiness receipt digest is invalid"); + } + return receipt; + } + + private static PodReceipt podReceipt( + ProbeEntry entry, + ExpectedPod expected, + AuthenticatedAcceptance acceptance, + long sourceEntryVersion) { + PodTarget target = expected.target(); + PodReceipt unsigned = + new PodReceipt( + entry.rotationOperationId(), + entry.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + target.podUid(), + entry.jti(), + sourceEntryVersion, + entry.compactTokenSha256().orElseThrow(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive(), + acceptance.result(), + acceptance.podUid(), + acceptance.image(), + acceptance.verifierConfigSha256(), + acceptance.verifiedKid(), + URI.create(acceptance.actualPodEndpoint()), + acceptance.actualServiceUri(), + acceptance.actualPeerSpkiSha256(), + acceptance.observedAtEpochSecond(), + "0".repeat(64)); + return new PodReceipt( + unsigned.rotationOperationId(), + unsigned.planDigest(), + unsigned.validatorId(), + unsigned.tokenProfile(), + unsigned.audience(), + unsigned.probeKind(), + unsigned.podUid(), + unsigned.jti(), + unsigned.sourceEntryVersion(), + unsigned.compactTokenSha256(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.expectedActive(), + unsigned.outcome(), + unsigned.observedPodUid(), + unsigned.image(), + unsigned.verifierConfigSha256(), + unsigned.verifiedKid(), + unsigned.receiverEndpoint(), + unsigned.receiverServiceUri(), + unsigned.receiverPeerSpkiSha256(), + unsigned.observedAtEpochSecond(), + podReceiptDigest(unsigned)); + } + + private static ProbeEntry sourceEntryForVerifiedClosure(ProbeEntry verified) { + VerificationReceipt receipt = verified.verificationReceipt().orElseThrow(); + if (receipt.receiptVersion() != 2 + || receipt.sourceEntryVersion() + 1L != verified.entryVersion()) { + throw new QuarantinedStateException("Verified per-Pod closure has an invalid source version"); + } + return new ProbeEntry( + verified.rotationOperationId(), + verified.planDigest(), + verified.validatorId(), + verified.tokenProfile(), + verified.audience(), + verified.probeKind(), + verified.jti(), + verified.targetGeneration(), + verified.targetKid(), + verified.expectedActive(), + verified.registryVersion(), + receipt.sourceEntryVersion(), + verified.plannedIssuedAtEpochSecond(), + verified.expiresAtEpochSecond(), + ProbeState.ISSUED, + Optional.empty(), + verified.signingAttemptedAtEpochSecond(), + verified.compactTokenSha256(), + Optional.empty()); + } + + private static String podReceiptDigest(PodReceipt receipt) { + Map value = new LinkedHashMap<>(); + value.put("domain", "account-jwt-readiness-per-pod-receipt/v1"); + value.put("rotationOperationId", receipt.rotationOperationId().toString()); + value.put("planDigest", receipt.planDigest()); + value.put("validatorId", receipt.validatorId()); + value.put("tokenProfile", receipt.tokenProfile()); + value.put("audience", receipt.audience()); + value.put("probeKind", receipt.probeKind().name()); + value.put("podUid", receipt.podUid()); + value.put("jti", receipt.jti().toString()); + value.put("sourceEntryVersion", receipt.sourceEntryVersion()); + value.put("compactTokenSha256", receipt.compactTokenSha256()); + value.put("targetGeneration", receipt.targetGeneration()); + value.put("targetKid", receipt.targetKid()); + value.put("expectedActive", activeMap(receipt.expectedActive())); + value.put("outcome", receipt.outcome().name()); + value.put("observedPodUid", receipt.observedPodUid()); + value.put("image", receipt.image()); + value.put("verifierConfigSha256", receipt.verifierConfigSha256()); + value.put("verifiedKid", receipt.verifiedKid()); + value.put("receiverEndpoint", receipt.receiverEndpoint().toString()); + value.put("receiverServiceUri", receipt.receiverServiceUri()); + value.put("receiverPeerSpkiSha256", receipt.receiverPeerSpkiSha256()); + value.put("observedAtEpochSecond", receipt.observedAtEpochSecond()); + return digest(value); + } + + private static VerificationReceipt podReceiptClosure( + ReadinessProbePlan plan, + ProbeEntry entry, + List expectedPods, + List receipts) { + Map expectedByUid = new LinkedHashMap<>(); + for (ExpectedPod expected : expectedPods) { + if (expectedByUid.putIfAbsent(expected.target().podUid(), expected) != null) { + throw new QuarantinedStateException("Readiness Pod plan contains duplicate Pod UIDs"); + } + } + Map receiptsByUid = new LinkedHashMap<>(); + for (PodReceipt receipt : receipts) { + ExpectedPod expected = expectedByUid.get(receipt.podUid()); + if (expected == null + || receiptsByUid.putIfAbsent(receipt.podUid(), receipt) != null + || !receipt.rotationOperationId().equals(entry.rotationOperationId()) + || !receipt.planDigest().equals(entry.planDigest()) + || !receipt.validatorId().equals(entry.validatorId()) + || !receipt.tokenProfile().equals(entry.tokenProfile()) + || !receipt.audience().equals(entry.audience()) + || receipt.probeKind() != entry.probeKind() + || !receipt.jti().equals(entry.jti()) + || receipt.sourceEntryVersion() != entry.entryVersion() + || !receipt.compactTokenSha256().equals(entry.compactTokenSha256().orElseThrow()) + || !receipt.targetGeneration().equals(entry.targetGeneration()) + || !receipt.targetKid().equals(entry.targetKid()) + || !receipt.expectedActive().equals(entry.expectedActive()) + || receipt.outcome() != expected.target().expectation() + || !receipt.observedPodUid().equals(expected.target().podUid()) + || !receipt.image().equals(expected.target().image()) + || !receipt.verifierConfigSha256().equals(expected.target().verifierConfigSha256()) + || !receipt.receiverEndpoint().equals(expected.target().exactPodEndpoint().orElseThrow()) + || !receipt + .receiverServiceUri() + .equals(expected.target().canonicalServiceUri().orElseThrow()) + || !receipt + .receiverPeerSpkiSha256() + .equals(expected.target().podLeafSpkiSha256().orElseThrow()) + || !receipt.receiptSha256().equals(podReceiptDigest(receipt))) { + throw new QuarantinedStateException( + "Readiness Pod receipt does not match its exact target"); + } + } + if (expectedByUid.size() != receiptsByUid.size() + || expectedByUid.isEmpty() + || expectedByUid.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Readiness Pod receipt closure is incomplete"); + } + ProbeExpectation expectedOutcome = null; + List> closurePods = new ArrayList<>(); + List ordered = + expectedPods.stream() + .sorted(java.util.Comparator.comparing(value -> value.target().podUid())) + .toList(); + long observedAt = 0L; + for (ExpectedPod expected : ordered) { + PodTarget target = expected.target(); + PodReceipt receipt = receiptsByUid.get(target.podUid()); + if (receipt == null || (expectedOutcome != null && expectedOutcome != target.expectation())) { + throw new QuarantinedStateException("Readiness Pod expectations are not a closed matrix"); + } + expectedOutcome = target.expectation(); + observedAt = Math.max(observedAt, receipt.observedAtEpochSecond()); + Map pod = new LinkedHashMap<>(); + pod.put("podUid", target.podUid()); + pod.put("podIpEndpoint", target.exactPodEndpoint().orElseThrow().toString()); + pod.put("serviceUri", target.canonicalServiceUri().orElseThrow()); + pod.put("leafSpkiSha256", target.podLeafSpkiSha256().orElseThrow()); + pod.put("image", target.image()); + pod.put("verifierConfigSha256", target.verifierConfigSha256()); + pod.put("receiptSha256", receipt.receiptSha256()); + closurePods.add(pod); + } + ExpectedPod first = ordered.get(0); + PodTarget firstTarget = first.target(); + Map closure = new LinkedHashMap<>(); + closure.put("domain", "account-jwt-readiness-per-pod-closure/v1"); + closure.put("rotationOperationId", plan.operationId().toString()); + closure.put("planDigest", plan.planDigest()); + closure.put("applicabilityMatrixDigest", plan.applicabilityMatrixDigest()); + closure.put("inventorySnapshotDigest", plan.inventorySnapshotDigest().orElseThrow()); + closure.put("validatorId", entry.validatorId()); + closure.put("tokenProfile", entry.tokenProfile()); + closure.put("audience", entry.audience()); + closure.put("probeKind", entry.probeKind().name()); + closure.put("jti", entry.jti().toString()); + closure.put("sourceEntryVersion", entry.entryVersion()); + closure.put("compactTokenSha256", entry.compactTokenSha256().orElseThrow()); + closure.put("targetGeneration", entry.targetGeneration()); + closure.put("targetKid", entry.targetKid()); + closure.put("expectedActive", activeMap(entry.expectedActive())); + closure.put("pods", closurePods); + String closureSha256 = digest(closure); + return new VerificationReceipt( + 2, + entry.entryVersion(), + entry.entryVersion() + 1L, + observedAt, + closureSha256, + entry.targetKid(), + firstTarget.podUid(), + firstTarget.inventoryBindingDigest(), + firstTarget.inventoryBindingRevision(), + firstTarget.canonicalServiceUri().orElseThrow(), + firstTarget.podLeafSpkiSha256().orElseThrow(), + expectedPods.size(), + closureSha256); + } + + private ReadinessProbePlan selectPlan(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + PLAN_TABLE + + " WHERE rotation_operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodePlan(row, selectEntries(operationId, lock)); + } + + private ReadinessProbePlan readbackPlan(ReadinessProbePlan plan, boolean lock) { + List entries = selectEntries(plan.operationId(), lock); + if (!entries.equals(plan.entries())) { + throw new QuarantinedStateException("Readiness probe entries changed after plan persistence"); + } + if (!plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException("Readiness probe plan digest is invalid"); + } + plan.inventorySnapshotDigest() + .ifPresent( + digest -> inventoryRepository.readRequired(digest, plan.binding(), plan.trustFence())); + return plan; + } + + private List selectEntries(UUID operationId, boolean lock) { + Result rows = + dsl.fetch( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? ORDER BY validator_id, CASE token_profile WHEN '" + + CANARY_PROFILE + + "' THEN 0 WHEN '" + + CONTROL_UI_PROFILE + + "' THEN 1 WHEN '" + + PLAYER_BOOTSTRAP_PROFILE + + "' THEN 2 WHEN '" + + REPRESENTATIVE_PROFILE + + "' THEN 3 ELSE 4 END, token_profile, audience, probe_kind" + + (lock ? " FOR UPDATE" : ""), + operationId); + List entries = new ArrayList<>(rows.size()); + for (Record row : rows) { + entries.add(decodeEntry(row)); + } + return List.copyOf(entries); + } + + // V1 digests bind the established canary/control/player/delegation profile order. V2 adds + // validator identity as the leading key; per-Pod requirements remain separately bound rows. + private static final Comparator PROBE_ENTRY_ORDER = + Comparator.comparing(ProbeEntry::validatorId) + .thenComparingInt(entry -> profileOrder(entry.tokenProfile())) + .thenComparing(ProbeEntry::audience) + .thenComparing(entry -> entry.probeKind().name()); + + private static int profileOrder(String profile) { + if (CANARY_PROFILE.equals(profile)) return 0; + if (CONTROL_UI_PROFILE.equals(profile)) return 1; + if (PLAYER_BOOTSTRAP_PROFILE.equals(profile)) return 2; + if (REPRESENTATIVE_PROFILE.equals(profile)) return 3; + throw new QuarantinedStateException("Readiness probe profile has no canonical plan order"); + } + + private ProbeEntry selectEntry( + UUID operationId, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + boolean lock) { + Record row = + dsl.fetchOne( + "SELECT * FROM " + + ENTRY_TABLE + + " WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ?" + + (lock ? " FOR UPDATE" : ""), + operationId, + validatorId, + tokenProfile, + audience, + probeKind.name()); + return row == null ? null : decodeEntry(row); + } + + private ProbeEntry selectEntry(ProbeEntry entry, boolean lock) { + return selectEntry( + entry.rotationOperationId(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + lock); + } + + private ProbeEntry decodeEntry(Record row) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + Optional expectedActive = decodeActive(activeGeneration, activeKid); + Long attemptAt = row.get("signing_attempted_at_epoch_seconds", Long.class); + String hash = row.get("compact_token_sha256", String.class); + String terminalOutcome = row.get("terminal_outcome", String.class); + VerificationReceipt receipt = decodeVerificationReceipt(row); + return new ProbeEntry( + row.get("rotation_operation_id", UUID.class), + row.get("plan_digest", String.class), + row.get("validator_id", String.class), + row.get("token_profile", String.class), + row.get("audience", String.class), + ProbeKind.valueOf(row.get("probe_kind", String.class)), + row.get("jti", UUID.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + expectedActive, + row.get("registry_version", Short.class).intValue(), + row.get("entry_version", Long.class), + row.get("planned_issued_at_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + ProbeState.valueOf(row.get("state", String.class)), + Optional.ofNullable(terminalOutcome), + Optional.ofNullable(attemptAt), + Optional.ofNullable(hash), + Optional.ofNullable(receipt)); + } + + private VerificationReceipt decodeVerificationReceipt(Record row) { + Short version = row.get("verification_receipt_version", Short.class); + Long sourceVersion = row.get("verification_source_entry_version", Long.class); + Long verifiedAt = row.get("verified_at_epoch_seconds", Long.class); + String verifiedKid = row.get("verified_kid", String.class); + String validatorInstanceId = row.get("validator_instance_id", String.class); + String bindingDigest = row.get("validator_binding_digest", String.class); + String configRevision = row.get("validator_config_revision", String.class); + String peerUri = row.get("validator_peer_uri", String.class); + String peerSpki = row.get("validator_peer_spki_sha256", String.class); + String receiptSha256 = row.get("verification_receipt_sha256", String.class); + Short podReceiptCount = row.get("pod_receipt_count", Short.class); + String podReceiptClosureSha256 = row.get("pod_receipt_closure_sha256", String.class); + if (version == null + && sourceVersion == null + && verifiedAt == null + && verifiedKid == null + && validatorInstanceId == null + && bindingDigest == null + && configRevision == null + && peerUri == null + && peerSpki == null + && receiptSha256 == null + && podReceiptCount == null + && podReceiptClosureSha256 == null) { + return null; + } + if (version == null + || sourceVersion == null + || verifiedAt == null + || validatorInstanceId == null + || bindingDigest == null + || configRevision == null + || peerUri == null + || peerSpki == null + || receiptSha256 == null) { + throw new QuarantinedStateException("Readiness verification receipt is partial"); + } + if ((version == 1 + && (verifiedKid == null || podReceiptCount != null || podReceiptClosureSha256 != null)) + || (version == 2 && (podReceiptCount == null || podReceiptClosureSha256 == null))) { + throw new QuarantinedStateException("Readiness verification receipt version is partial"); + } + Long resultVersion = Math.addExact(sourceVersion, 1L); + return new VerificationReceipt( + version.intValue(), + sourceVersion, + resultVersion, + verifiedAt, + receiptSha256, + verifiedKid, + validatorInstanceId, + bindingDigest, + configRevision, + peerUri, + peerSpki, + podReceiptCount == null ? 0 : podReceiptCount.intValue(), + podReceiptClosureSha256); + } + + private ReadinessProbePlan decodePlan(Record row, List entries) { + Long activeGeneration = row.get("expected_active_generation", Long.class); + String activeKid = row.get("expected_active_kid", String.class); + Long publishedGeneration = row.get("expected_published_generation", Long.class); + String publishedKid = row.get("expected_published_kid", String.class); + SignerFence fence = + new SignerFence( + decodeActive(activeGeneration, activeKid), + decodeActive(publishedGeneration, publishedKid)); + return new ReadinessProbePlan( + row.get("rotation_operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + AccountJwtSignerDesiredStateRepository.CustodyMode + .INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + row.get("generation_receipt_digest", String.class), + row.get("desired_state_version", Long.class), + String.valueOf(row.get("target_generation", Long.class)), + row.get("target_kid", String.class), + row.get("target_public_key_fingerprint", String.class), + fence, + row.get("publication_intent_digest", String.class), + row.get("publication_receipt_digest", String.class), + row.get("mounted_observation_digest", String.class), + row.get("applicability_matrix_json", String.class), + row.get("applicability_matrix_digest", String.class), + row.get("validator_inventory_complete", Boolean.class), + row.get("maximum_cache_age_seconds", Short.class).intValue(), + row.get("planned_at_epoch_seconds", Long.class), + row.get("not_before_epoch_seconds", Long.class), + row.get("expires_at_epoch_seconds", Long.class), + row.get("plan_version", Short.class).intValue(), + row.get("plan_digest", String.class), + entries, + Optional.ofNullable(row.get("inventory_snapshot_digest", String.class))); + } + + private static Optional decodeActive(Long generation, String kid) { + if (generation == null && kid == null) { + return Optional.empty(); + } + if (generation == null || kid == null) { + throw new QuarantinedStateException("Readiness signer fence has a partial active pair"); + } + return Optional.of(new ActiveSigner(generation.toString(), kid)); + } + + private void requirePlanMatchesCurrent(ReadinessProbePlan plan, CurrentEvidence current) { + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = current.publication(); + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = + publication.receipt().orElseThrow(); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication.mountedCorrespondence().orElseThrow(); + if (!plan.operationId().equals(request.operationId()) + || !plan.binding().equals(request.binding()) + || !plan.trustFence().equals(request.trustFence()) + || !plan.operationDigest().equals(request.operationDigest()) + || !plan.generationRequestDigest().equals(result.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(result.receiptDigest()) + || plan.desiredStateVersion() != result.desiredStateVersion() + || !plan.targetGeneration().equals(result.targetGeneration()) + || !plan.targetKid().equals(result.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !plan.expectedFence().durableActive().equals(request.expectedActive()) + || !plan.expectedFence().publishedActive().equals(request.expectedPublishedActive()) + || !plan.publicationIntentDigest().equals(intent.intentDigest()) + || !plan.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !plan.mountedObservationDigest().equals(mount.observationDigest()) + || (plan.planVersion() == 1 + && !plan.applicabilityMatrixJson().equals(applicabilityMatrixJson())) + || !plan.applicabilityMatrixDigest() + .equals(sha256(plan.applicabilityMatrixJson().getBytes(StandardCharsets.UTF_8))) + || (plan.planVersion() == 1 && plan.validatorInventoryComplete()) + || (plan.planVersion() == INVENTORY_PLAN_VERSION && !matchesStoredV2Inventory(plan)) + || !plan.planDigest().equals(planDigest(plan))) { + throw new StaleOperationException( + "Readiness probe plan no longer matches current Account evidence"); + } + } + + private static AccountJwtJwksPublicationRepository.PromotionPublicationEvidence + promotionPublicationEvidence( + AccountJwtJwksPublicationRepository.PublicationEvidence publication) { + return new AccountJwtJwksPublicationRepository.PromotionPublicationEvidence( + publication.intent(), + publication.receipt().orElseThrow(() -> new MissingPublicationEvidenceException()), + publication + .mountedCorrespondence() + .orElseThrow(() -> new MissingPublicationEvidenceException())); + } + + private boolean matchesStoredV2Inventory(ReadinessProbePlan plan) { + String inventoryDigest = plan.inventorySnapshotDigest().orElse(null); + if (inventoryDigest == null) { + return false; + } + AccountJwtValidatorInventoryRepository.StoredSnapshot snapshot = + inventoryRepository.readRequired(inventoryDigest, plan.binding(), plan.trustFence()); + try { + JsonNode matrix = JSON.readTree(plan.applicabilityMatrixJson()); + JsonNode source = matrix == null ? null : matrix.get("source"); + if (matrix == null + || !matrix.isObject() + || !"2".equals(matrix.path("schemaVersion").asText()) + || !inventoryDigest.equals(matrix.path("inventorySnapshotDigest").asText()) + || source == null + || !snapshot.apiBindingRevision().equals(source.path("apiBindingRevision").asText()) + || !snapshot.apiBindingDigest().equals(source.path("apiBindingDigest").asText()) + || !snapshot + .inventoryBindingRevision() + .equals(source.path("inventoryBindingRevision").asText()) + || !snapshot + .inventoryBindingDigest() + .equals(source.path("inventoryBindingDigest").asText()) + || !snapshot.clusterIncarnationUid().equals(source.path("clusterIncarnationUid").asText()) + || !snapshot.namespace().equals(source.path("namespace").asText()) + || !snapshot.namespaceUid().equals(source.path("namespaceUid").asText()) + || !snapshot.environmentId().equals(source.path("environmentId").asText()) + || !snapshot.clusterId().equals(source.path("clusterId").asText())) { + return false; + } + JsonNode validators = matrix.get("validators"); + if (validators == null + || !validators.isArray() + || validators.isEmpty() + || validators.size() > 32) { + return false; + } + if (!plan.validatorInventoryComplete()) { + return "PARTIAL_UNCONFIRMED".equals(matrix.path("inventoryStatus").asText()); + } + if (!"PROTECTED_LIVE_COMPLETE".equals(matrix.path("inventoryStatus").asText()) + || validators.size() != 2) { + return false; + } + JsonNode accountProfiles = null; + JsonNode gameSessionProfiles = null; + for (JsonNode validator : validators) { + String validatorId = validator.path("validatorId").asText(); + if (VALIDATOR_ID.equals(validatorId)) { + accountProfiles = validator.get("applicableProfiles"); + } else if ("game-session-service".equals(validatorId)) { + gameSessionProfiles = validator.get("applicableProfiles"); + } else { + return false; + } + } + return hasExactProfiles(accountProfiles, PRODUCTION_PROFILE_CASES) + && hasExactProfiles( + gameSessionProfiles, + List.of(new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE))); + } catch (Exception failure) { + throw new QuarantinedStateException("V2 readiness inventory matrix cannot be read back"); + } + } + + private static boolean hasExactProfiles(JsonNode node, List expected) { + if (node == null || !node.isArray() || node.size() != expected.size()) { + return false; + } + Set actual = new java.util.HashSet<>(); + for (JsonNode profile : node) { + actual.add( + new ProfileCase( + profile.path("tokenProfile").asText(), profile.path("audience").asText())); + } + return actual.equals(Set.copyOf(expected)); + } + + private static void requirePreparedPlanMatches( + ReadinessProbePlan plan, + GenerationResult generation, + AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence promotion, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication) { + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = publication.receipt(); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication.mountedCorrespondence(); + if (!plan.operationId().equals(generation.operationId()) + || !plan.binding().equals(generation.binding()) + || !plan.trustFence().equals(generation.trustFence()) + || !plan.operationDigest().equals(generation.operationDigest()) + || !plan.generationRequestDigest().equals(generation.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(generation.receiptDigest()) + || plan.desiredStateVersion() != generation.desiredStateVersion() + || !plan.targetGeneration().equals(generation.targetGeneration()) + || !plan.targetKid().equals(generation.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(generation.publicKeyFingerprint()) + || !plan.expectedFence().durableActive().equals(promotion.expectedPreviousActive()) + || !plan.expectedFence().publishedActive().equals(promotion.expectedPublishedActive()) + || !plan.publicationIntentDigest().equals(intent.intentDigest()) + || !plan.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !plan.mountedObservationDigest().equals(mount.observationDigest()) + || !plan.planDigest().equals(promotion.readinessPlanDigest()) + || !intent.operationId().equals(generation.operationId()) + || !receipt.operationId().equals(generation.operationId()) + || !mount.operationId().equals(generation.operationId()) + || !promotion.prepublicationIntentDigest().equals(intent.intentDigest()) + || !promotion.prepublicationReceiptDigest().equals(receipt.receiptDigest()) + || !promotion.mountedObservationDigest().equals(mount.observationDigest()) + || !promotion.publicConfigMapUid().equals(intent.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(receipt.observedResourceVersion()) + || !promotion.expectedPublicJwksJson().equals(intent.jwksJson()) + || !promotion.apiBindingDigest().equals(intent.apiBindingDigest()) + || !promotion.apiConfigRevision().equals(intent.apiConfigRevision()) + || !plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException( + "Prepared readiness evidence differs from exact Account generation/publication owner records"); + } + } + + private CurrentEvidence lockCurrentEvidence(Binding binding, TrustFence trust) { + Objects.requireNonNull(binding, "Account signer binding is required"); + Objects.requireNonNull(trust, "Current signer trust fence is required"); + GenerationRequest request = desiredStateRepository.readCurrentGenerationRequest(binding, trust); + GenerationResult result = desiredStateRepository.readCurrentGenerationResult(binding, trust); + DesiredState state = desiredStateRepository.read(binding); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = + publicationRepository + .readCurrentPublication(binding, trust) + .orElseThrow(() -> new MissingPublicationEvidenceException()); + if (request.phase() != GenerationPhase.GENERATION_RECORDED + || state.preparedOperationId().isPresent() + || !state.generationOperationId().equals(Optional.of(request.operationId())) + || !request.operationId().equals(result.operationId()) + || !request.binding().equals(binding) + || !result.binding().equals(binding) + || !request.trustFence().equals(trust) + || !result.trustFence().equals(trust) + || state.recordVersion() != result.desiredStateVersion() + || !request.targetGeneration().equals(result.targetGeneration()) + || !request.targetKid().equals(result.targetKid()) + || !request.expectedActive().equals(state.durableActive()) + || !request.expectedPublishedActive().equals(state.publishedActive()) + || !state.durableActive().equals(state.publishedActive())) { + throw new StaleOperationException( + "Current Account JWT signer evidence is incomplete or changed"); + } + AccountJwtJwksPublicationRepository.PrepublicationIntent intent = publication.intent(); + AccountJwtJwksPublicationRepository.PublicationReceipt receipt = + publication.receipt().orElseThrow(() -> new MissingPublicationEvidenceException()); + AccountJwtJwksPublicationRepository.MountObservation mount = + publication + .mountedCorrespondence() + .orElseThrow(() -> new MissingPublicationEvidenceException()); + if (!intent.operationId().equals(result.operationId()) + || !intent.operationDigest().equals(result.operationDigest()) + || !intent.generationRequestDigest().equals(result.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(result.receiptDigest()) + || !intent.targetGeneration().equals(result.targetGeneration()) + || !intent.targetKid().equals(result.targetKid()) + || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !receipt.operationId().equals(result.operationId()) + || !receipt.intentDigest().equals(intent.intentDigest()) + || !mount.operationId().equals(result.operationId()) + || !mount.intentDigest().equals(intent.intentDigest()) + || !mount.publicationReceiptDigest().equals(receipt.receiptDigest()) + || !mount.publicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw new StaleOperationException( + "Account JWT publication evidence is not exact for readiness"); + } + return new CurrentEvidence(state, request, result, publication); + } + + private ReadinessProbePlan requireStoredPlan(CurrentEvidence current) { + ReadinessProbePlan plan = selectPlan(current.request().operationId(), true); + if (plan == null) { + throw new MissingPlanException("Account JWT readiness probe plan is missing"); + } + requirePlanMatchesCurrent(plan, current); + return readbackPlan(plan, true); + } + + private static void requireCurrentOperation(CurrentEvidence current, String operationId) { + if (!current.request().operationId().toString().equals(operationId)) { + throw new StaleOperationException("Readiness probe belongs to a stale Account operation"); + } + } + + private static void requireSignedResultMatches( + ReadinessProbePlan plan, ProbeEntry entry, SignedProbeDigest signed) { + if (entry == null + || !signed.operationId().equals(plan.operationId().toString()) + || !signed.validatorId().equals(entry.validatorId()) + || signed.probeKind() != entry.probeKind() + || !signed.tokenProfile().equals(entry.tokenProfile()) + || !signed.audience().equals(entry.audience()) + || !signed.jti().equals(entry.jti()) + || !signed.targetGeneration().equals(entry.targetGeneration()) + || !signed.targetKid().equals(entry.targetKid()) + || !signed.publicKeyFingerprint().equals(plan.targetPublicKeyFingerprint()) + || signed.issuedAtEpochSecond() != entry.plannedIssuedAtEpochSecond() + || signed.expiresAtEpochSecond() != entry.expiresAtEpochSecond() + || !SHA256.matcher(signed.compactTokenSha256()).matches()) { + throw new IdempotencyConflictException( + "Mounted readiness signature does not match its exact plan"); + } + } + + private static VerificationReceipt verificationReceipt( + ReadinessProbePlan plan, + ProbeEntry entry, + VerifiedProbeObservation observation, + long resultEntryVersion) { + Map fields = new LinkedHashMap<>(); + fields.put("receiptVersion", 1); + fields.put("rotationOperationId", plan.operationId().toString()); + fields.put("planDigest", plan.planDigest()); + fields.put("operationDigest", plan.operationDigest()); + fields.put("generationRequestDigest", plan.generationRequestDigest()); + fields.put("generationReceiptDigest", plan.generationReceiptDigest()); + fields.put("desiredStateVersion", plan.desiredStateVersion()); + fields.put("environmentId", plan.binding().environmentId()); + fields.put("clusterId", plan.binding().clusterId()); + fields.put("namespace", plan.binding().namespace()); + fields.put( + "trustFence", + Map.of( + "clusterIncarnationUid", plan.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", plan.trustFence().expectedNamespaceUid(), + "bindingDigest", plan.trustFence().bindingDigest(), + "configRevision", plan.trustFence().configRevision())); + fields.put("targetGeneration", entry.targetGeneration()); + fields.put("targetKid", entry.targetKid()); + fields.put("targetPublicKeyFingerprint", plan.targetPublicKeyFingerprint()); + fields.put("expectedActive", activeMap(plan.expectedFence().durableActive())); + fields.put("expectedPublishedActive", activeMap(plan.expectedFence().publishedActive())); + fields.put("validatorId", entry.validatorId()); + fields.put("tokenProfile", entry.tokenProfile()); + fields.put("audience", entry.audience()); + fields.put("probeKind", entry.probeKind().name()); + fields.put("jti", entry.jti().toString()); + fields.put("registryVersion", entry.registryVersion()); + fields.put("sourceEntryVersion", entry.entryVersion()); + fields.put("resultEntryVersion", resultEntryVersion); + fields.put("issuedAtEpochSecond", entry.plannedIssuedAtEpochSecond()); + fields.put("expiresAtEpochSecond", entry.expiresAtEpochSecond()); + fields.put("compactTokenSha256", observation.compactTokenSha256()); + fields.put("verifiedKid", observation.verifiedKid()); + fields.put("validatorInstanceId", observation.validatorInstanceId()); + fields.put("validatorBindingDigest", observation.validatorBindingDigest()); + fields.put("validatorConfigRevision", observation.validatorConfigRevision()); + fields.put("validatorPeerUri", observation.validatorPeerUri()); + fields.put("validatorPeerSpkiSha256", observation.validatorPeerSpkiSha256()); + fields.put("observedAtEpochSecond", observation.observedAtEpochSecond()); + return new VerificationReceipt( + 1, + entry.entryVersion(), + resultEntryVersion, + observation.observedAtEpochSecond(), + digest(fields), + observation.verifiedKid(), + observation.validatorInstanceId(), + observation.validatorBindingDigest(), + observation.validatorConfigRevision(), + observation.validatorPeerUri(), + observation.validatorPeerSpkiSha256()); + } + + private static void requireMatchingObservation( + VerificationReceipt receipt, VerifiedProbeObservation observation) { + if (!receipt.verifiedKid().equals(observation.verifiedKid()) + || !receipt.validatorInstanceId().equals(observation.validatorInstanceId()) + || !receipt.validatorBindingDigest().equals(observation.validatorBindingDigest()) + || !receipt.validatorConfigRevision().equals(observation.validatorConfigRevision()) + || !receipt.validatorPeerUri().equals(observation.validatorPeerUri()) + || !receipt.validatorPeerSpkiSha256().equals(observation.validatorPeerSpkiSha256())) { + throw new IdempotencyConflictException( + "Readiness verification retry differs from its immutable authenticated receipt"); + } + } + + private void requireNotExpired(ProbeEntry entry, long nowEpoch) { + if (nowEpoch >= entry.expiresAtEpochSecond()) { + throw new ProbeExpiredException(); + } + } + + static String applicabilityMatrixJson() { + List> applicableProfiles = + List.of( + Map.of("audience", CONTROL_UI_AUDIENCE, "tokenProfile", CONTROL_UI_PROFILE), + Map.of( + "audience", PLAYER_BOOTSTRAP_AUDIENCE, + "tokenProfile", PLAYER_BOOTSTRAP_PROFILE), + Map.of("audience", REPRESENTATIVE_AUDIENCE, "tokenProfile", REPRESENTATIVE_PROFILE)); + Map validator = new LinkedHashMap<>(); + validator.put("applicableProfiles", applicableProfiles); + validator.put("validatorId", VALIDATOR_ID); + Map matrix = new LinkedHashMap<>(); + matrix.put("inventoryStatus", INVENTORY_STATUS); + matrix.put("schemaVersion", 1); + matrix.put("validators", List.of(validator)); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(matrix)), + StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new StorageUnavailableException( + "Readiness applicability matrix cannot be canonicalized"); + } + } + + private static String applicabilityMatrixJson( + InventorySnapshot snapshot, boolean inventoryComplete) { + List> validators = + snapshot.validators().stream() + .sorted(java.util.Comparator.comparing(ValidatorObservation::validatorId)) + .map( + validator -> { + List> applicable = + validator.profiles().stream() + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .sorted( + java.util.Comparator.comparing( + (Map value) -> + value.get("tokenProfile").toString()) + .thenComparing(value -> value.get("audience").toString())) + .toList(); + List> inapplicable = + PRODUCTION_PROFILE_CASES.stream() + .filter( + profile -> + validator.profiles().stream() + .noneMatch( + actual -> + actual.tokenProfile().equals(profile.tokenProfile()) + && actual.audience().equals(profile.audience()))) + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .toList(); + Map value = new LinkedHashMap<>(); + value.put("applicableProfiles", applicable); + value.put("deploymentUid", validator.deploymentUid()); + value.put("image", validator.image()); + value.put("podCount", validator.pods().size()); + value.put( + "pods", + validator.pods().stream() + .sorted(java.util.Comparator.comparing(PodObservation::uid)) + .map( + pod -> + Map.of( + "podUid", pod.uid(), + "podIp", pod.podIp(), + "exactPodEndpoint", pod.endpoint().toString(), + "canonicalServiceUri", pod.receiverServiceUri(), + "leafSpkiSha256", pod.leafSpkiSha256(), + "image", pod.image(), + "verifierConfigSha256", pod.verifierConfigSha256())) + .toList()); + value.put("inapplicableProfiles", inapplicable); + value.put("validatorId", validator.validatorId()); + value.put("verifierConfigSha256", validator.verifierConfigSha256()); + return value; + }) + .toList(); + Map source = new LinkedHashMap<>(); + source.put("apiBindingDigest", snapshot.apiBindingDigest()); + source.put("apiBindingRevision", snapshot.apiBindingRevision()); + source.put("clusterIncarnationUid", snapshot.clusterIncarnationUid()); + source.put("clusterId", snapshot.clusterId()); + source.put("environmentId", snapshot.environmentId()); + source.put("inventoryBindingDigest", snapshot.inventoryBindingDigest()); + source.put("inventoryBindingRevision", snapshot.inventoryBindingRevision()); + source.put("namespace", snapshot.namespace()); + source.put("namespaceUid", snapshot.namespaceUid()); + Map matrix = new LinkedHashMap<>(); + matrix.put("inventoryStatus", inventoryComplete ? "PROTECTED_LIVE_COMPLETE" : INVENTORY_STATUS); + matrix.put("inventorySnapshotDigest", snapshot.digest()); + matrix.put( + "productionProfiles", + PRODUCTION_PROFILE_CASES.stream() + .map( + profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .toList()); + matrix.put("schemaVersion", INVENTORY_PLAN_VERSION); + matrix.put("source", source); + matrix.put("validators", validators); + try { + String canonical = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(matrix)), + StandardCharsets.UTF_8); + if (canonical.getBytes(StandardCharsets.UTF_8).length > 8192) { + throw new InventoryPlanConflictException(); + } + return canonical; + } catch (IOException ex) { + throw new StorageUnavailableException( + "Readiness inventory applicability matrix cannot be canonicalized"); + } + } + + private static boolean inventoryPlanComplete(InventorySnapshot snapshot) { + Map> actual = new LinkedHashMap<>(); + for (ValidatorObservation validator : snapshot.validators()) { + Set profiles = new java.util.HashSet<>(); + for (var profile : validator.profiles()) { + ProfileCase candidate = new ProfileCase(profile.tokenProfile(), profile.audience()); + if (!PRODUCTION_PROFILE_CASES.contains(candidate) || !profiles.add(candidate)) { + return false; + } + } + if (validator.pods().isEmpty() + || actual.putIfAbsent(validator.validatorId(), profiles) != null) { + return false; + } + } + Set accountProfiles = actual.get(VALIDATOR_ID); + Set gameSessionProfiles = actual.get("game-session-service"); + return actual.keySet().equals(Set.of(VALIDATOR_ID, "game-session-service")) + && accountProfiles != null + && accountProfiles.equals(Set.copyOf(PRODUCTION_PROFILE_CASES)) + && gameSessionProfiles != null + && gameSessionProfiles.equals( + Set.of(new ProfileCase(REPRESENTATIVE_PROFILE, REPRESENTATIVE_AUDIENCE))); + } + + private static List expectedPods( + ReadinessProbePlan plan, InventorySnapshot snapshot) { + List expected = new ArrayList<>(); + for (ProbeEntry entry : plan.entries()) { + ValidatorObservation validator = + snapshot.validators().stream() + .filter(value -> value.validatorId().equals(entry.validatorId())) + .findFirst() + .orElseThrow(InventoryPlanConflictException::new); + ProbeExpectation expectation = + entry.probeKind() == ProbeKind.CANARY + ? ProbeExpectation.ACCEPT + : validator.profiles().stream() + .anyMatch( + profile -> + profile.tokenProfile().equals(entry.tokenProfile()) + && profile.audience().equals(entry.audience())) + ? ProbeExpectation.ACCEPT + : ProbeExpectation.INAPPLICABLE_REJECT; + for (PodObservation pod : validator.pods()) { + PodTarget target = + new PodTarget( + snapshot.digest(), + snapshot.environmentId(), + snapshot.clusterId(), + snapshot.clusterIncarnationUid(), + snapshot.namespace(), + snapshot.namespaceUid(), + snapshot.apiBindingRevision(), + snapshot.apiBindingDigest(), + snapshot.inventoryBindingRevision(), + snapshot.inventoryBindingDigest(), + validator.validatorId(), + validator.deploymentUid(), + pod.uid(), + pod.podIp(), + pod.image(), + pod.verifierConfigSha256(), + plan.applicabilityMatrixDigest(), + expectation, + Optional.of(pod.endpoint()), + Optional.of(pod.receiverServiceUri()), + Optional.of(pod.leafSpkiSha256())); + expected.add( + new ExpectedPod( + plan.operationId(), + plan.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + entry.jti(), + target)); + } + } + if (expected.isEmpty() || expected.size() > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new InventoryPlanConflictException(); + } + return List.copyOf(expected); + } + + private static String planDigest( + CurrentEvidence current, + String matrixJson, + String matrixDigest, + int planVersion, + boolean validatorInventoryComplete, + long plannedAt, + long notBefore, + long expiresAt, + List entries, + Optional inventorySnapshotDigest) { + Map preimage = new LinkedHashMap<>(); + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + AccountJwtJwksPublicationRepository.PublicationEvidence publication = current.publication(); + preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v" + planVersion); + preimage.put("rotationOperationId", request.operationId().toString()); + preimage.put("environmentId", request.binding().environmentId()); + preimage.put("clusterId", request.binding().clusterId()); + preimage.put("namespace", request.binding().namespace()); + preimage.put("custodyMode", request.binding().mode().value()); + preimage.put("operationDigest", request.operationDigest()); + preimage.put("generationRequestDigest", result.generationRequestDigest()); + preimage.put("generationReceiptDigest", result.receiptDigest()); + preimage.put("desiredStateVersion", result.desiredStateVersion()); + preimage.put( + "trustFence", + Map.of( + "clusterIncarnationUid", request.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", request.trustFence().expectedNamespaceUid(), + "bindingDigest", request.trustFence().bindingDigest(), + "configRevision", request.trustFence().configRevision())); + preimage.put("targetGeneration", result.targetGeneration()); + preimage.put("targetKid", result.targetKid()); + preimage.put("targetPublicKeyFingerprint", result.publicKeyFingerprint()); + preimage.put("expectedActive", activeMap(request.expectedActive())); + preimage.put("expectedPublishedActive", activeMap(request.expectedPublishedActive())); + preimage.put("publicationIntentDigest", publication.intent().intentDigest()); + preimage.put("publicationReceiptDigest", publication.receipt().orElseThrow().receiptDigest()); + preimage.put( + "mountedObservationDigest", + publication.mountedCorrespondence().orElseThrow().observationDigest()); + preimage.put("applicabilityMatrixJson", matrixJson); + preimage.put("applicabilityMatrixDigest", matrixDigest); + preimage.put("validatorInventoryComplete", validatorInventoryComplete); + if (planVersion != 1) { + preimage.put("planVersion", planVersion); + } + inventorySnapshotDigest.ifPresent(digest -> preimage.put("inventorySnapshotDigest", digest)); + preimage.put("maximumCacheAgeSeconds", MAX_VALIDATOR_CACHE_AGE_SECONDS); + preimage.put("plannedAtEpochSecond", plannedAt); + preimage.put("notBeforeEpochSecond", notBefore); + preimage.put("expiresAtEpochSecond", expiresAt); + preimage.put( + "entries", + entries.stream().map(AccountJwtReadinessProbeRepository::entryDigestMap).toList()); + return digest(preimage); + } + + private static String planDigest(ReadinessProbePlan plan) { + Map preimage = planDigestMap(plan); + return digest(preimage); + } + + private static Map planDigestMap(ReadinessProbePlan plan) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-readiness-probe-plan/v" + plan.planVersion()); + preimage.put("rotationOperationId", plan.operationId().toString()); + preimage.put("environmentId", plan.binding().environmentId()); + preimage.put("clusterId", plan.binding().clusterId()); + preimage.put("namespace", plan.binding().namespace()); + preimage.put("custodyMode", plan.binding().mode().value()); + preimage.put("operationDigest", plan.operationDigest()); + preimage.put("generationRequestDigest", plan.generationRequestDigest()); + preimage.put("generationReceiptDigest", plan.generationReceiptDigest()); + preimage.put("desiredStateVersion", plan.desiredStateVersion()); + preimage.put( + "trustFence", + Map.of( + "clusterIncarnationUid", plan.trustFence().expectedClusterIncarnationUid(), + "namespaceUid", plan.trustFence().expectedNamespaceUid(), + "bindingDigest", plan.trustFence().bindingDigest(), + "configRevision", plan.trustFence().configRevision())); + preimage.put("targetGeneration", plan.targetGeneration()); + preimage.put("targetKid", plan.targetKid()); + preimage.put("targetPublicKeyFingerprint", plan.targetPublicKeyFingerprint()); + preimage.put("expectedActive", activeMap(plan.expectedFence().durableActive())); + preimage.put("expectedPublishedActive", activeMap(plan.expectedFence().publishedActive())); + preimage.put("publicationIntentDigest", plan.publicationIntentDigest()); + preimage.put("publicationReceiptDigest", plan.publicationReceiptDigest()); + preimage.put("mountedObservationDigest", plan.mountedObservationDigest()); + preimage.put("applicabilityMatrixJson", plan.applicabilityMatrixJson()); + preimage.put("applicabilityMatrixDigest", plan.applicabilityMatrixDigest()); + preimage.put("validatorInventoryComplete", plan.validatorInventoryComplete()); + if (plan.planVersion() != 1) { + preimage.put("planVersion", plan.planVersion()); + } + plan.inventorySnapshotDigest() + .ifPresent(digest -> preimage.put("inventorySnapshotDigest", digest)); + preimage.put("maximumCacheAgeSeconds", plan.maximumCacheAgeSeconds()); + preimage.put("plannedAtEpochSecond", plan.plannedAtEpochSecond()); + preimage.put("notBeforeEpochSecond", plan.notBeforeEpochSecond()); + preimage.put("expiresAtEpochSecond", plan.expiresAtEpochSecond()); + preimage.put( + "entries", + plan.entries().stream().map(AccountJwtReadinessProbeRepository::entryDigestMap).toList()); + return preimage; + } + + private static Map entryDigestMap(ProbeEntry entry) { + Map item = new LinkedHashMap<>(); + item.put("validatorId", entry.validatorId()); + item.put("tokenProfile", entry.tokenProfile()); + item.put("audience", entry.audience()); + item.put("probeKind", entry.probeKind().name()); + item.put("jti", entry.jti().toString()); + item.put("targetGeneration", entry.targetGeneration()); + item.put("targetKid", entry.targetKid()); + item.put("expectedActive", activeMap(entry.expectedActive())); + item.put("registryVersion", entry.registryVersion()); + item.put("entryVersion", 1); + item.put("plannedIssuedAtEpochSecond", entry.plannedIssuedAtEpochSecond()); + item.put("expiresAtEpochSecond", entry.expiresAtEpochSecond()); + return item; + } + + private static Map activeMap(Optional active) { + if (active.isEmpty()) { + return Map.of("present", false); + } + ActiveSigner signer = active.orElseThrow(); + return Map.of("present", true, "generation", signer.generation(), "kid", signer.kid()); + } + + private static String deliveryClaimDigest(DeliveryClaim claim) { + Map value = new LinkedHashMap<>(); + value.put("rotationOperationId", claim.rotationOperationId().toString()); + value.put("planDigest", claim.planDigest()); + value.put("expectedClusterUid", claim.expectedClusterUid()); + value.put("expectedNamespaceUid", claim.expectedNamespaceUid()); + value.put("materializerTrustBindingDigest", claim.materializerTrustBindingDigest()); + value.put("materializerTrustConfigRevision", claim.materializerTrustConfigRevision()); + value.put("targetGeneration", claim.targetGeneration()); + value.put("targetKid", claim.targetKid()); + value.put("expectedActive", activeMap(claim.expectedActive())); + value.put("readinessBindingDigest", claim.readinessBindingDigest()); + value.put("readinessConfigRevision", claim.readinessConfigRevision()); + value.put( + "readinessBindingValidUntilEpochSecond", claim.readinessBindingValidUntilEpochSecond()); + value.put("validatorId", claim.validatorId()); + value.put("validatorInstanceId", claim.validatorInstanceId()); + value.put("validatorPeerUri", claim.validatorPeerUri()); + value.put("validatorPeerSpkiSha256", claim.validatorPeerSpkiSha256()); + value.put("claimedAtEpochSecond", claim.claimedAtEpochSecond()); + value.put("expiresAtEpochSecond", claim.expiresAtEpochSecond()); + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } catch (IOException failure) { + throw new StorageUnavailableException("Readiness delivery claim cannot be canonicalized"); + } + } + + private static Map readinessPromotionPreimage( + ReadinessProbePlan plan, + GenerationResult generation, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication, + String inventoryEvidenceReference, + String inventoryEvidenceDigest, + List verifiedProbes) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-readiness-promotion-proof/v1"); + preimage.put("plan", planDigestMap(plan)); + preimage.put("planDigest", plan.planDigest()); + preimage.put("generation", generationEvidenceMap(generation)); + preimage.put("publication", promotionPublicationEvidenceMap(publication)); + preimage.put("inventoryEvidenceReference", inventoryEvidenceReference); + preimage.put("inventoryEvidenceDigest", inventoryEvidenceDigest); + preimage.put( + "verifiedProbes", + verifiedProbes.stream() + .map(AccountJwtReadinessProbeRepository::verifiedProbeEvidenceMap) + .toList()); + return preimage; + } + + private static byte[] readinessPromotionPreimageBytes(Map preimage) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + } catch (IOException ex) { + throw new StorageUnavailableException("Readiness evidence cannot be canonicalized"); + } + } + + private static String readinessPromotionDigest(byte[] preimage) { + return sha256(preimage); + } + + private static Map generationEvidenceMap(GenerationResult result) { + Map value = new LinkedHashMap<>(); + value.put("operationId", result.operationId().toString()); + value.put("environmentId", result.binding().environmentId()); + value.put("clusterId", result.binding().clusterId()); + value.put("namespace", result.binding().namespace()); + value.put("custodyMode", result.binding().mode().value()); + value.put("operationDigest", result.operationDigest()); + value.put("generationRequestDigest", result.generationRequestDigest()); + value.put("desiredStateVersion", result.desiredStateVersion()); + value.put("trustFence", trustFenceMap(result.trustFence())); + value.put("privateSecretName", result.privateSecretName()); + value.put("secretUid", result.secretUid()); + value.put("expectedPriorResourceVersion", result.expectedPriorResourceVersion()); + value.put("observedResourceVersion", result.observedResourceVersion()); + value.put("targetGeneration", result.targetGeneration()); + value.put("targetKid", result.targetKid()); + value.put("targetAlgorithm", result.targetAlgorithm()); + value.put("publicKeyFingerprint", result.publicKeyFingerprint()); + value.put("publicJwkJson", result.publicJwkJson()); + value.put("receiptDigest", result.receiptDigest()); + return value; + } + + private static Map trustFenceMap(TrustFence trust) { + return Map.of( + "clusterIncarnationUid", trust.expectedClusterIncarnationUid(), + "namespaceUid", trust.expectedNamespaceUid(), + "bindingDigest", trust.bindingDigest(), + "configRevision", trust.configRevision()); + } + + private static Map promotionPublicationEvidenceMap( + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence evidence) { + var intent = evidence.intent(); + var receipt = evidence.receipt(); + var mount = evidence.mountedCorrespondence(); + Map intentValue = new LinkedHashMap<>(); + intentValue.put("operationId", intent.operationId().toString()); + intentValue.put("environmentId", intent.binding().environmentId()); + intentValue.put("clusterId", intent.binding().clusterId()); + intentValue.put("namespace", intent.binding().namespace()); + intentValue.put("operationDigest", intent.operationDigest()); + intentValue.put("generationRequestDigest", intent.generationRequestDigest()); + intentValue.put("generationReceiptDigest", intent.generationReceiptDigest()); + intentValue.put("desiredStateVersion", intent.desiredStateVersion()); + intentValue.put("trustFence", trustFenceMap(intent.trustFence())); + intentValue.put("apiBindingDigest", intent.apiBindingDigest()); + intentValue.put("apiConfigRevision", intent.apiConfigRevision()); + intentValue.put("configMapName", intent.configMapName()); + intentValue.put("configMapUid", intent.configMapUid()); + intentValue.put("expectedResourceVersion", intent.expectedResourceVersion()); + intentValue.put("expectedSnapshotDigest", intent.expectedSnapshotDigest()); + intentValue.put("targetGeneration", intent.targetGeneration()); + intentValue.put("targetKid", intent.targetKid()); + intentValue.put("publicKeyFingerprint", intent.publicKeyFingerprint()); + intentValue.put("expectedDurableActive", activeMap(intent.expectedDurableActive())); + intentValue.put("expectedPublishedActive", activeMap(intent.expectedPublishedActive())); + intentValue.put("publicDataDigest", intent.publicDataDigest()); + intentValue.put("generationMarkerDigest", intent.generationMarkerDigest()); + intentValue.put("intentDigest", intent.intentDigest()); + + Map receiptValue = new LinkedHashMap<>(); + receiptValue.put("operationId", receipt.operationId().toString()); + receiptValue.put("intentDigest", receipt.intentDigest()); + receiptValue.put("configMapUid", receipt.configMapUid()); + receiptValue.put("expectedResourceVersion", receipt.expectedResourceVersion()); + receiptValue.put("observedResourceVersion", receipt.observedResourceVersion()); + receiptValue.put("publicDataDigest", receipt.publicDataDigest()); + receiptValue.put("receiptDigest", receipt.receiptDigest()); + + Map mountValue = new LinkedHashMap<>(); + mountValue.put("operationId", mount.operationId().toString()); + mountValue.put("intentDigest", mount.intentDigest()); + mountValue.put("publicationReceiptDigest", mount.publicationReceiptDigest()); + mountValue.put("generationMarkerDigest", mount.generationMarkerDigest()); + mountValue.put("publicDataDigest", mount.publicDataDigest()); + mountValue.put("publicKeyFingerprint", mount.publicKeyFingerprint()); + mountValue.put("observationDigest", mount.observationDigest()); + return Map.of("intent", intentValue, "receipt", receiptValue, "mount", mountValue); + } + + private static Map verifiedProbeEvidenceMap(VerifiedProbeEvidence probe) { + VerificationReceipt receipt = probe.receipt(); + Map value = new LinkedHashMap<>(); + value.put("rotationOperationId", probe.rotationOperationId().toString()); + value.put("planDigest", probe.planDigest()); + value.put("validatorId", probe.validatorId()); + value.put("tokenProfile", probe.tokenProfile()); + value.put("audience", probe.audience()); + value.put("probeKind", probe.probeKind().name()); + value.put("jti", probe.jti().toString()); + value.put("targetGeneration", probe.targetGeneration()); + value.put("targetKid", probe.targetKid()); + value.put("expectedActive", activeMap(probe.expectedActive())); + value.put("registryVersion", probe.registryVersion()); + value.put("entryVersion", probe.entryVersion()); + value.put("plannedIssuedAtEpochSecond", probe.plannedIssuedAtEpochSecond()); + value.put("expiresAtEpochSecond", probe.expiresAtEpochSecond()); + value.put("compactTokenSha256", probe.compactTokenSha256()); + Map receiptValue = new LinkedHashMap<>(); + receiptValue.put("receiptVersion", receipt.receiptVersion()); + receiptValue.put("sourceEntryVersion", receipt.sourceEntryVersion()); + receiptValue.put("resultEntryVersion", receipt.resultEntryVersion()); + receiptValue.put("observedAtEpochSecond", receipt.observedAtEpochSecond()); + receiptValue.put("receiptSha256", receipt.receiptSha256()); + receiptValue.put("verifiedKid", receipt.verifiedKid()); + receiptValue.put("validatorInstanceId", receipt.validatorInstanceId()); + receiptValue.put("validatorBindingDigest", receipt.validatorBindingDigest()); + receiptValue.put("validatorConfigRevision", receipt.validatorConfigRevision()); + receiptValue.put("validatorPeerUri", receipt.validatorPeerUri()); + receiptValue.put("validatorPeerSpkiSha256", receipt.validatorPeerSpkiSha256()); + receiptValue.put("podReceiptCount", receipt.podReceiptCount()); + receiptValue.put("podReceiptClosureSha256", receipt.podReceiptClosureSha256()); + value.put("verificationReceipt", receiptValue); + return value; + } + + private static String digest(Map value) { + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } catch (IOException ex) { + throw new StorageUnavailableException("Readiness evidence cannot be canonicalized"); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new StorageUnavailableException("SHA-256 is unavailable"); + } + } + + private static long exactEpochSecond(Instant instant) { + Objects.requireNonNull(instant, "Readiness timestamp is required"); + if (instant.getNano() != 0 || instant.getEpochSecond() <= 0L) { + throw new IllegalArgumentException("Readiness time must be a positive exact epoch second"); + } + return instant.getEpochSecond(); + } + + private static long add(long value, long amount) { + try { + return Math.addExact(value, amount); + } catch (ArithmeticException ex) { + throw new IllegalArgumentException("Readiness timestamp overflow", ex); + } + } + + private static void requireOperationId(UUID operationId) { + if (operationId == null || operationId.version() != 4 || operationId.variant() != 2) { + throw new IllegalArgumentException("Account JWT readiness operation ID must be UUIDv4"); + } + } + + private static String requireCanonicalKubeUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + String canonical = parsed.toString(); + if (!canonical.equals(value) + || parsed.equals(new UUID(0L, 0L)) + || parsed.version() < 1 + || parsed.version() > 8 + || parsed.variant() != 2) { + throw new IllegalArgumentException(); + } + return canonical; + } catch (RuntimeException invalid) { + throw new QuarantinedStateException(label + " is malformed"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("An owning Account transaction is required"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("A writable Account transaction is required"); + } + } + + private static void insertOne(DSLContext dsl, String table, Map fields) { + String columns = String.join(", ", fields.keySet()); + String placeholders = String.join(", ", java.util.Collections.nCopies(fields.size(), "?")); + dsl.execute( + "INSERT INTO " + table + " (" + columns + ") VALUES (" + placeholders + ")", + fields.values().toArray()); + } + + private record CurrentEvidence( + DesiredState state, + GenerationRequest request, + GenerationResult result, + AccountJwtJwksPublicationRepository.PublicationEvidence publication) {} + + private record ProfileCase(String tokenProfile, String audience) {} + + /** Exact immutable per-Pod requirement for one logical registry entry. */ + public record ExpectedPod( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + PodTarget target) { + public ExpectedPod { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "expected Pod plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + Objects.requireNonNull(target); + if (jti.version() != 4 || jti.variant() != 2 || !validatorId.equals(target.validatorId())) { + throw new QuarantinedStateException("Expected readiness Pod binding is malformed"); + } + } + } + + /** Owner-derived current plan, ISSUED entry, and exact expected Pod; contains no JWT. */ + public record OwnerProbeEvidence( + ReadinessProbePlan plan, ProbeEntry entry, ExpectedPod expectedPod) { + public OwnerProbeEvidence { + Objects.requireNonNull(plan); + Objects.requireNonNull(entry); + Objects.requireNonNull(expectedPod); + if (plan.planVersion() != INVENTORY_PLAN_VERSION + || !plan.validatorInventoryComplete() + || entry.state() != ProbeState.ISSUED + || !plan.operationId().equals(entry.rotationOperationId()) + || !plan.planDigest().equals(entry.planDigest()) + || !entry.rotationOperationId().equals(expectedPod.rotationOperationId()) + || !entry.planDigest().equals(expectedPod.planDigest()) + || !entry.jti().equals(expectedPod.jti())) { + throw new ReceiverUnavailableException(); + } + } + } + + /** Immutable digest-covered one-Pod verifier receipt; no token or private key material. */ + private record PodReceipt( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + String podUid, + UUID jti, + long sourceEntryVersion, + String compactTokenSha256, + String targetGeneration, + String targetKid, + Optional expectedActive, + ProbeExpectation outcome, + String observedPodUid, + String image, + String verifierConfigSha256, + String verifiedKid, + URI receiverEndpoint, + String receiverServiceUri, + String receiverPeerSpkiSha256, + long observedAtEpochSecond, + String receiptSha256) { + private PodReceipt { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "per-Pod readiness plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + requireCanonicalKubeUuid(podUid, "per-Pod readiness target UID"); + Objects.requireNonNull(jti); + if (jti.version() != 4 || jti.variant() != 2 || sourceEntryVersion <= 0L) { + throw new QuarantinedStateException("Per-Pod readiness receipt identity is malformed"); + } + requireDigest(compactTokenSha256, "per-Pod readiness token digest"); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + Objects.requireNonNull(outcome); + requireCanonicalKubeUuid(observedPodUid, "observed readiness Pod UID"); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new QuarantinedStateException("Per-Pod verifier image is not pinned"); + } + requireDigest(verifierConfigSha256, "per-Pod verifier config digest"); + if (verifiedKid == null || !verifiedKid.equals(targetKid)) { + throw new QuarantinedStateException("Per-Pod verifier outcome does not match its key ID"); + } + Objects.requireNonNull(receiverEndpoint); + requireDigest(receiverPeerSpkiSha256, "per-Pod receiver SPKI digest"); + if (receiverServiceUri == null + || !receiverServiceUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}") + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Per-Pod receiver identity is malformed"); + } + requireDigest(receiptSha256, "per-Pod readiness receipt digest"); + } + } + + public enum ProbeState { + PLANNED, + ISSUED, + VERIFIED, + CLEANED, + EXPIRED, + ABORTED + } + + public record SignerFence( + Optional durableActive, Optional publishedActive) { + public SignerFence { + durableActive = Objects.requireNonNull(durableActive); + publishedActive = Objects.requireNonNull(publishedActive); + if (!durableActive.equals(publishedActive)) { + throw new QuarantinedStateException("Durable and published signer fences disagree"); + } + } + } + + public record ProbeEntry( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + String targetGeneration, + String targetKid, + Optional expectedActive, + int registryVersion, + long entryVersion, + long plannedIssuedAtEpochSecond, + long expiresAtEpochSecond, + ProbeState state, + Optional terminalOutcome, + Optional signingAttemptedAtEpochSecond, + Optional compactTokenSha256, + Optional verificationReceipt) { + public ProbeEntry { + Objects.requireNonNull(rotationOperationId); + requireDigest(planDigest, "probe plan digest"); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + Objects.requireNonNull(expectedActive); + Objects.requireNonNull(state); + terminalOutcome = Objects.requireNonNull(terminalOutcome); + signingAttemptedAtEpochSecond = Objects.requireNonNull(signingAttemptedAtEpochSecond); + compactTokenSha256 = Objects.requireNonNull(compactTokenSha256); + verificationReceipt = Objects.requireNonNull(verificationReceipt); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + requireGeneration(targetGeneration); + requireKid(targetKid); + if (jti.version() != 4 + || jti.variant() != 2 + || registryVersion != 1 + || entryVersion <= 0L + || plannedIssuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= plannedIssuedAtEpochSecond + || expiresAtEpochSecond - plannedIssuedAtEpochSecond > PROBE_LIFETIME_SECONDS) { + throw new QuarantinedStateException("Readiness probe entry identity is malformed"); + } + compactTokenSha256.ifPresent(value -> requireDigest(value, "compact probe hash")); + if (compactTokenSha256.isPresent() != signingAttemptedAtEpochSecond.isPresent()) { + throw new QuarantinedStateException("Readiness signing-attempt evidence is partial"); + } + signingAttemptedAtEpochSecond.ifPresent( + attemptedAt -> { + if (attemptedAt < plannedIssuedAtEpochSecond || attemptedAt >= expiresAtEpochSecond) { + throw new QuarantinedStateException( + "Readiness signing-attempt time is outside its plan"); + } + }); + if ((state == ProbeState.ABORTED + || state == ProbeState.EXPIRED + || state == ProbeState.CLEANED) + != terminalOutcome.isPresent() + || (state == ProbeState.ABORTED && terminalOutcome.filter("ABORTED"::equals).isEmpty()) + || (state == ProbeState.EXPIRED && terminalOutcome.filter("EXPIRED"::equals).isEmpty()) + || (state == ProbeState.CLEANED + && terminalOutcome + .filter(value -> value.equals("ABORTED") || value.equals("EXPIRED")) + .isEmpty())) { + throw new QuarantinedStateException("Readiness terminal outcome does not match its state"); + } + if ((state == ProbeState.ISSUED || state == ProbeState.VERIFIED) + && compactTokenSha256.isEmpty()) { + throw new QuarantinedStateException("Issued readiness probe has no exact token hash"); + } + if ((state == ProbeState.VERIFIED && verificationReceipt.isEmpty()) + || ((state == ProbeState.PLANNED || state == ProbeState.ISSUED) + && verificationReceipt.isPresent())) { + throw new QuarantinedStateException("Readiness state and verification receipt disagree"); + } + verificationReceipt.ifPresent( + receipt -> { + if ((receipt.receiptVersion() == 1 && !receipt.verifiedKid().equals(targetKid)) + || (receipt.receiptVersion() == 2 + && receipt.verifiedKid() != null + && !receipt.verifiedKid().equals(targetKid)) + || receipt.resultEntryVersion() > entryVersion + || receipt.sourceEntryVersion() + 1L != receipt.resultEntryVersion() + || (state == ProbeState.VERIFIED && receipt.resultEntryVersion() != entryVersion)) { + throw new QuarantinedStateException( + "Readiness verification receipt differs from its immutable entry"); + } + }); + if (verificationReceipt.isPresent() + && verificationReceipt.orElseThrow().resultEntryVersion() > entryVersion) { + throw new QuarantinedStateException("Terminal readiness receipt version is invalid"); + } + if (state == ProbeState.CLEANED && terminalOutcome.isEmpty()) { + throw new QuarantinedStateException("Cleaned readiness probe lost its terminal evidence"); + } + } + + private ProbeEntry withPlanDigest(String value) { + return new ProbeEntry( + rotationOperationId, + value, + validatorId, + tokenProfile, + audience, + probeKind, + jti, + targetGeneration, + targetKid, + expectedActive, + registryVersion, + entryVersion, + plannedIssuedAtEpochSecond, + expiresAtEpochSecond, + state, + terminalOutcome, + signingAttemptedAtEpochSecond, + compactTokenSha256, + verificationReceipt); + } + } + + /** Exact authenticated transport and cryptographic verification evidence; contains no token. */ + public record VerifiedProbeObservation( + String compactTokenSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256, + long observedAtEpochSecond) { + public VerifiedProbeObservation { + requireDigest(compactTokenSha256, "verified compact token hash"); + requireKid(verifiedKid); + if (validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorConfigRevision == null + || !validatorConfigRevision.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness") + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Readiness verification observation is malformed"); + } + requireDigest(validatorBindingDigest, "validator trust binding digest"); + requireDigest(validatorPeerSpkiSha256, "validator peer SPKI digest"); + } + } + + /** Immutable digest and identity fields read back from the readiness entry row. */ + public record VerificationReceipt( + int receiptVersion, + long sourceEntryVersion, + long resultEntryVersion, + long observedAtEpochSecond, + String receiptSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256, + int podReceiptCount, + String podReceiptClosureSha256) { + public VerificationReceipt( + int receiptVersion, + long sourceEntryVersion, + long resultEntryVersion, + long observedAtEpochSecond, + String receiptSha256, + String verifiedKid, + String validatorInstanceId, + String validatorBindingDigest, + String validatorConfigRevision, + String validatorPeerUri, + String validatorPeerSpkiSha256) { + this( + receiptVersion, + sourceEntryVersion, + resultEntryVersion, + observedAtEpochSecond, + receiptSha256, + verifiedKid, + validatorInstanceId, + validatorBindingDigest, + validatorConfigRevision, + validatorPeerUri, + validatorPeerSpkiSha256, + 0, + null); + } + + public VerificationReceipt { + if ((receiptVersion != 1 && receiptVersion != 2) + || sourceEntryVersion <= 0L + || resultEntryVersion != sourceEntryVersion + 1L + || observedAtEpochSecond <= 0L) { + throw new QuarantinedStateException("Readiness verification receipt version is malformed"); + } + requireDigest(receiptSha256, "readiness verification receipt digest"); + if (receiptVersion == 1) { + requireKid(verifiedKid); + if (podReceiptCount != 0 || podReceiptClosureSha256 != null) { + throw new QuarantinedStateException("Legacy receipt cannot carry per-Pod closure fields"); + } + } else { + requireKid(verifiedKid); + if (podReceiptCount <= 0 || podReceiptCount > MAX_POD_RECEIPTS_PER_OPERATION) { + throw new QuarantinedStateException("Per-Pod receipt closure count is malformed"); + } + requireDigest(podReceiptClosureSha256, "per-Pod receipt closure digest"); + if (!receiptSha256.equals(podReceiptClosureSha256)) { + throw new QuarantinedStateException("Per-Pod closure and verification digests differ"); + } + } + if (validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorConfigRevision == null + || !validatorConfigRevision.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "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])?")) { + throw new QuarantinedStateException("Readiness verification receipt identity is malformed"); + } + requireDigest(validatorBindingDigest, "validator trust binding digest"); + requireDigest(validatorPeerSpkiSha256, "validator peer SPKI digest"); + } + } + + public record ReadinessProbePlan( + UUID operationId, + Binding binding, + TrustFence trustFence, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + String targetGeneration, + String targetKid, + String targetPublicKeyFingerprint, + SignerFence expectedFence, + String publicationIntentDigest, + String publicationReceiptDigest, + String mountedObservationDigest, + String applicabilityMatrixJson, + String applicabilityMatrixDigest, + boolean validatorInventoryComplete, + int maximumCacheAgeSeconds, + long plannedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + int planVersion, + String planDigest, + List entries, + Optional inventorySnapshotDigest) { + public ReadinessProbePlan( + UUID operationId, + Binding binding, + TrustFence trustFence, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long desiredStateVersion, + String targetGeneration, + String targetKid, + String targetPublicKeyFingerprint, + SignerFence expectedFence, + String publicationIntentDigest, + String publicationReceiptDigest, + String mountedObservationDigest, + String applicabilityMatrixJson, + String applicabilityMatrixDigest, + boolean validatorInventoryComplete, + int maximumCacheAgeSeconds, + long plannedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + int planVersion, + String planDigest, + List entries) { + this( + operationId, + binding, + trustFence, + operationDigest, + generationRequestDigest, + generationReceiptDigest, + desiredStateVersion, + targetGeneration, + targetKid, + targetPublicKeyFingerprint, + expectedFence, + publicationIntentDigest, + publicationReceiptDigest, + mountedObservationDigest, + applicabilityMatrixJson, + applicabilityMatrixDigest, + validatorInventoryComplete, + maximumCacheAgeSeconds, + plannedAtEpochSecond, + notBeforeEpochSecond, + expiresAtEpochSecond, + planVersion, + planDigest, + entries, + Optional.empty()); + } + + public ReadinessProbePlan { + requireOperationId(operationId); + Objects.requireNonNull(binding); + Objects.requireNonNull(trustFence); + Objects.requireNonNull(expectedFence); + requireDigest(operationDigest, "operation digest"); + requireDigest(generationRequestDigest, "generation request digest"); + requireDigest(generationReceiptDigest, "generation receipt digest"); + requireGeneration(targetGeneration); + requireKid(targetKid); + requireDigest(targetPublicKeyFingerprint, "target public key fingerprint"); + requireDigest(publicationIntentDigest, "publication intent digest"); + requireDigest(publicationReceiptDigest, "publication receipt digest"); + requireDigest(mountedObservationDigest, "mounted observation digest"); + Objects.requireNonNull(applicabilityMatrixJson); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + requireDigest(planDigest, "plan digest"); + Objects.requireNonNull(inventorySnapshotDigest); + inventorySnapshotDigest.ifPresent( + value -> requireDigest(value, "validator inventory snapshot digest")); + entries = List.copyOf(entries); + if (desiredStateVersion <= 1L + || maximumCacheAgeSeconds != MAX_VALIDATOR_CACHE_AGE_SECONDS + || plannedAtEpochSecond <= 0L + || notBeforeEpochSecond < plannedAtEpochSecond + maximumCacheAgeSeconds + || expiresAtEpochSecond <= notBeforeEpochSecond + || expiresAtEpochSecond - notBeforeEpochSecond > PROBE_LIFETIME_SECONDS + || (planVersion != 1 && planVersion != INVENTORY_PLAN_VERSION) + || (planVersion == INVENTORY_PLAN_VERSION && inventorySnapshotDigest.isEmpty()) + || entries.isEmpty() + || entries.size() > MAX_ENTRIES_PER_OPERATION) { + throw new QuarantinedStateException("Readiness probe plan is malformed"); + } + } + + private static ReadinessProbePlan fromCurrent( + CurrentEvidence current, + String matrixJson, + String matrixDigest, + boolean inventoryComplete, + int maxCacheAge, + long plannedAt, + long notBefore, + long expiresAt, + String planDigest, + List entries, + Optional inventorySnapshotDigest, + int planVersion) { + GenerationRequest request = current.request(); + GenerationResult result = current.result(); + var publication = current.publication(); + return new ReadinessProbePlan( + request.operationId(), + request.binding(), + request.trustFence(), + request.operationDigest(), + result.generationRequestDigest(), + result.receiptDigest(), + result.desiredStateVersion(), + result.targetGeneration(), + result.targetKid(), + result.publicKeyFingerprint(), + new SignerFence(request.expectedActive(), request.expectedPublishedActive()), + publication.intent().intentDigest(), + publication.receipt().orElseThrow().receiptDigest(), + publication.mountedCorrespondence().orElseThrow().observationDigest(), + matrixJson, + matrixDigest, + inventoryComplete, + maxCacheAge, + plannedAt, + notBefore, + expiresAt, + planVersion, + planDigest, + entries, + inventorySnapshotDigest); + } + } + + /** + * Owner-created, non-secret readiness evidence accepted by the Account promotion owner. Its + * constructor is private: callers cannot turn an applicability matrix or receipt DTO into proof. + */ + public static final class ReadinessPromotionProof { + private final ReadinessProbePlan plan; + private final GenerationResult generationResult; + private final AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication; + private final String inventoryEvidenceReference; + private final String inventoryEvidenceDigest; + private final List verifiedProbes; + private final byte[] readinessEvidencePreimage; + private final String readinessEvidenceDigest; + + private ReadinessPromotionProof( + ReadinessProbePlan plan, + GenerationResult generationResult, + AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication, + String inventoryEvidenceReference, + String inventoryEvidenceDigest) { + this.plan = Objects.requireNonNull(plan); + this.generationResult = Objects.requireNonNull(generationResult); + this.publication = Objects.requireNonNull(publication); + if (!plan.validatorInventoryComplete()) { + throw new QuarantinedStateException( + "Partial readiness inventory cannot create promotion proof"); + } + if (inventoryEvidenceReference == null + || !inventoryEvidenceReference.matches("[A-Za-z0-9][A-Za-z0-9._:/-]{0,511}")) { + throw new QuarantinedStateException("Protected readiness inventory reference is malformed"); + } + requireDigest(inventoryEvidenceDigest, "protected readiness inventory digest"); + this.inventoryEvidenceReference = inventoryEvidenceReference; + this.inventoryEvidenceDigest = inventoryEvidenceDigest; + List verifiedProbes = + plan.entries().stream().map(VerifiedProbeEvidence::from).toList(); + if (verifiedProbes.isEmpty() + || verifiedProbes.size() > MAX_ENTRIES_PER_OPERATION + || plan.planVersion() != INVENTORY_PLAN_VERSION + || verifiedProbes.stream().anyMatch(probe -> probe.receipt().receiptVersion() != 2) + || !plan.operationId().equals(generationResult.operationId()) + || !plan.operationDigest().equals(generationResult.operationDigest()) + || !plan.generationRequestDigest().equals(generationResult.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(generationResult.receiptDigest()) + || plan.desiredStateVersion() != generationResult.desiredStateVersion() + || !plan.targetGeneration().equals(generationResult.targetGeneration()) + || !plan.targetKid().equals(generationResult.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(generationResult.publicKeyFingerprint()) + || !plan.planDigest().equals(planDigest(plan))) { + throw new QuarantinedStateException( + "Readiness proof differs from exact generation and verified probe evidence"); + } + this.verifiedProbes = List.copyOf(verifiedProbes); + this.readinessEvidencePreimage = + readinessPromotionPreimageBytes( + readinessPromotionPreimage( + plan, + generationResult, + publication, + inventoryEvidenceReference, + inventoryEvidenceDigest, + this.verifiedProbes)); + this.readinessEvidenceDigest = readinessPromotionDigest(this.readinessEvidencePreimage); + } + + public ReadinessProbePlan plan() { + return plan; + } + + public GenerationResult generationResult() { + return generationResult; + } + + public AccountJwtJwksPublicationRepository.PromotionPublicationEvidence publication() { + return publication; + } + + public String inventoryEvidenceReference() { + return inventoryEvidenceReference; + } + + public String inventoryEvidenceDigest() { + return inventoryEvidenceDigest; + } + + public List verifiedProbes() { + return verifiedProbes; + } + + /** Digest computed by Account over all canonical proof fields except this digest itself. */ + public String readinessEvidenceDigest() { + return readinessEvidenceDigest; + } + + /** Exact non-secret RFC 8785 preimage bytes hashed for {@link #readinessEvidenceDigest()}. */ + public byte[] readinessEvidencePreimage() { + return readinessEvidencePreimage.clone(); + } + } + + /** Ordered immutable row and authenticated receipt identity for one VERIFIED registry entry. */ + public record VerifiedProbeEvidence( + UUID rotationOperationId, + String planDigest, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + UUID jti, + String targetGeneration, + String targetKid, + Optional expectedActive, + int registryVersion, + long entryVersion, + long plannedIssuedAtEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256, + VerificationReceipt receipt) { + public VerifiedProbeEvidence { + Objects.requireNonNull(rotationOperationId); + requireDigest(planDigest, "verified probe plan digest"); + requireValidatorId(validatorId); + requireProfile(tokenProfile); + requireAudience(audience); + Objects.requireNonNull(probeKind); + Objects.requireNonNull(jti); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + requireDigest(compactTokenSha256, "verified probe token digest"); + Objects.requireNonNull(receipt); + if (registryVersion != 1 + || entryVersion <= 0L + || plannedIssuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= plannedIssuedAtEpochSecond + || (receipt.receiptVersion() == 1 && !targetKid.equals(receipt.verifiedKid())) + || (receipt.receiptVersion() == 2 + && receipt.verifiedKid() != null + && !targetKid.equals(receipt.verifiedKid())) + || receipt.resultEntryVersion() != entryVersion) { + throw new QuarantinedStateException( + "Verified probe evidence does not match its immutable receipt"); + } + } + + private static VerifiedProbeEvidence from(ProbeEntry entry) { + if (entry.state() != ProbeState.VERIFIED) { + throw new QuarantinedStateException( + "Every promotion readiness entry must be owner-recorded VERIFIED"); + } + return new VerifiedProbeEvidence( + entry.rotationOperationId(), + entry.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + entry.jti(), + entry.targetGeneration(), + entry.targetKid(), + entry.expectedActive(), + entry.registryVersion(), + entry.entryVersion(), + entry.plannedIssuedAtEpochSecond(), + entry.expiresAtEpochSecond(), + entry.compactTokenSha256().orElseThrow(), + entry.verificationReceipt().orElseThrow()); + } + } + + /** Immutable winner of the only permitted transient delivery for a readiness operation. */ + public record DeliveryClaim( + UUID rotationOperationId, + String planDigest, + String expectedClusterUid, + String expectedNamespaceUid, + String materializerTrustBindingDigest, + String materializerTrustConfigRevision, + String targetGeneration, + String targetKid, + Optional expectedActive, + String readinessBindingDigest, + String readinessConfigRevision, + long readinessBindingValidUntilEpochSecond, + String validatorId, + String validatorInstanceId, + String validatorPeerUri, + String validatorPeerSpkiSha256, + long claimedAtEpochSecond, + long expiresAtEpochSecond, + String claimDigest) { + public DeliveryClaim { + requireOperationId(rotationOperationId); + requireDigest(planDigest, "delivery plan digest"); + requireUuid(expectedClusterUid, "delivery cluster UID"); + requireUuid(expectedNamespaceUid, "delivery namespace UID"); + requireDigest(materializerTrustBindingDigest, "materializer trust digest"); + requireRevision(materializerTrustConfigRevision, "materializer trust revision"); + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive); + expectedActive.ifPresent( + active -> { + requireGeneration(active.generation()); + requireKid(active.kid()); + if (Long.parseLong(targetGeneration) <= Long.parseLong(active.generation()) + || targetKid.equals(active.kid())) { + throw new QuarantinedStateException("Delivery active fence is not older than target"); + } + }); + requireDigest(readinessBindingDigest, "readiness trust digest"); + requireRevision(readinessConfigRevision, "readiness trust revision"); + if (readinessBindingValidUntilEpochSecond <= claimedAtEpochSecond) { + throw new QuarantinedStateException("Readiness binding expires before delivery claim"); + } + requireValidatorId(validatorId); + if (!VALIDATOR_ID.equals(validatorId) + || validatorInstanceId == null + || !validatorInstanceId.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}") + || validatorPeerUri == null + || !validatorPeerUri.matches( + "spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness")) { + throw new QuarantinedStateException("Readiness delivery identity is malformed"); + } + requireDigest(validatorPeerSpkiSha256, "readiness peer SPKI digest"); + if (claimedAtEpochSecond <= 0L || expiresAtEpochSecond <= claimedAtEpochSecond) { + throw new QuarantinedStateException("Readiness delivery claim window is malformed"); + } + requireDigest(claimDigest, "readiness delivery claim digest"); + } + + private static DeliveryClaim create( + ReadinessProbePlan plan, + TrustFence trust, + net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.Binding + readinessBinding, + PeerIdentity peer, + long claimedAt) { + DeliveryClaim unsigned = + new DeliveryClaim( + plan.operationId(), + plan.planDigest(), + trust.expectedClusterIncarnationUid(), + trust.expectedNamespaceUid(), + trust.bindingDigest(), + trust.configRevision(), + plan.targetGeneration(), + plan.targetKid(), + plan.expectedFence().durableActive(), + readinessBinding.bindingDigest(), + readinessBinding.configRevision(), + readinessBinding.validUntilEpochSecond(), + readinessBinding.validatorId(), + readinessBinding.validatorInstanceId(), + peer.uri(), + peer.spkiSha256(), + claimedAt, + plan.expiresAtEpochSecond(), + "0".repeat(64)); + return new DeliveryClaim( + unsigned.rotationOperationId(), + unsigned.planDigest(), + unsigned.expectedClusterUid(), + unsigned.expectedNamespaceUid(), + unsigned.materializerTrustBindingDigest(), + unsigned.materializerTrustConfigRevision(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.expectedActive(), + unsigned.readinessBindingDigest(), + unsigned.readinessConfigRevision(), + unsigned.readinessBindingValidUntilEpochSecond(), + unsigned.validatorId(), + unsigned.validatorInstanceId(), + unsigned.validatorPeerUri(), + unsigned.validatorPeerSpkiSha256(), + unsigned.claimedAtEpochSecond(), + unsigned.expiresAtEpochSecond(), + deliveryClaimDigest(unsigned)); + } + } + + private static String requireDigest(String value, String label) { + if (value == null || !SHA256.matcher(value).matches()) { + throw new QuarantinedStateException(label + " is malformed"); + } + return value; + } + + private static String requireUuid(String value, String label) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) + || parsed.version() != 4 + || parsed.variant() != 2 + || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(); + } + return value; + } catch (RuntimeException invalid) { + throw new QuarantinedStateException(label + " is malformed"); + } + } + + private static String requireRevision(String value, String label) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new QuarantinedStateException(label + " is malformed"); + } + return value; + } + + private static String requireValidatorId(String value) { + if (value == null || !value.matches("[a-z0-9][a-z0-9-]{0,62}")) { + throw new QuarantinedStateException("Readiness validator ID is malformed"); + } + return value; + } + + private static String requireProfile(String value) { + if (value == null || !value.matches("[a-z0-9][a-z0-9-]{0,127}")) { + throw new QuarantinedStateException("Readiness token profile is malformed"); + } + return value; + } + + private static String requireAudience(String value) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new QuarantinedStateException("Readiness audience is malformed"); + } + return value; + } + + private static String requireGeneration(String value) { + if (value == null || !value.matches("[1-9][0-9]{0,63}")) { + throw new QuarantinedStateException("Readiness signer generation is malformed"); + } + return value; + } + + private static String requireKid(String value) { + if (value == null || !value.matches("[A-Za-z0-9_-]{1,64}")) { + throw new QuarantinedStateException("Readiness signer kid is malformed"); + } + return value; + } + + public static final class MissingPlanException extends IllegalStateException { + public MissingPlanException(String message) { + super(message); + } + } + + public static final class DeliveryAlreadyClaimedException extends IllegalStateException { + public DeliveryAlreadyClaimedException() { + super("Readiness probe delivery was already claimed"); + } + } + + public static final class DeliveryClaimRejectedException extends SecurityException { + public DeliveryClaimRejectedException() { + super("Authenticated readiness delivery caller is not bound to the current plan"); + } + } + + public static final class MissingPublicationEvidenceException extends IllegalStateException { + public MissingPublicationEvidenceException() { + super("Current JWKS publication evidence is incomplete"); + } + } + + public static final class InventoryPlanConflictException extends IllegalStateException { + public InventoryPlanConflictException() { + super("Account validator inventory snapshot does not match the immutable readiness plan"); + } + } + + public static final class StaleOperationException extends IllegalStateException { + public StaleOperationException(String message) { + super(message); + } + } + + public static final class CacheAgeNotElapsedException extends IllegalStateException { + public CacheAgeNotElapsedException() { + super("Validator maximum cache age has not elapsed"); + } + } + + public static final class ProbeExpiredException extends IllegalStateException { + public ProbeExpiredException() { + super("Readiness probe is expired"); + } + } + + public static final class AmbiguousDeliveryException extends IllegalStateException { + public AmbiguousDeliveryException(String message) { + super(message); + } + } + + public static final class VersionConflictException extends IllegalStateException { + public VersionConflictException(String message) { + super(message); + } + } + + public static final class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static final class QuarantinedStateException extends IllegalStateException { + public QuarantinedStateException(String message) { + super(message); + } + } + + public static final class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java new file mode 100644 index 0000000000..f5f3e9043b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -0,0 +1,4561 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +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.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Account-owned persistence for the interim mounted JWT signer. + * + *

Account chooses and persists the operation, generation, and {@code kid}. The materializer can + * only observe the fixed Secret, then perform one pending-slot generation/CAS or an exact + * PREPARED-only slot promotion and return public-only results. Account remains the sole durable + * commit authority; public prepublication, cache convergence, validator probes, and correspondence + * evidence are separately owned prerequisites and are never inferred by this repository. + */ +@Repository +public class AccountJwtSignerDesiredStateRepository { + public static final String PRIVATE_SECRET_NAME = "jwt-signing-keys"; + public static final String PUBLIC_JWKS_CONFIG_MAP_NAME = "jwt-jwks"; + public static final String REQUEST_DIGEST_VERSION = "account-jwt-signer-generation-operation/v1"; + public static final String OBSERVATION_DIGEST_VERSION = + "account-jwt-signer-secret-observation/v1"; + public static final String GENERATION_REQUEST_DIGEST_VERSION = + "account-jwt-signer-generation-request/v1"; + public static final String RECEIPT_DIGEST_VERSION = "account-jwt-signer-generation-receipt/v1"; + private static final String PROMOTION_DIGEST_VERSION = + "account-jwt-signer-promotion-operation/v1"; + + private static final String STATE_TABLE = "account_jwt_signer_desired_states"; + private static final String OPERATION_TABLE = "account_jwt_signer_generation_operations"; + private static final String OBSERVATION_TABLE = "account_jwt_signer_secret_observations"; + private static final String RESULT_TABLE = "account_jwt_signer_generation_results"; + private static final String GENERATION_ABORT_TABLE = + "account_jwt_signer_generation_abort_receipts"; + private static final String PROMOTION_TABLE = "account_jwt_signer_promotion_operations"; + private static final String MODE = "INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK"; + private static final String ALGORITHM = "RS256"; + private static final String ACTION = "MATERIALIZE_PENDING"; + private static final String PENDING_SLOT = "pending"; + private static final byte[] PENDING_SLOT_CANONICAL_BYTES = + "[\"pending\"]".getBytes(StandardCharsets.UTF_8); + private static final byte[] PROMOTION_SLOTS_CANONICAL_BYTES = + "[\"current\",\"pending\",\"previous\"]".getBytes(StandardCharsets.UTF_8); + private static final Pattern ENVIRONMENT_ID = + Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"); + private static final Pattern CLUSTER_ID = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern SHA256_HEX = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Set PUBLIC_JWK_FIELDS = + Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final DSLContext dsl; + + @Autowired + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates its trusted injected DSLContext; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtSignerDesiredStateRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** + * Enrolls the fixed Account environment only after both protected trust bindings and a live + * fixed-ConfigMap observation have been reconciled by the enrollment owner. + */ + @Transactional(propagation = Propagation.MANDATORY) + public DesiredState initialize(Binding binding, EnrollmentIdentity enrollmentIdentity) { + requireWritableAccountTransaction(); + Objects.requireNonNull(binding, "JWT signer binding is required"); + Objects.requireNonNull(enrollmentIdentity, "Pinned JWT signer enrollment is required"); + int inserted = + dsl.execute( + "INSERT INTO " + + STATE_TABLE + + " (environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "private_secret_name, public_jwks_config_map_name, record_version, " + + "durable_active_generation, durable_active_kid, published_active_generation, " + + "published_active_kid, generation_operation_id, prepared_operation_id, " + + "enrollment_cluster_incarnation_uid, enrollment_namespace_uid, " + + "enrollment_materializer_binding_digest, enrollment_materializer_config_revision, " + + "enrollment_api_binding_digest, enrollment_api_config_revision, " + + "enrollment_public_config_map_uid, enrollment_public_config_map_resource_version, " + + "enrollment_public_config_map_snapshot_digest) " + + "VALUES (?, ?, ?, ?, 'jwt-signing-keys', 'jwt-jwks', 1, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (environment_id) DO NOTHING", + binding.environmentId(), + binding.clusterId(), + binding.namespace(), + binding.mode().value(), + UUID.fromString(enrollmentIdentity.expectedClusterIncarnationUid()), + UUID.fromString(enrollmentIdentity.expectedNamespaceUid()), + enrollmentIdentity.materializerTrustBindingDigest(), + enrollmentIdentity.materializerTrustConfigRevision(), + enrollmentIdentity.apiBindingDigest(), + enrollmentIdentity.apiConfigRevision(), + UUID.fromString(enrollmentIdentity.publicConfigMapUid()), + enrollmentIdentity.publicConfigMapResourceVersion(), + enrollmentIdentity.publicConfigMapSnapshotDigest()); + if (inserted < 0 || inserted > 1) { + throw new StorageUnavailableException("Account JWT signer initialization was ambiguous"); + } + Record row = selectState(binding.environmentId(), true); + if (row == null) { + throw new QuarantinedStateException("Initialized Account JWT signer state did not read back"); + } + DesiredState state = decodeState(row); + requireBinding(state, binding); + if (state.enrollmentIdentity().isEmpty() + || !state.enrollmentIdentity().orElseThrow().sameStablePins(enrollmentIdentity)) { + throw new BindingMismatchException( + "Account JWT signer enrollment trust or precreated resource identity changed"); + } + if (inserted == 1 && !state.enrollmentIdentity().orElseThrow().equals(enrollmentIdentity)) { + throw new QuarantinedStateException( + "Initial Account JWT signer enrollment receipt did not read back exactly"); + } + if (inserted == 1 + && (state.recordVersion() != 1 + || state.durableActive().isPresent() + || state.publishedActive().isPresent() + || state.generationOperationId().isPresent() + || state.preparedOperationId().isPresent())) { + throw new QuarantinedStateException( + "New Account JWT signer state contains inferred or unexpected authority"); + } + return state; + } + + /** + * Returns a pinned enrollment row even while PREPARED so startup reconciliation can inspect it. + * Ordinary desired-state reads continue to quarantine PREPARED signer state. + */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public Optional readEnrollmentState(Binding expectedBinding) { + requireAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Record row = selectState(expectedBinding.environmentId(), false); + if (row == null) { + return Optional.empty(); + } + DesiredState state = decodeState(row); + requireBinding(state, expectedBinding); + if (state.enrollmentIdentity().isEmpty()) { + throw new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity"); + } + return Optional.of(state); + } + + /** Reads an explicitly enrolled state; a missing row never initializes desired state. */ + @Transactional(propagation = Propagation.MANDATORY, readOnly = true) + public DesiredState read(Binding expectedBinding) { + requireAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Record row = selectState(expectedBinding.environmentId(), false); + if (row == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(row); + requireBinding(state, expectedBinding); + if (state.enrollmentIdentity().isEmpty()) { + throw new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity"); + } + verifyPreparedIsUnavailable(state); + if (state.generationOperationId().isPresent()) { + StoredGenerationOperation operation = + selectGenerationOperation(state.generationOperationId().orElseThrow(), false); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + } + return state; + } + + /** + * Account's internal operation entrypoint. It receives no caller-selected operation, key + * identity, resource name, fingerprint, or material. Account creates one immutable operation if + * absent, or returns the same operation under the same protected trust snapshot. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest ensureCurrentGenerationRequest( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + + if (state.generationOperationId().isEmpty()) { + if (state.durableActive().isPresent()) { + throw new MissingGenerationOperationException( + "Account has no durable rotation request for its committed signer"); + } + return createGenerationRequest(state, trust); + } + + StoredGenerationOperation operation = + selectGenerationOperation(state.generationOperationId().orElseThrow(), true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return readGenerationRequest(operation, state, true); + } + + /** + * Durably releases only the exact current UNPREPARED generation after its owner-recorded + * generation result failed readiness. The immutable abort receipt preserves the operation and + * both active fences; it grants no materialization, promotion, or replacement authority. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationAbortReceipt abortUnpreparedGeneration( + Binding expectedBinding, TrustFence trust, GenerationResult expectedResult) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(expectedResult, "Exact Account generation result is required"); + UUID operationId = expectedResult.operationId(); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + GenerationResult persistedResult = selectGenerationResult(operationId, true); + if (operation == null || persistedResult == null) { + throw new StaleGenerationOperationException( + "Abort does not target an exact owner-recorded generation result"); + } + requireCurrentTrust(operation, trust); + if (!expectedResult.equals(persistedResult) + || !expectedResult.binding().equals(expectedBinding) + || !expectedResult.trustFence().equals(trust) + || !expectedResult.operationDigest().equals(operation.operationDigest()) + || !expectedResult.generationRequestDigest().matches("[0-9a-f]{64}") + || !generationOperationDigest(operation).equals(operation.operationDigest())) { + throw new IdempotencyConflictException( + "Generation abort does not match the immutable Account operation and result"); + } + + GenerationAbortReceipt existing = selectGenerationAbortReceipt(operationId, true); + if (existing != null) { + if (!existing.matches(operation, persistedResult, trust)) { + throw new IdempotencyConflictException( + "Generation abort retry changed its immutable operation or result"); + } + if (!state.generationOperationId().equals(Optional.of(operationId))) { + if (state.recordVersion() < existing.resultingStateVersion()) { + throw new QuarantinedStateException( + "Persisted generation abort receipt is ahead of desired state"); + } + return existing; + } + if (state.preparedOperationId().isPresent() + || state.recordVersion() != existing.expectedStateVersion()) { + throw new StaleGenerationOperationException( + "Persisted abort receipt cannot release a changed generation state"); + } + } + if (!state.generationOperationId().equals(Optional.of(operationId)) + || state.preparedOperationId().isPresent()) { + throw new StaleGenerationOperationException( + "Abort does not target Account's exact current UNPREPARED generation"); + } + verifyOperationMatchesState(operation, state); + verifyGenerationResultMatchesOperation(persistedResult, operation, state); + if (state.recordVersion() == Long.MAX_VALUE) { + throw new VersionConflictException("Account JWT signer state version is exhausted"); + } + if (Boolean.TRUE.equals( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM " + + PROMOTION_TABLE + + " WHERE generation_operation_id = ?)", + operationId), + "Account JWT promotion-existence readback is required") + .get(0, Boolean.class))) { + throw new StaleGenerationOperationException( + "An operation with promotion evidence cannot use generation abort"); + } + + GenerationAbortReceipt candidate = + existing == null + ? GenerationAbortReceipt.from(state, operation, persistedResult, trust) + : existing; + if (existing == null) { + insertGenerationAbortReceipt(candidate); + } + int changed = + dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, generation_operation_id = NULL, " + + "updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? AND cluster_id = ? " + + "AND kubernetes_namespace = ? AND custody_mode = ? AND record_version = ? " + + "AND generation_operation_id = ? AND prepared_operation_id IS NULL " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ?", + expectedBinding.environmentId(), + expectedBinding.clusterId(), + expectedBinding.namespace(), + expectedBinding.mode().value(), + candidate.expectedStateVersion(), + operationId, + generationValue(candidate.durableActive()), + kidValue(candidate.durableActive()), + generationValue(candidate.publishedActive()), + kidValue(candidate.publishedActive())); + if (changed != 1) { + throw new VersionConflictException("Account generation abort state CAS did not apply"); + } + GenerationAbortReceipt readback = selectGenerationAbortReceipt(operationId, true); + Record readbackStateRow = selectState(expectedBinding.environmentId(), true); + if (readback == null || readbackStateRow == null || !readback.equals(candidate)) { + throw new QuarantinedStateException("Account generation abort receipt did not read back"); + } + DesiredState readbackState = decodeState(readbackStateRow); + if (readbackState.recordVersion() != candidate.resultingStateVersion() + || readbackState.generationOperationId().isPresent() + || readbackState.preparedOperationId().isPresent() + || !readbackState.durableActive().equals(candidate.durableActive()) + || !readbackState.publishedActive().equals(candidate.publishedActive())) { + throw new QuarantinedStateException( + "Account generation abort changed a protected active fence or lifecycle pointer"); + } + return readback; + } + + /** + * Returns the same current Account-selected request and exact phase for an authenticated peer. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest readCurrentGenerationRequest(Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + UUID operationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no owner-selected JWT generation operation")); + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return readGenerationRequest(operation, state, true); + } + + /** + * Reads the exact immutable result for Account's current generation operation while locking the + * desired-state, operation, and result rows in their canonical order. A historical result is + * never returned after the Account operation or protected trust fence has moved. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationResult readCurrentGenerationResult(Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + requireEnrollmentTrust(state, trust); + UUID operationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no owner-selected JWT generation operation")); + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + GenerationResult result = selectGenerationResult(operationId, true); + if (result == null) { + throw new MissingGenerationObservationException( + "Account JWT generation result is not recorded for the current operation"); + } + verifyGenerationResultMatchesOperation(result, operation, state); + return result; + } + + /** + * Recovery-only read for the exact generation that owns the current PREPARED operation. It is + * intentionally distinct from ordinary serving/generation reads, which continue to fail closed + * while a promotion is unresolved. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedGenerationEvidence readPreparedGenerationForRecovery( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + UUID promotionId = + state.preparedOperationId().orElseThrow(() -> new NoPreparedPromotionException()); + if (state.generationOperationId().isPresent()) { + throw new QuarantinedStateException( + "Account PREPARED signer state also contains a generation pointer"); + } + StoredPromotion promotion = selectPromotion(promotionId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + StoredGenerationOperation operation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (operation == null || result == null) { + throw new QuarantinedStateException( + "Prepared JWT signer operation has incomplete generation evidence"); + } + verifyPreparedGenerationMatches(promotion, operation, result); + return new PreparedGenerationEvidence(state, promotion.publicEvidence(), result); + } + + /** + * Atomically records that the authenticated materializer may receive the immutable private-slot + * promotion operation. This marker is deliberately sticky: after it is committed, a lost RPC + * response is an uncertain external mutation and the operation must remain PREPARED for forward + * reconciliation. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedGenerationEvidence readAndMarkPreparedPromotionDispatched( + Binding expectedBinding, TrustFence trust) { + requireWritableAccountTransaction(); + PreparedGenerationEvidence evidence = readPreparedGenerationForRecovery(expectedBinding, trust); + UUID operationId = evidence.promotion().operationId(); + StoredPromotion promotion = selectPromotion(operationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + int expectedReadinessProbeCount = 0; + if (!promotion.privatePromotionDispatched()) { + expectedReadinessProbeCount = + requireFreshReadinessBeforeDispatch(promotion, evidence.generationResult()); + int changed = + dsl.execute( + "WITH readiness_clock AS MATERIALIZED (SELECT clock_timestamp() AS checked_at) " + + "UPDATE " + + PROMOTION_TABLE + + " AS promotion SET private_promotion_dispatched_at = readiness_clock.checked_at " + + "FROM readiness_clock WHERE promotion.operation_id = ? " + + "AND promotion.status = 'PREPARED' " + + "AND promotion.private_promotion_dispatched_at IS NULL " + + "AND promotion.private_promotion_receipt_digest IS NULL " + + "AND promotion.active_jwks_receipt_digest IS NULL " + + "AND promotion.readiness_plan_digest = ? " + + "AND promotion.readiness_evidence_digest = ? " + + "AND encode(sha256(promotion.readiness_evidence_preimage), 'hex') " + + "= promotion.readiness_evidence_digest " + + "AND EXISTS (SELECT 1 FROM account_jwt_readiness_probe_plans plan " + + "WHERE plan.rotation_operation_id = promotion.generation_operation_id " + + "AND plan.plan_digest = promotion.readiness_plan_digest " + + "AND plan.validator_inventory_complete = TRUE " + + "AND plan.not_before_epoch_seconds <= " + + "floor(extract(epoch FROM readiness_clock.checked_at))::BIGINT " + + "AND plan.expires_at_epoch_seconds > " + + "floor(extract(epoch FROM readiness_clock.checked_at))::BIGINT) " + + "AND (SELECT count(*) FROM account_jwt_readiness_probe_entries entry " + + "WHERE entry.rotation_operation_id = promotion.generation_operation_id " + + "AND entry.plan_digest = promotion.readiness_plan_digest) = ? " + + "AND (SELECT count(*) FROM account_jwt_readiness_probe_entries entry " + + "WHERE entry.rotation_operation_id = promotion.generation_operation_id " + + "AND entry.plan_digest = promotion.readiness_plan_digest " + + "AND entry.state = 'VERIFIED' " + + "AND entry.verification_receipt_sha256 IS NOT NULL " + + "AND entry.verified_at_epoch_seconds < entry.expires_at_epoch_seconds " + + "AND entry.expires_at_epoch_seconds > " + + "floor(extract(epoch FROM readiness_clock.checked_at))::BIGINT) = ?", + operationId, + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + expectedReadinessProbeCount, + expectedReadinessProbeCount); + if (changed != 1) { + throw new VersionConflictException( + "Account private promotion dispatch authorization CAS did not apply"); + } + promotion = selectPromotion(operationId, true); + } + if (promotion == null + || !promotion.privatePromotionDispatched() + || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException( + "Account private promotion dispatch authorization did not read back exactly"); + } + return new PreparedGenerationEvidence( + evidence.desiredState(), promotion.publicEvidence(), evidence.generationResult()); + } + + /** + * Records one authenticated materializer readback of the exact fixed-Secret slot transition. Only + * public key identities, resource UID/RV, and slot names cross this boundary; private bytes and + * hashes of private bytes are neither accepted nor persisted. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PrivatePromotionReceipt recordPrivatePromotionResult( + Binding expectedBinding, TrustFence trust, PrivatePromotionObservation observation) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(observation, "Exact private promotion observation is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + StoredPromotion promotion = selectPromotion(observation.promotionOperationId(), true); + if (promotion == null) { + throw new StaleGenerationOperationException( + "Private promotion result does not target an Account-owned operation"); + } + requireCurrentTrust(promotion, trust); + if (!promotion.requestDigest().equals(observation.promotionRequestDigest()) + || !promotion.generationOperationId().equals(observation.generationOperationId()) + || !promotion.generationOperationDigest().equals(observation.generationOperationDigest())) { + throw new IdempotencyConflictException( + "Private promotion result does not match the exact Account operation"); + } + if (!promotion.privatePromotionDispatched()) { + throw new PromotionPrerequisitesIncompleteException( + "Private promotion result has no prior durable Account dispatch authorization"); + } + StoredGenerationOperation operation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (operation == null || result == null) { + throw new QuarantinedStateException( + "Prepared JWT signer operation has incomplete generation evidence"); + } + verifyPreparedGenerationMatches(promotion, operation, result); + requirePrivatePromotionObservation(promotion, observation); + PrivatePromotionReceipt candidate = PrivatePromotionReceipt.from(promotion, observation); + + if ("COMMITTED".equals(promotion.status())) { + ActiveSigner target = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!promotion.binding().equals(expectedBinding) + || !promotion.requestDigest().equals(promotionRequestDigest(promotion)) + || state.preparedOperationId().isPresent() + || state.durableActive().filter(target::equals).isEmpty() + || state.publishedActive().filter(target::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() < promotion.expectedRecordVersion() + 2 + || promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null + || !candidate.receiptDigest().equals(promotion.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.privatePromotionObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Committed private promotion retry does not match current Account evidence"); + } + return candidate; + } + + if (!"PREPARED".equals(promotion.status()) + || !state.preparedOperationId().equals(Optional.of(observation.promotionOperationId())) + || state.generationOperationId().isPresent()) { + throw new StaleGenerationOperationException( + "Private promotion result does not target Account's current PREPARED operation"); + } + requirePromotionMatchesState(promotion, state); + if (promotion.privatePromotionReceiptDigest() != null) { + if (!candidate.receiptDigest().equals(promotion.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.privatePromotionObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Private promotion readback changed for the same Account operation"); + } + return candidate; + } + int updated = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET private_promotion_observed_resource_version = ?, " + + "private_promotion_receipt_digest = ? WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_dispatched_at IS NOT NULL " + + "AND private_promotion_receipt_digest IS NULL", + candidate.observedResourceVersion(), + candidate.receiptDigest(), + candidate.promotionOperationId()); + if (updated != 1) { + throw new VersionConflictException("Account private promotion receipt CAS did not apply"); + } + StoredPromotion readback = selectPromotion(candidate.promotionOperationId(), true); + if (readback == null + || !candidate.receiptDigest().equals(readback.privatePromotionReceiptDigest()) + || !candidate + .observedResourceVersion() + .equals(readback.privatePromotionObservedResourceVersion())) { + throw new QuarantinedStateException( + "Account private promotion receipt did not read back exactly"); + } + return candidate; + } + + /** + * Records Account's exact readback after its fixed public ConfigMap CAS changes only the + * generation marker from PREPUBLISHED to ACTIVE. The public receipt contains no private Secret + * bytes or digest of private material. + */ + @Transactional(propagation = Propagation.MANDATORY) + public ActiveJwksPromotionReceipt recordActiveJwksPromotionResult( + Binding expectedBinding, TrustFence trust, ActiveJwksPromotionObservation observation) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(observation, "Exact Account ConfigMap promotion readback is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + UUID promotionId = + state + .preparedOperationId() + .orElseThrow( + () -> + new PromotionPrerequisitesIncompleteException( + "Account has no PREPARED JWT signer promotion")); + StoredPromotion promotion = selectPromotion(promotionId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionReceiptDigest() == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account cannot publish ACTIVE before the exact private-slot readback"); + } + requireActiveJwksObservation(promotion, observation); + ActiveJwksPromotionReceipt candidate = ActiveJwksPromotionReceipt.from(promotion, observation); + if (promotion.activeJwksReceiptDigest() != null) { + if (!candidate.receiptDigest().equals(promotion.activeJwksReceiptDigest()) + || !candidate.publicDataDigest().equals(promotion.activeJwksPublicDataDigest()) + || !candidate + .observedResourceVersion() + .equals(promotion.activeJwksObservedResourceVersion())) { + throw new IdempotencyConflictException( + "Active Account JWT JWKS readback changed for the same promotion operation"); + } + return candidate; + } + int updated = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET active_jwks_observed_resource_version = ?, active_jwks_public_data_digest = ?, " + + "active_jwks_receipt_digest = ? WHERE operation_id = ? AND status = 'PREPARED' " + + "AND private_promotion_receipt_digest IS NOT NULL " + + "AND active_jwks_receipt_digest IS NULL", + candidate.observedResourceVersion(), + candidate.publicDataDigest(), + candidate.receiptDigest(), + candidate.promotionOperationId()); + if (updated != 1) { + throw new VersionConflictException("Account active JWKS promotion receipt CAS did not apply"); + } + StoredPromotion readback = selectPromotion(candidate.promotionOperationId(), true); + if (readback == null + || !candidate.receiptDigest().equals(readback.activeJwksReceiptDigest()) + || !candidate.publicDataDigest().equals(readback.activeJwksPublicDataDigest()) + || !candidate + .observedResourceVersion() + .equals(readback.activeJwksObservedResourceVersion())) { + throw new QuarantinedStateException("Account active JWKS receipt did not read back exactly"); + } + return candidate; + } + + /** + * Commits only after both exact external-resource receipts are durably read back. The promotion + * row and desired-state active fences transition in one Account transaction. + */ + @Transactional(propagation = Propagation.MANDATORY) + public CommittedSignerEvidence commitPreparedPromotion( + Binding expectedBinding, + TrustFence trust, + UUID promotionOperationId, + ReadinessPromotionProof readinessProof) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(promotionOperationId); + Objects.requireNonNull(readinessProof, "Current Account readiness proof is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + if (!state.preparedOperationId().equals(Optional.of(promotionOperationId))) { + throw new StaleGenerationOperationException( + "Commit does not target Account's exact PREPARED promotion"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account promotion lacks exact private and public resource receipts"); + } + if (!promotion.privatePromotionDispatched()) { + throw new QuarantinedStateException( + "Account promotion receipts have no durable private dispatch authorization"); + } + StoredGenerationOperation generation = + selectGenerationOperation(promotion.generationOperationId(), true); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), true); + if (generation == null || result == null) { + throw new QuarantinedStateException("Committed signer generation evidence is missing"); + } + verifyPreparedGenerationMatches(promotion, generation, result); + PromotionPreparation commitPreparation = + new PromotionPreparation( + promotion.generationOperationId(), + result, + state.enrollmentIdentity().orElseThrow(), + promotion.apiBindingDigest(), + promotion.apiConfigRevision(), + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + promotion.prepublicationIntentDigest(), + promotion.prepublicationReceiptDigest(), + promotion.mountedObservationDigest(), + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.expectedPublicJwksJson()); + requireReadinessProofMatches( + result, commitPreparation, promotion, expectedBinding, trust, readinessProof); + + // Readiness freshness was required before PREPARED and again at the one-way dispatch boundary. + // After dispatch, recovery is authorized by that exact immutable proof and the durable + // resource receipts, not by the proof's former wall-clock window. + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET status = 'COMMITTED' WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_dispatched_at IS NOT NULL " + + "AND private_promotion_receipt_digest IS NOT NULL " + + "AND active_jwks_receipt_digest IS NOT NULL " + + "AND readiness_plan_digest = ? AND readiness_evidence_digest = ? " + + "AND encode(sha256(readiness_evidence_preimage), 'hex') = readiness_evidence_digest " + + "AND EXISTS (SELECT 1 FROM account_jwt_readiness_probe_plans plan " + + "WHERE plan.rotation_operation_id = ? AND plan.plan_digest = ? " + + "AND plan.validator_inventory_complete = TRUE) " + + "AND (SELECT count(*) FROM account_jwt_readiness_probe_entries entry " + + "WHERE entry.rotation_operation_id = ? AND entry.plan_digest = ?) = ? " + + "AND (SELECT count(*) FROM account_jwt_readiness_probe_entries entry " + + "WHERE entry.rotation_operation_id = ? AND entry.plan_digest = ? " + + "AND entry.state = 'VERIFIED' AND entry.verification_receipt_sha256 IS NOT NULL " + + "AND entry.verified_at_epoch_seconds < entry.expires_at_epoch_seconds) = ?", + promotionOperationId, + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + readinessProof.verifiedProbes().size(), + promotion.generationOperationId(), + promotion.readinessPlanDigest(), + readinessProof.verifiedProbes().size()); + if (changed != 1) { + throw new VersionConflictException("Account promotion terminal CAS did not apply"); + } + int advanced = + dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, durable_active_generation = ?, " + + "durable_active_kid = ?, published_active_generation = ?, published_active_kid = ?, " + + "prepared_operation_id = NULL, updated_at = CURRENT_TIMESTAMP " + + "WHERE environment_id = ? AND cluster_id = ? AND kubernetes_namespace = ? " + + "AND custody_mode = ? AND record_version = ? AND prepared_operation_id = ? " + + "AND generation_operation_id IS NULL " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ?", + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + promotionOperationId, + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + if (advanced != 1) { + throw new VersionConflictException("Account committed active-signer CAS did not apply"); + } + StoredPromotion committed = selectPromotion(promotionOperationId, true); + Record committedStateRow = selectState(expectedBinding.environmentId(), true); + if (committed == null || committedStateRow == null || !"COMMITTED".equals(committed.status())) { + throw new QuarantinedStateException("Account committed promotion did not read back"); + } + DesiredState committedState = decodeState(committedStateRow); + requireCommittedStateMatches(committed, committedState); + return new CommittedSignerEvidence( + committed.publicEvidence(), + result, + committedState, + PrivatePromotionReceipt.fromStored(committed), + ActiveJwksPromotionReceipt.fromStored(committed)); + } + + /** + * Aborts only before either Kubernetes mutation was recorded. Once either external write may have + * happened, the operation remains PREPARED for exact forward recovery rather than guessing + * rollback state. + */ + @Transactional(propagation = Propagation.MANDATORY) + public AbortedPromotion abortPreparedBeforeMutation( + Binding expectedBinding, TrustFence trust, UUID promotionOperationId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(promotionOperationId); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + if (!state.preparedOperationId().equals(Optional.of(promotionOperationId))) { + throw new StaleGenerationOperationException( + "Abort does not target the exact PREPARED operation"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, true); + if (promotion == null || !"PREPARED".equals(promotion.status())) { + throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); + } + requirePromotionMatchesState(promotion, state); + requireCurrentTrust(promotion, trust); + if (promotion.privatePromotionDispatched() + || promotion.privatePromotionReceiptDigest() != null + || promotion.activeJwksReceiptDigest() != null) { + throw new PromotionPrerequisitesIncompleteException( + "A dispatched promotion must remain PREPARED for forward reconciliation"); + } + int changed = + dsl.execute( + "UPDATE " + + PROMOTION_TABLE + + " SET status = 'ABORTED' WHERE operation_id = ? " + + "AND status = 'PREPARED' AND private_promotion_receipt_digest IS NULL " + + "AND active_jwks_receipt_digest IS NULL " + + "AND private_promotion_dispatched_at IS NULL", + promotionOperationId); + if (changed != 1) + throw new VersionConflictException("Account promotion abort CAS did not apply"); + int advanced = + dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, prepared_operation_id = NULL, " + + "updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? AND record_version = ? " + + "AND prepared_operation_id = ? AND generation_operation_id IS NULL", + expectedBinding.environmentId(), + state.recordVersion(), + promotionOperationId); + if (advanced != 1) + throw new VersionConflictException("Account signer abort state CAS did not apply"); + StoredPromotion aborted = selectPromotion(promotionOperationId, true); + DesiredState abortedState = decodeState(selectState(expectedBinding.environmentId(), true)); + if (aborted == null + || !"ABORTED".equals(aborted.status()) + || abortedState.preparedOperationId().isPresent()) { + throw new QuarantinedStateException("Account aborted promotion did not read back exactly"); + } + return new AbortedPromotion( + promotionOperationId, + abortedState.recordVersion(), + abortedState.durableActive(), + abortedState.publishedActive()); + } + + /** Reads only the exact Account-committed generation and both durable resource receipts. */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readCurrentCommittedSigner( + Binding expectedBinding, + TrustFence trust, + String currentApiBindingDigest, + String currentApiConfigRevision) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) return Optional.empty(); + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow(); + requireMatch(SHA256_HEX, currentApiBindingDigest, "current public API binding digest"); + requireMatch(CLUSTER_ID, currentApiConfigRevision, "current public API config revision"); + if (!enrollment.apiBindingDigest().equals(currentApiBindingDigest) + || !enrollment.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException("Protected Account JWKS API binding changed"); + } + if (state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Account signer lifecycle is unresolved and cannot serve a committed signer"); + } + if (state.durableActive().isEmpty() || !state.durableActive().equals(state.publishedActive())) { + throw new QuarantinedStateException( + "Account durable and published active signer fences disagree"); + } + ActiveSigner active = state.durableActive().orElseThrow(); + if (state.generationOperationId().isPresent()) { + StoredGenerationOperation pending = + selectGenerationOperation(state.generationOperationId().orElseThrow(), false); + if (pending == null) { + throw new QuarantinedStateException("Current Account generation operation is missing"); + } + verifyOperationMatchesState(pending, state); + requireCurrentTrust(pending, trust); + } + StoredPromotion promotion = selectCommittedPromotion(state, active); + if (promotion == null) { + throw new QuarantinedStateException( + "Account active signer has no exact committed promotion receipt"); + } + requireCurrentTrust(promotion, trust); + requireCommittedActiveStillCurrent(promotion, state); + if (!promotion.apiBindingDigest().equals(currentApiBindingDigest) + || !promotion.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException( + "Committed signer uses an obsolete Account JWKS API binding"); + } + StoredGenerationOperation generation = + selectGenerationOperation(promotion.generationOperationId(), false); + GenerationResult result = selectGenerationResult(promotion.generationOperationId(), false); + if (generation == null || result == null) { + throw new QuarantinedStateException("Committed Account generation result is missing"); + } + verifyPreparedGenerationMatches(promotion, generation, result); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException( + "Committed Account signer is missing exact resource receipts"); + } + return Optional.of( + new CommittedSignerEvidence( + promotion.publicEvidence(), + result, + state, + PrivatePromotionReceipt.fromStored(promotion), + ActiveJwksPromotionReceipt.fromStored(promotion))); + } + + /** + * Reads the original committed signer after ordinary rotation. This authenticates retained + * lifecycle provenance only; the caller must separately verify that the original public JWK is + * still accepted by the current protected JWKS source. No current-active equality is imposed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public Optional readOriginalCommittedSigner( + Binding expectedBinding, + TrustFence trust, + String currentApiBindingDigest, + String currentApiConfigRevision, + UUID promotionOperationId, + UUID generationOperationId) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding); + Objects.requireNonNull(trust); + requireOperationId(promotionOperationId); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, currentApiBindingDigest, "current public API binding digest"); + requireMatch(CLUSTER_ID, currentApiConfigRevision, "current public API config revision"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) return Optional.empty(); + DesiredState current = decodeState(stateRow); + requireBinding(current, expectedBinding); + requireEnrollmentTrust(current, trust); + EnrollmentIdentity enrollment = current.enrollmentIdentity().orElseThrow(); + if (!enrollment.apiBindingDigest().equals(currentApiBindingDigest) + || !enrollment.apiConfigRevision().equals(currentApiConfigRevision)) { + throw new BindingMismatchException("Protected Account JWKS API binding changed"); + } + StoredPromotion promotion = selectPromotion(promotionOperationId, false); + if (promotion == null) return Optional.empty(); + requireCurrentTrust(promotion, trust); + if (!"COMMITTED".equals(promotion.status()) + || !expectedBinding.equals(promotion.binding()) + || !generationOperationId.equals(promotion.generationOperationId()) + || !currentApiBindingDigest.equals(promotion.apiBindingDigest()) + || !currentApiConfigRevision.equals(promotion.apiConfigRevision())) { + throw new QuarantinedStateException("Original committed signer identity differs"); + } + StoredGenerationOperation generation = selectGenerationOperation(generationOperationId, false); + GenerationResult result = selectGenerationResult(generationOperationId, false); + if (generation == null || result == null) { + throw new QuarantinedStateException("Original committed signer generation is absent"); + } + requireCurrentTrust(generation, trust); + verifyPreparedGenerationMatches(promotion, generation, result); + if (promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException("Original committed signer resource receipts are absent"); + } + return Optional.of( + new OriginalCommittedSignerEvidence( + promotion.publicEvidence(), + result, + PrivatePromotionReceipt.fromStored(promotion), + ActiveJwksPromotionReceipt.fromStored(promotion))); + } + + /** Immutable historical owner readback, not an active-key or authenticated-actor grant. */ + public record OriginalCommittedSignerEvidence( + PromotionOperationEvidence promotion, + GenerationResult generationResult, + PrivatePromotionReceipt privateReceipt, + ActiveJwksPromotionReceipt publicReceipt) { + public OriginalCommittedSignerEvidence { + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + Objects.requireNonNull(privateReceipt); + Objects.requireNonNull(publicReceipt); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.generationOperationId().equals(generationResult.operationId()) + || !promotion.operationId().equals(privateReceipt.promotionOperationId()) + || !promotion.operationId().equals(publicReceipt.promotionOperationId())) { + throw new QuarantinedStateException("Original committed signer linkage is inconsistent"); + } + } + } + + /** Persists the pinned materializer's read-only observation of the fixed pre-created Secret. */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationRequest recordSecretObservation( + Binding expectedBinding, + TrustFence trust, + UUID operationId, + String operationDigest, + String secretUid, + String observedResourceVersion) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, operationDigest, "JWT generation operation digest"); + requireUuid(secretUid, "fixed Secret UID"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + + LockedCurrent current = lockCurrentOperation(expectedBinding, trust, operationId); + if (!current.operation().operationDigest().equals(operationDigest)) { + throw new IdempotencyConflictException( + "JWT signer Secret observation does not match the Account operation digest"); + } + SecretObservation candidate = + SecretObservation.from(current.operation(), secretUid, observedResourceVersion); + SecretObservation existing = selectSecretObservation(operationId, true); + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer Secret observation changed for the same Account operation"); + } + return readGenerationRequest(current.operation(), current.state(), true); + } + + insertSecretObservation(candidate); + SecretObservation readback = selectSecretObservation(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account JWT signer Secret observation did not read back exactly"); + } + return toGenerationRequest(current.operation(), current.state(), readback, null); + } + + /** + * Persists one public-only key-generation result. Account validates the canonical RSA JWK and + * derives the RFC 7638 fingerprint; private members, tokens, and caller fingerprints are not + * accepted. Exact retries return the immutable receipt; changed/stale retries fail closed. + */ + @Transactional(propagation = Propagation.MANDATORY) + public GenerationResult recordGenerationResult( + Binding expectedBinding, + TrustFence trust, + UUID operationId, + String generationRequestDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String publicJwkJson) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, generationRequestDigest, "JWT generation request digest"); + requireUuid(secretUid, "fixed Secret UID"); + requireMatch(RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret resourceVersion"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + if (expectedPriorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException("JWT signer Secret resourceVersion did not advance"); + } + PublicJwk publicJwk = parsePublicJwk(publicJwkJson); + + LockedCurrent current = lockCurrentOperation(expectedBinding, trust, operationId); + StoredGenerationOperation operation = current.operation(); + SecretObservation observation = selectSecretObservation(operationId, true); + if (observation == null) { + throw new MissingGenerationObservationException( + "JWT signer generation cannot precede exact Secret observation"); + } + if (!observation.secretUid().equals(secretUid) + || !observation.observedResourceVersion().equals(expectedPriorResourceVersion) + || !observation.generationRequestDigest().equals(generationRequestDigest)) { + throw new StaleGenerationOperationException( + "JWT signer generation result does not match the observed Secret fence"); + } + if (!publicJwk.kid().equals(operation.targetKid()) + || !ALGORITHM.equals(operation.targetAlgorithm())) { + throw new QuarantinedStateException( + "JWT signer public JWK does not match the Account-selected key identity"); + } + + GenerationResult candidate = + GenerationResult.from( + operation, + current.state().recordVersion(), + observation, + observedResourceVersion, + publicJwk); + GenerationResult existing = selectGenerationResult(operationId, true); + if (existing != null) { + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer generation result changed for the same Account operation"); + } + return existing; + } + + insertGenerationResult(candidate); + GenerationResult readback = selectGenerationResult(operationId, true); + if (readback == null || !readback.equals(candidate)) { + throw new QuarantinedStateException( + "Account JWT signer generation result did not read back exactly"); + } + return readback; + } + + /** + * Persists PREPARED only for exact owner-readback generation, prepublication, and readiness + * evidence supplied by the lifecycle coordinator. The database independently locks and checks the + * generation/publication/readiness rows; caller booleans and signer/JWKS agreement alone cannot + * enter PREPARED. + */ + @Transactional(propagation = Propagation.MANDATORY) + public PreparedPromotion prepareCurrentGeneration( + Binding expectedBinding, + TrustFence trust, + PromotionPreparation preparation, + ReadinessPromotionProof readinessProof) { + requireWritableAccountTransaction(); + Objects.requireNonNull(expectedBinding, "Expected JWT signer binding is required"); + Objects.requireNonNull(trust, "Protected JWT materializer trust fence is required"); + Objects.requireNonNull(preparation, "Owner-readback promotion preparation is required"); + Objects.requireNonNull(readinessProof, "Account-verified readiness proof is required"); + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + requireEnrollmentTrust(state, trust); + EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow(); + if (!enrollment.sameStablePins(preparation.enrollmentIdentity()) + || !enrollment.apiBindingDigest().equals(preparation.apiBindingDigest()) + || !enrollment.apiConfigRevision().equals(preparation.apiConfigRevision()) + || !enrollment.publicConfigMapUid().equals(preparation.publicConfigMapUid())) { + throw new BindingMismatchException( + "JWT signer promotion trust does not match the independently pinned enrollment"); + } + if (state.preparedOperationId().isPresent()) { + StoredPromotion replay = selectPromotion(state.preparedOperationId().orElseThrow(), true); + if (replay == null || !"PREPARED".equals(replay.status())) { + throw new QuarantinedStateException("Account PREPARED promotion is missing"); + } + requirePromotionMatchesState(replay, state); + requireCurrentTrust(replay, trust); + StoredGenerationOperation replayGeneration = + selectGenerationOperation(replay.generationOperationId(), true); + GenerationResult replayResult = selectGenerationResult(replay.generationOperationId(), true); + if (replayGeneration == null || replayResult == null) { + throw new QuarantinedStateException("Prepared promotion source generation is missing"); + } + verifyPreparedGenerationMatches(replay, replayGeneration, replayResult); + if (!replay.matchesPreparation( + preparation, replayGeneration, replayResult, enrollment, readinessProof)) { + throw new IdempotencyConflictException( + "JWT signer promotion retry changed its immutable evidence"); + } + requireReadinessProofMatches( + replayResult, preparation, replay, expectedBinding, trust, readinessProof); + return new PreparedPromotion(replay.operationId(), replay.requestDigest(), "PREPARED"); + } + UUID generationOperationId = + state + .generationOperationId() + .orElseThrow( + () -> + new MissingGenerationOperationException( + "Account has no current generation operation to promote")); + StoredGenerationOperation generation = selectGenerationOperation(generationOperationId, true); + GenerationResult result = selectGenerationResult(generationOperationId, true); + if (generation == null || result == null) { + throw new PromotionPrerequisitesIncompleteException( + "Account generation operation has no exact persisted result"); + } + verifyOperationMatchesState(generation, state); + requireCurrentTrust(generation, trust); + verifyGenerationResultMatchesOperation(result, generation, state); + if (!result.equals(preparation.generationResult()) + || !preparation.generationOperationId().equals(generationOperationId)) { + throw new StaleGenerationOperationException( + "Promotion preparation does not match the exact current generation result"); + } + requireReadinessProofMatches(result, preparation, null, expectedBinding, trust, readinessProof); + requireCurrentPublicationForPreparation(result, preparation); + requireCurrentReadinessForPreparation(result, preparation); + + StoredPromotion candidate = + StoredPromotion.create( + preparation, state, generation, result, trust, expectedBinding, readinessProof); + StoredPromotion existing = selectPromotion(candidate.operationId(), true); + if (existing != null) { + requirePromotionMatchesState(existing, state); + if (!existing.equals(candidate)) { + throw new IdempotencyConflictException( + "JWT signer promotion request changed for the same operation"); + } + return new PreparedPromotion(existing.operationId(), existing.requestDigest(), "PREPARED"); + } + insertPromotion(candidate); + int advanced = advanceToPrepared(state, candidate.operationId()); + if (advanced != 1) { + throw new VersionConflictException("Account desired state changed while entering PREPARED"); + } + StoredPromotion readback = selectPromotion(candidate.operationId(), true); + Record stateReadbackRow = selectState(expectedBinding.environmentId(), true); + if (readback == null || stateReadbackRow == null || !readback.equals(candidate)) { + throw new QuarantinedStateException("Account PREPARED promotion did not read back exactly"); + } + DesiredState stateReadback = decodeState(stateReadbackRow); + requirePromotionMatchesState(readback, stateReadback); + return new PreparedPromotion(readback.operationId(), readback.requestDigest(), "PREPARED"); + } + + private static void requireReadinessProofMatches( + GenerationResult result, + PromotionPreparation preparation, + StoredPromotion preparedReplay, + Binding expectedBinding, + TrustFence trust, + ReadinessPromotionProof proof) { + var plan = proof.plan(); + var publication = proof.publication(); + if (!proof.generationResult().equals(result) + || !preparation.generationResult().equals(result) + || !plan.operationId().equals(result.operationId()) + || !plan.binding().equals(expectedBinding) + || !plan.trustFence().equals(trust) + || !plan.planDigest().equals(preparation.readinessPlanDigest()) + || !proof.readinessEvidenceDigest().equals(preparation.readinessEvidenceDigest()) + || !plan.operationDigest().equals(result.operationDigest()) + || !plan.generationRequestDigest().equals(result.generationRequestDigest()) + || !plan.generationReceiptDigest().equals(result.receiptDigest()) + || plan.desiredStateVersion() != result.desiredStateVersion() + || !plan.targetGeneration().equals(result.targetGeneration()) + || !plan.targetKid().equals(result.targetKid()) + || !plan.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint()) + || !publication.intent().intentDigest().equals(preparation.prepublicationIntentDigest()) + || !publication.receipt().receiptDigest().equals(preparation.prepublicationReceiptDigest()) + || !publication + .mountedCorrespondence() + .observationDigest() + .equals(preparation.mountedObservationDigest()) + || !publication.intent().configMapUid().equals(preparation.publicConfigMapUid()) + || !publication + .receipt() + .observedResourceVersion() + .equals(preparation.expectedPublicResourceVersion()) + || !publication.intent().apiBindingDigest().equals(preparation.apiBindingDigest()) + || !publication.intent().apiConfigRevision().equals(preparation.apiConfigRevision()) + || !publication.intent().jwksJson().equals(preparation.expectedPublicJwksJson())) { + throw new PromotionPrerequisitesIncompleteException( + "Account readiness proof does not match the exact generation and publication"); + } + if (preparedReplay != null + && (!preparedReplay.readinessPlanDigest().equals(plan.planDigest()) + || !preparedReplay.readinessEvidenceDigest().equals(proof.readinessEvidenceDigest()) + || !Arrays.equals( + preparedReplay.readinessEvidencePreimage().getBytes(StandardCharsets.UTF_8), + proof.readinessEvidencePreimage()))) { + throw new IdempotencyConflictException( + "Readiness recovery proof changed from the exact frozen PREPARED evidence"); + } + if (!plan.validatorInventoryComplete() + || proof.inventoryEvidenceReference() == null + || !proof.inventoryEvidenceReference().matches("[A-Za-z0-9][A-Za-z0-9._:/-]{0,511}") + || proof.inventoryEvidenceDigest() == null + || !proof.inventoryEvidenceDigest().matches("[0-9a-f]{64}") + || proof.verifiedProbes().isEmpty() + || !proof.readinessEvidenceDigest().matches("[0-9a-f]{64}") + || !publication.intent().operationId().equals(result.operationId()) + || !publication.receipt().operationId().equals(result.operationId()) + || !publication.mountedCorrespondence().operationId().equals(result.operationId()) + || !publication.intent().intentDigest().equals(plan.publicationIntentDigest()) + || !publication.receipt().receiptDigest().equals(plan.publicationReceiptDigest()) + || !publication + .mountedCorrespondence() + .observationDigest() + .equals(plan.mountedObservationDigest())) { + throw new PromotionPrerequisitesIncompleteException( + "Account readiness proof lacks exact publication or protected inventory evidence"); + } + } + + private GenerationRequest createGenerationRequest(DesiredState state, TrustFence trust) { + if (state.recordVersion() == Long.MAX_VALUE) { + throw new VersionConflictException("Account JWT signer state version is exhausted"); + } + long previousGeneration = + Math.max( + Math.max( + state.durableActive().map(value -> parseGeneration(value.generation())).orElse(0L), + state + .publishedActive() + .map(value -> parseGeneration(value.generation())) + .orElse(0L)), + Objects.requireNonNull( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT COALESCE(MAX(target_generation), 0) FROM " + + OPERATION_TABLE + + " WHERE environment_id = ?", + state.binding().environmentId()), + "Historical Account generation high-water row is required") + .get(0, Long.class), + "Historical Account generation high-water readback is required")); + if (previousGeneration == Long.MAX_VALUE) { + throw new VersionConflictException("Account JWT signer generation is exhausted"); + } + long targetGeneration = previousGeneration + 1; + UUID operationId = UUID.randomUUID(); + String targetKid = "jwt-" + targetGeneration + "-" + operationId.toString().substring(0, 12); + StoredGenerationOperation operation = + StoredGenerationOperation.create(state, trust, operationId, targetGeneration, targetKid); + insertGenerationOperation(operation); + int changed = advanceToGenerationRequest(state, operationId); + if (changed != 1) { + throw new VersionConflictException( + "Account JWT signer state changed during request creation"); + } + Record readbackStateRow = selectState(state.binding().environmentId(), true); + Record readbackOperationRow = selectGenerationOperationRow(operationId, true); + if (readbackStateRow == null || readbackOperationRow == null) { + throw new QuarantinedStateException("Account JWT generation request did not read back"); + } + DesiredState readbackState = decodeState(readbackStateRow); + StoredGenerationOperation readbackOperation = decodeGenerationOperation(readbackOperationRow); + requireBinding(readbackState, state.binding()); + verifyOperationMatchesState(readbackOperation, readbackState); + if (!readbackOperation.equals(operation)) { + throw new QuarantinedStateException("Account JWT generation request changed on readback"); + } + return readGenerationRequest(readbackOperation, readbackState, true); + } + + private GenerationRequest readGenerationRequest( + StoredGenerationOperation operation, DesiredState state, boolean lockEvidence) { + GenerationResult result = selectGenerationResult(operation.operationId(), lockEvidence); + if (result != null) { + verifyGenerationResultMatchesOperation(result, operation, state); + return toGenerationRequest(operation, state, null, result); + } + SecretObservation observation = selectSecretObservation(operation.operationId(), lockEvidence); + if (observation != null) { + verifySecretObservationMatchesOperation(observation, operation, state); + } + return toGenerationRequest(operation, state, observation, null); + } + + private static void verifySecretObservationMatchesOperation( + SecretObservation observation, StoredGenerationOperation operation, DesiredState state) { + if (!observation.operationId().equals(operation.operationId()) + || !observation.binding().equals(operation.binding()) + || !observation.operationDigest().equals(operation.operationDigest()) + || observation.expectedRecordVersion() != operation.expectedRecordVersion() + || !observation.trustFence().equals(operation.trustFence()) + || state.recordVersion() != operation.expectedRecordVersion() + 1) { + throw new QuarantinedStateException( + "JWT signer Secret observation is not bound to its operation"); + } + } + + private static void verifyGenerationResultMatchesOperation( + GenerationResult result, StoredGenerationOperation operation, DesiredState state) { + if (!result.operationId().equals(operation.operationId()) + || !result.binding().equals(operation.binding()) + || !result.operationDigest().equals(operation.operationDigest()) + || !result.trustFence().equals(operation.trustFence()) + || result.desiredStateVersion() != state.recordVersion() + || !result.targetGeneration().equals(operation.targetGeneration()) + || !result.targetKid().equals(operation.targetKid()) + || !result.targetAlgorithm().equals(operation.targetAlgorithm())) { + throw new QuarantinedStateException( + "JWT signer generation result is not bound to its operation"); + } + } + + private GenerationRequest toGenerationRequest( + StoredGenerationOperation operation, + DesiredState state, + SecretObservation observation, + GenerationResult result) { + GenerationPhase phase = + result != null + ? GenerationPhase.GENERATION_RECORDED + : observation != null + ? GenerationPhase.GENERATE_PENDING + : GenerationPhase.OBSERVE_PRIVATE_SECRET; + return new GenerationRequest( + phase, + operation.operationId(), + operation.operationDigest(), + result != null + ? result.generationRequestDigest() + : observation == null ? "" : observation.generationRequestDigest(), + state.recordVersion(), + operation.binding(), + operation.trustFence(), + PRIVATE_SECRET_NAME, + operation.targetGeneration(), + operation.targetKid(), + operation.targetAlgorithm(), + ACTION, + List.of(PENDING_SLOT), + operation.expectedPreviousActive(), + operation.expectedPublishedActive(), + result != null ? result.secretUid() : observation == null ? "" : observation.secretUid(), + result != null + ? result.expectedPriorResourceVersion() + : observation == null ? "" : observation.observedResourceVersion(), + result == null ? "" : result.receiptDigest(), + result == null ? "" : result.publicKeyFingerprint(), + result == null ? "" : result.publicJwkJson(), + result == null ? "" : result.observedResourceVersion()); + } + + private LockedCurrent lockCurrentOperation( + Binding expectedBinding, TrustFence trust, UUID operationId) { + Record stateRow = selectState(expectedBinding.environmentId(), true); + if (stateRow == null) { + throw new MissingDesiredStateException(expectedBinding.environmentId()); + } + DesiredState state = decodeState(stateRow); + requireBinding(state, expectedBinding); + verifyPreparedIsUnavailable(state); + if (!state.generationOperationId().equals(Optional.of(operationId))) { + throw new StaleGenerationOperationException( + "JWT signer request does not target Account's current generation operation"); + } + StoredGenerationOperation operation = selectGenerationOperation(operationId, true); + if (operation == null) { + throw new QuarantinedStateException("Account JWT signer generation operation is missing"); + } + verifyOperationMatchesState(operation, state); + requireCurrentTrust(operation, trust); + return new LockedCurrent(state, operation); + } + + private void requireCurrentTrust(StoredGenerationOperation operation, TrustFence current) { + if (!operation.trustFence().equals(current)) { + throw new BindingMismatchException( + "JWT materializer trust or namespace incarnation changed for the generation operation"); + } + } + + private static void requireEnrollmentTrust(DesiredState state, TrustFence trust) { + EnrollmentIdentity enrolled = + state + .enrollmentIdentity() + .orElseThrow( + () -> + new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity")); + if (!enrolled.expectedClusterIncarnationUid().equals(trust.expectedClusterIncarnationUid()) + || !enrolled.expectedNamespaceUid().equals(trust.expectedNamespaceUid()) + || !enrolled.materializerTrustBindingDigest().equals(trust.bindingDigest()) + || !enrolled.materializerTrustConfigRevision().equals(trust.configRevision())) { + throw new BindingMismatchException( + "JWT materializer trust no longer matches Account's pinned enrollment"); + } + } + + private void verifyOperationMatchesState( + StoredGenerationOperation operation, DesiredState state) { + if (!state.generationOperationId().equals(Optional.of(operation.operationId())) + || !operation.binding().equals(state.binding()) + || operation.expectedRecordVersion() == Long.MAX_VALUE + || state.recordVersion() != operation.expectedRecordVersion() + 1 + || !operation.expectedPreviousActive().equals(state.durableActive()) + || !operation.expectedPublishedActive().equals(state.publishedActive()) + || !REQUEST_DIGEST_VERSION.equals(operation.digestVersion()) + || !generationOperationDigest(operation).equals(operation.operationDigest())) { + throw new QuarantinedStateException( + "Account JWT signer generation request does not match current desired state"); + } + } + + private Record selectState(String environmentId, boolean lock) { + return dsl.fetchOne( + "SELECT environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "private_secret_name, public_jwks_config_map_name, record_version, " + + "durable_active_generation, durable_active_kid, published_active_generation, " + + "published_active_kid, generation_operation_id, prepared_operation_id, " + + "enrollment_cluster_incarnation_uid, enrollment_namespace_uid, " + + "enrollment_materializer_binding_digest, enrollment_materializer_config_revision, " + + "enrollment_api_binding_digest, enrollment_api_config_revision, " + + "enrollment_public_config_map_uid, enrollment_public_config_map_resource_version, " + + "enrollment_public_config_map_snapshot_digest FROM " + + STATE_TABLE + + " WHERE environment_id = ?" + + (lock ? " FOR UPDATE" : ""), + environmentId); + } + + private StoredPromotion selectPromotion(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT p.operation_id, p.environment_id, p.cluster_id, p.kubernetes_namespace, p.custody_mode, " + + "p.request_digest_version, p.request_digest, p.expected_record_version, " + + "p.expected_previous_generation, p.expected_previous_kid, p.target_generation, p.target_kid, " + + "p.target_algorithm, p.target_public_key_fingerprint, " + + "p.expected_private_secret_resource_version, p.expected_public_jwks_resource_version, " + + "p.expected_public_active_generation, p.expected_public_active_kid, p.operation_action, " + + "p.allowed_private_slots_canonical_bytes, p.status, p.generation_operation_id, " + + "p.expected_cluster_incarnation_uid, p.expected_namespace_uid, " + + "p.materializer_trust_binding_digest, p.materializer_trust_config_revision, " + + "p.api_binding_digest, p.api_config_revision, p.expected_private_secret_uid, " + + "p.expected_public_config_map_uid, p.prepublication_intent_digest, " + + "p.prepublication_receipt_digest, p.mounted_observation_digest, p.readiness_plan_digest, " + + "p.readiness_evidence_digest, p.readiness_evidence_preimage, p.expected_public_jwks_json, " + + "p.expected_active_generation_marker_json, " + + "(p.private_promotion_dispatched_at IS NOT NULL) AS private_promotion_dispatched, " + + "p.private_promotion_observed_resource_version, " + + "p.private_promotion_receipt_digest, p.active_jwks_observed_resource_version, " + + "p.active_jwks_public_data_digest, p.active_jwks_receipt_digest, " + + "generation.operation_digest AS generation_operation_digest, " + + "generation_result.receipt_digest AS generation_receipt_digest " + + "FROM " + + PROMOTION_TABLE + + " AS p " + + "JOIN " + + OPERATION_TABLE + + " AS generation " + + "ON generation.operation_id = p.generation_operation_id " + + "JOIN " + + RESULT_TABLE + + " AS generation_result " + + "ON generation_result.operation_id = p.generation_operation_id " + + "WHERE p.operation_id = ?" + + (lock ? " FOR UPDATE OF p, generation, generation_result" : ""), + operationId); + return row == null ? null : decodePromotion(row); + } + + private StoredPromotion selectCommittedPromotion(DesiredState state, ActiveSigner active) { + Result rows = + dsl.fetch( + "SELECT operation_id FROM " + + PROMOTION_TABLE + + " WHERE environment_id = ? AND cluster_id = ? AND kubernetes_namespace = ? " + + "AND custody_mode = ? AND status = 'COMMITTED' AND target_generation = ? " + + "AND target_kid = ? ORDER BY created_at DESC LIMIT 2", + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + parseGeneration(active.generation()), + active.kid()); + if (rows.size() != 1) { + throw new QuarantinedStateException( + "Account active signer does not resolve to exactly one committed promotion"); + } + UUID operationId = rows.get(0).get("operation_id", UUID.class); + return selectPromotion(operationId, false); + } + + private static void requireCommittedStateMatches(StoredPromotion promotion, DesiredState state) { + ActiveSigner expected = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.binding().equals(state.binding()) + || state.preparedOperationId().isPresent() + || state.generationOperationId().isPresent() + || state.durableActive().filter(expected::equals).isEmpty() + || state.publishedActive().filter(expected::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() != promotion.expectedRecordVersion() + 2 + || promotion.privatePromotionReceiptDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException( + "Committed Account signer does not match its exact operation and active fences"); + } + } + + private static void requireCommittedActiveStillCurrent( + StoredPromotion promotion, DesiredState state) { + ActiveSigner expected = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.binding().equals(state.binding()) + || state.preparedOperationId().isPresent() + || state.durableActive().filter(expected::equals).isEmpty() + || state.publishedActive().filter(expected::equals).isEmpty() + || promotion.expectedRecordVersion() > Long.MAX_VALUE - 2 + || state.recordVersion() < promotion.expectedRecordVersion() + 2) { + throw new QuarantinedStateException( + "Committed Account promotion is not the current active signer"); + } + } + + private static void requireActiveJwksObservation( + StoredPromotion promotion, ActiveJwksPromotionObservation observation) { + if (!promotion.publicConfigMapUid().equals(observation.configMapUid()) + || !promotion.expectedPublicResourceVersion().equals(observation.priorResourceVersion()) + || observation.priorResourceVersion().equals(observation.observedResourceVersion()) + || !promotion.expectedPublicJwksJson().equals(observation.jwksJson()) + || !promotion.expectedActiveMarkerJson().equals(observation.activeMarkerJson())) { + throw new QuarantinedStateException( + "Account ConfigMap CAS did not read back the exact authorized ACTIVE projection"); + } + requireActiveMarkerMatchesPromotion(promotion, observation.activeMarkerJson()); + } + + private static void requireActiveMarkerMatchesPromotion( + StoredPromotion promotion, String marker) { + try { + JsonNode root = STRICT_JSON.readTree(marker); + if (root == null + || !root.isObject() + || root.size() != 11 + || !root.path("schemaVersion").isIntegralNumber() + || root.path("schemaVersion").intValue() != 1 + || !"ACTIVE".equals(requiredText(root, "phase", 16)) + || !promotion + .generationOperationId() + .toString() + .equals(requiredText(root, "operationId", 36)) + || !promotion + .generationOperationDigest() + .equals(requiredText(root, "operationDigest", 64)) + || !promotion + .generationReceiptDigest() + .equals(requiredText(root, "generationReceiptDigest", 64)) + || !markerBindingMatches(promotion, root.get("binding")) + || !markerFenceMatches( + promotion, root.get("expectedDurableActive"), promotion.expectedPreviousActive()) + || !markerFenceMatches( + promotion, root.get("expectedPublishedActive"), promotion.expectedPublishedActive()) + || !markerPublicMapMatches(root.get("publicConfigMap")) + || !markerPromotionMatches(promotion, root.get("promotion"))) { + throw new IllegalArgumentException("Active marker mismatch"); + } + JsonNode active = root.get("active"); + if (active == null + || !active.isObject() + || active.size() != 4 + || !promotion.targetGeneration().equals(requiredText(active, "generation", 19)) + || !promotion.targetKid().equals(requiredText(active, "kid", 64)) + || !ALGORITHM.equals(requiredText(active, "algorithm", 16)) + || !promotion + .targetPublicKeyFingerprint() + .equals(requiredText(active, "publicKeyFingerprint", 64))) { + throw new IllegalArgumentException("Active signer mismatch"); + } + } catch (RuntimeException ex) { + throw new QuarantinedStateException("Account ACTIVE generation marker is malformed", ex); + } + } + + private static boolean markerBindingMatches(StoredPromotion promotion, JsonNode binding) { + return binding != null + && binding.isObject() + && binding.size() == 9 + && promotion.binding().environmentId().equals(requiredText(binding, "environmentId", 64)) + && promotion.binding().clusterId().equals(requiredText(binding, "clusterId", 128)) + && promotion.binding().namespace().equals(requiredText(binding, "namespace", 64)) + && promotion + .trustFence() + .expectedClusterIncarnationUid() + .equals(requiredText(binding, "expectedClusterIncarnationUid", 36)) + && promotion + .trustFence() + .expectedNamespaceUid() + .equals(requiredText(binding, "expectedNamespaceUid", 36)) + && promotion + .trustFence() + .bindingDigest() + .equals(requiredText(binding, "trustBindingDigest", 64)) + && promotion + .trustFence() + .configRevision() + .equals(requiredText(binding, "trustConfigRevision", 128)) + && promotion.apiBindingDigest().equals(requiredText(binding, "apiBindingDigest", 64)) + && promotion.apiConfigRevision().equals(requiredText(binding, "apiConfigRevision", 128)); + } + + private static boolean markerFenceMatches( + StoredPromotion promotion, JsonNode fence, Optional expected) { + return fence != null && parseMarkerActive(fence).equals(expected); + } + + private static Optional parseMarkerActive(JsonNode fence) { + if (fence == null || !fence.isObject()) { + throw new IllegalArgumentException("Active marker fence is malformed"); + } + if (fence.size() == 1 + && fence.path("present").isBoolean() + && !fence.path("present").booleanValue()) { + return Optional.empty(); + } + if (fence.size() == 3 + && fence.path("present").isBoolean() + && fence.path("present").booleanValue()) { + return Optional.of( + new ActiveSigner(requiredText(fence, "generation", 19), requiredText(fence, "kid", 64))); + } + throw new IllegalArgumentException("Active marker fence is malformed"); + } + + private static boolean markerPublicMapMatches(JsonNode publicMap) { + return publicMap != null + && publicMap.isObject() + && publicMap.size() == 1 + && PUBLIC_JWKS_CONFIG_MAP_NAME.equals(requiredText(publicMap, "name", 64)); + } + + private static boolean markerPromotionMatches(StoredPromotion promotion, JsonNode proof) { + return proof != null + && proof.isObject() + && proof.size() == 7 + && promotion.operationId().toString().equals(requiredText(proof, "operationId", 36)) + && promotion.requestDigest().equals(requiredText(proof, "requestDigest", 64)) + && promotion + .prepublicationIntentDigest() + .equals(requiredText(proof, "prepublicationIntentDigest", 64)) + && promotion + .prepublicationReceiptDigest() + .equals(requiredText(proof, "prepublicationReceiptDigest", 64)) + && promotion + .mountedObservationDigest() + .equals(requiredText(proof, "mountedObservationDigest", 64)) + && promotion.readinessPlanDigest().equals(requiredText(proof, "readinessPlanDigest", 64)) + && promotion + .readinessEvidenceDigest() + .equals(requiredText(proof, "readinessEvidenceDigest", 64)); + } + + private static String activeMarkerJson(StoredPromotion promotion) { + Map marker = new LinkedHashMap<>(); + marker.put("schemaVersion", 1); + marker.put("phase", "ACTIVE"); + marker.put("operationId", promotion.generationOperationId().toString()); + marker.put("operationDigest", promotion.generationOperationDigest()); + marker.put("generationReceiptDigest", promotion.generationReceiptDigest()); + Map binding = new LinkedHashMap<>(); + binding.put("environmentId", promotion.binding().environmentId()); + binding.put("clusterId", promotion.binding().clusterId()); + binding.put("namespace", promotion.binding().namespace()); + binding.put( + "expectedClusterIncarnationUid", promotion.trustFence().expectedClusterIncarnationUid()); + binding.put("expectedNamespaceUid", promotion.trustFence().expectedNamespaceUid()); + binding.put("trustBindingDigest", promotion.trustFence().bindingDigest()); + binding.put("trustConfigRevision", promotion.trustFence().configRevision()); + binding.put("apiBindingDigest", promotion.apiBindingDigest()); + binding.put("apiConfigRevision", promotion.apiConfigRevision()); + marker.put("binding", binding); + marker.put("publicConfigMap", Map.of("name", PUBLIC_JWKS_CONFIG_MAP_NAME)); + marker.put("expectedDurableActive", activeMarker(promotion.expectedPreviousActive())); + marker.put("expectedPublishedActive", activeMarker(promotion.expectedPublishedActive())); + marker.put( + "active", + Map.of( + "generation", promotion.targetGeneration(), + "kid", promotion.targetKid(), + "algorithm", promotion.targetAlgorithm(), + "publicKeyFingerprint", promotion.targetPublicKeyFingerprint())); + marker.put( + "promotion", + Map.of( + "operationId", promotion.operationId().toString(), + "requestDigest", promotion.requestDigest(), + "prepublicationIntentDigest", promotion.prepublicationIntentDigest(), + "prepublicationReceiptDigest", promotion.prepublicationReceiptDigest(), + "mountedObservationDigest", promotion.mountedObservationDigest(), + "readinessPlanDigest", promotion.readinessPlanDigest(), + "readinessEvidenceDigest", promotion.readinessEvidenceDigest())); + try { + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(marker)), + StandardCharsets.UTF_8); + } catch (IOException ex) { + throw new StorageUnavailableException("Account ACTIVE JWT marker could not be canonicalized"); + } + } + + 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 String requiredText(JsonNode object, String name, int maxLength) { + JsonNode value = object.get(name); + if (value == null + || !value.isTextual() + || value.textValue().isEmpty() + || value.textValue().length() > maxLength) { + throw new IllegalArgumentException("Account JWT signer JSON field is malformed"); + } + return value.textValue(); + } + + private static void requirePromotionMatchesState(StoredPromotion promotion, DesiredState state) { + if (!promotion.binding().equals(state.binding()) + || !state.preparedOperationId().equals(Optional.of(promotion.operationId())) + || state.generationOperationId().isPresent() + || state.recordVersion() != promotion.expectedRecordVersion() + 1 + || !promotion.expectedPreviousActive().equals(state.durableActive()) + || !promotion.expectedPublishedActive().equals(state.publishedActive()) + || !promotion.requestDigest().equals(promotionRequestDigest(promotion))) { + throw new QuarantinedStateException( + "Account PREPARED promotion does not match its exact desired-state fence"); + } + } + + private static void requireCurrentTrust(StoredPromotion promotion, TrustFence current) { + if (!promotion.trustFence().equals(current)) { + throw new BindingMismatchException( + "JWT materializer trust or namespace incarnation changed during promotion"); + } + } + + private static void verifyPreparedGenerationMatches( + StoredPromotion promotion, StoredGenerationOperation operation, GenerationResult result) { + if (!promotion.generationOperationId().equals(operation.operationId()) + || !promotion.binding().equals(operation.binding()) + || !promotion.operationDigestForGeneration().equals(operation.operationDigest()) + || !promotion.expectedPreviousActive().equals(operation.expectedPreviousActive()) + || !promotion.expectedPublishedActive().equals(operation.expectedPublishedActive()) + || !promotion.targetGeneration().equals(operation.targetGeneration()) + || !promotion.targetKid().equals(operation.targetKid()) + || !ALGORITHM.equals(operation.targetAlgorithm()) + || !promotion.trustFence().equals(operation.trustFence()) + || !promotion.generationOperationId().equals(result.operationId()) + || !promotion.generationReceiptDigest().equals(result.receiptDigest()) + || !promotion.secretUid().equals(result.secretUid()) + || !promotion.expectedPrivateResourceVersion().equals(result.observedResourceVersion()) + || !promotion.targetPublicKeyFingerprint().equals(result.publicKeyFingerprint())) { + throw new QuarantinedStateException( + "Prepared promotion is not bound to the exact source generation result"); + } + } + + private static void requirePrivatePromotionObservation( + StoredPromotion promotion, PrivatePromotionObservation observation) { + Optional expectedPrevious = + promotion + .expectedPreviousActive() + .map( + active -> + new PublicKeyIdentity( + active.generation(), + active.kid(), + publicFingerprintForKid(promotion.expectedPublicJwksJson(), active.kid()))); + PublicKeyIdentity expectedCurrent = + new PublicKeyIdentity( + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()); + List expectedSlots = + expectedPrevious.isPresent() ? List.of("current", "previous") : List.of("current"); + if (!observation.secretUid().equals(promotion.secretUid()) + || !observation + .expectedPriorResourceVersion() + .equals(promotion.expectedPrivateResourceVersion()) + || observation.expectedPriorResourceVersion().equals(observation.observedResourceVersion()) + || !expectedCurrent.equals(observation.current()) + || !expectedPrevious.equals(observation.previous()) + || !expectedSlots.equals(observation.resultingSlots())) { + throw new QuarantinedStateException( + "Materializer did not read back the exact authorized private slot transition"); + } + } + + private static String publicFingerprintForKid(String jwksJson, String kid) { + try { + JsonNode root = STRICT_JSON.readTree(jwksJson); + JsonNode keys = root == null ? null : root.get("keys"); + if (keys == null || !keys.isArray()) { + throw new IllegalArgumentException("JWKS keys are malformed"); + } + String found = null; + for (JsonNode key : keys) { + if (key != null && key.isObject() && kid.equals(requiredText(key, "kid", 64))) { + if (found != null) { + throw new IllegalArgumentException("JWKS contains a duplicate kid"); + } + found = + digest( + Map.of( + "e", + requiredText(key, "e", 16), + "kty", + "RSA", + "n", + requiredText(key, "n", 4096))); + } + } + if (found == null) { + throw new IllegalArgumentException("Expected prior public key is missing from JWKS"); + } + return found; + } catch (Exception ex) { + throw new QuarantinedStateException("Expected prior public key identity is unavailable", ex); + } + } + + private StoredPromotion decodePromotion(Record row) { + try { + byte[] slots = row.get("allowed_private_slots_canonical_bytes", byte[].class); + if (!Arrays.equals(PROMOTION_SLOTS_CANONICAL_BYTES, slots) + || !"PROMOTE_PENDING".equals(row.get("operation_action", String.class))) { + throw new QuarantinedStateException( + "Account promotion action or fixed Secret slots are malformed"); + } + StoredPromotion promotion = + new StoredPromotion( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + Math.toIntExact( + positive( + row.get("request_digest_version", Short.class).longValue(), + "promotion digest version")), + row.get("request_digest", String.class), + positive( + row.get("expected_record_version", Long.class), "expected signer state version"), + activeOptional( + row.get("expected_previous_generation", Long.class), + row.get("expected_previous_kid", String.class), + "previous signer"), + activeOptional( + row.get("expected_public_active_generation", Long.class), + row.get("expected_public_active_kid", String.class), + "published previous signer"), + canonicalGeneration( + row.get("target_generation", Long.class), "promotion target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + row.get("target_public_key_fingerprint", String.class), + row.get("expected_private_secret_resource_version", String.class), + row.get("expected_public_jwks_resource_version", String.class), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("materializer_trust_binding_digest", String.class), + row.get("materializer_trust_config_revision", String.class)), + row.get("generation_operation_id", UUID.class), + row.get("generation_operation_digest", String.class), + row.get("generation_receipt_digest", String.class), + row.get("api_binding_digest", String.class), + row.get("api_config_revision", String.class), + row.get("expected_private_secret_uid", UUID.class).toString(), + row.get("expected_public_config_map_uid", UUID.class).toString(), + row.get("prepublication_intent_digest", String.class), + row.get("prepublication_receipt_digest", String.class), + row.get("mounted_observation_digest", String.class), + row.get("readiness_plan_digest", String.class), + row.get("readiness_evidence_digest", String.class), + readinessPreimageText( + row.get("readiness_evidence_preimage", byte[].class), + row.get("readiness_evidence_digest", String.class)), + row.get("expected_public_jwks_json", String.class), + row.get("expected_active_generation_marker_json", String.class), + row.get("status", String.class), + Boolean.TRUE.equals(row.get("private_promotion_dispatched", Boolean.class)), + row.get("private_promotion_observed_resource_version", String.class), + row.get("private_promotion_receipt_digest", String.class), + row.get("active_jwks_observed_resource_version", String.class), + row.get("active_jwks_public_data_digest", String.class), + row.get("active_jwks_receipt_digest", String.class)); + if (promotion.requestDigestVersion() != 1 + || !promotionRequestDigest(promotion).equals(promotion.requestDigest())) { + throw new QuarantinedStateException("Account promotion operation digest is invalid"); + } + return promotion; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account promotion operation is malformed", ex); + } + } + + private static String promotionRequestDigest(StoredPromotion promotion) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", PROMOTION_DIGEST_VERSION); + preimage.put("operationId", promotion.operationId().toString()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("environmentId", promotion.binding().environmentId()); + preimage.put("clusterId", promotion.binding().clusterId()); + preimage.put("namespace", promotion.binding().namespace()); + preimage.put("custodyMode", promotion.binding().mode().value()); + preimage.put("expectedRecordVersion", Long.toString(promotion.expectedRecordVersion())); + preimage.put("expectedPreviousActive", activeDigestValue(promotion.expectedPreviousActive())); + preimage.put("expectedPublishedActive", activeDigestValue(promotion.expectedPublishedActive())); + preimage.put("targetGeneration", promotion.targetGeneration()); + preimage.put("targetKid", promotion.targetKid()); + preimage.put("targetAlgorithm", ALGORITHM); + preimage.put("targetPublicKeyFingerprint", promotion.targetPublicKeyFingerprint()); + preimage.put("expectedPrivateSecretUid", promotion.secretUid()); + preimage.put( + "expectedPrivateSecretResourceVersion", promotion.expectedPrivateResourceVersion()); + preimage.put("expectedPublicConfigMapUid", promotion.publicConfigMapUid()); + preimage.put("expectedPublicJwksResourceVersion", promotion.expectedPublicResourceVersion()); + preimage.put( + "expectedClusterIncarnationUid", promotion.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", promotion.trustFence().expectedNamespaceUid()); + preimage.put("materializerTrustBindingDigest", promotion.trustFence().bindingDigest()); + preimage.put("materializerTrustConfigRevision", promotion.trustFence().configRevision()); + preimage.put("apiBindingDigest", promotion.apiBindingDigest()); + preimage.put("apiConfigRevision", promotion.apiConfigRevision()); + preimage.put("prepublicationIntentDigest", promotion.prepublicationIntentDigest()); + preimage.put("prepublicationReceiptDigest", promotion.prepublicationReceiptDigest()); + preimage.put("mountedObservationDigest", promotion.mountedObservationDigest()); + preimage.put("readinessPlanDigest", promotion.readinessPlanDigest()); + preimage.put("readinessEvidenceDigest", promotion.readinessEvidenceDigest()); + preimage.put("publicJwksSha256", sha256(promotion.expectedPublicJwksJson())); + preimage.put("operationAction", "PROMOTE_PENDING"); + preimage.put("allowedPrivateSlots", List.of("current", "pending", "previous")); + return digest(preimage); + } + + private Record selectGenerationOperationRow(UUID operationId, boolean lock) { + return dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, " + + "expected_published_generation, expected_published_kid, target_generation, target_kid, " + + "target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, operation_action, " + + "allowed_private_slots_canonical_bytes FROM " + + OPERATION_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + } + + private StoredGenerationOperation selectGenerationOperation(UUID operationId, boolean lock) { + Record row = selectGenerationOperationRow(operationId, lock); + return row == null ? null : decodeGenerationOperation(row); + } + + private SecretObservation selectSecretObservation(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, expected_record_version, expected_cluster_incarnation_uid, " + + "expected_namespace_uid, trust_binding_digest, trust_config_revision, " + + "private_secret_name, secret_uid, observed_resource_version, observation_digest, " + + "generation_request_digest FROM " + + OBSERVATION_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeSecretObservation(row); + } + + private GenerationResult selectGenerationResult(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, desired_state_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, " + + "expected_prior_resource_version, observed_resource_version, target_generation, " + + "target_kid, target_algorithm, public_key_fingerprint, public_jwk_json, receipt_digest " + + "FROM " + + RESULT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + return row == null ? null : decodeGenerationResult(row); + } + + private GenerationAbortReceipt selectGenerationAbortReceipt(UUID operationId, boolean lock) { + Record row = + dsl.fetchOne( + "SELECT operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "expected_state_version, resulting_state_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, durable_active_generation, durable_active_kid, " + + "published_active_generation, published_active_kid FROM " + + GENERATION_ABORT_TABLE + + " WHERE operation_id = ?" + + (lock ? " FOR UPDATE" : ""), + operationId); + if (row == null) { + return null; + } + return new GenerationAbortReceipt( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + row.get("generation_receipt_digest", String.class), + positive(row.get("expected_state_version", Long.class), "abort expected state version"), + positive(row.get("resulting_state_version", Long.class), "abort resulting state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + activeOptional( + row.get("durable_active_generation", Long.class), + row.get("durable_active_kid", String.class), + "aborted durable active signer"), + activeOptional( + row.get("published_active_generation", Long.class), + row.get("published_active_kid", String.class), + "aborted published active signer")); + } + + private void insertGenerationAbortReceipt(GenerationAbortReceipt receipt) { + int inserted = + dsl.execute( + "INSERT INTO " + + GENERATION_ABORT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "expected_state_version, resulting_state_version, expected_cluster_incarnation_uid, " + + "expected_namespace_uid, trust_binding_digest, trust_config_revision, " + + "durable_active_generation, durable_active_kid, published_active_generation, " + + "published_active_kid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.operationId(), + receipt.binding().environmentId(), + receipt.binding().clusterId(), + receipt.binding().namespace(), + receipt.binding().mode().value(), + receipt.operationDigest(), + receipt.generationRequestDigest(), + receipt.generationReceiptDigest(), + receipt.expectedStateVersion(), + receipt.resultingStateVersion(), + UUID.fromString(receipt.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(receipt.trustFence().expectedNamespaceUid()), + receipt.trustFence().bindingDigest(), + receipt.trustFence().configRevision(), + generationValue(receipt.durableActive()), + kidValue(receipt.durableActive()), + generationValue(receipt.publishedActive()), + kidValue(receipt.publishedActive())); + if (inserted != 1) { + throw new StorageUnavailableException( + "Account generation abort receipt insert was ambiguous"); + } + } + + private void insertGenerationOperation(StoredGenerationOperation operation) { + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, " + + "expected_published_generation, expected_published_kid, target_generation, target_kid, " + + "target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, " + + "trust_binding_digest, trust_config_revision, operation_action, " + + "allowed_private_slots_canonical_bytes) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'MATERIALIZE_PENDING', ?) ", + operation.operationId(), + operation.binding().environmentId(), + operation.binding().clusterId(), + operation.binding().namespace(), + operation.binding().mode().value(), + operation.operationDigest(), + operation.expectedRecordVersion(), + generationValue(operation.expectedPreviousActive()), + kidValue(operation.expectedPreviousActive()), + generationValue(operation.expectedPublishedActive()), + kidValue(operation.expectedPublishedActive()), + parseGeneration(operation.targetGeneration()), + operation.targetKid(), + operation.targetAlgorithm(), + UUID.fromString(operation.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(operation.trustFence().expectedNamespaceUid()), + operation.trustFence().bindingDigest(), + operation.trustFence().configRevision(), + PENDING_SLOT_CANONICAL_BYTES); + if (inserted != 1) { + throw new StorageUnavailableException( + "Account JWT generation operation insert was ambiguous"); + } + } + + private void requireCurrentPublicationForPreparation( + GenerationResult result, PromotionPreparation preparation) { + Record evidence = + dsl.fetchOne( + "SELECT intent.operation_id, intent.intent_digest, intent.environment_id, intent.cluster_id, " + + "intent.kubernetes_namespace, intent.custody_mode, intent.operation_digest, " + + "intent.generation_request_digest, intent.generation_receipt_digest, " + + "intent.desired_state_version, intent.expected_cluster_incarnation_uid, " + + "intent.expected_namespace_uid, intent.trust_binding_digest, " + + "intent.trust_config_revision, intent.api_binding_digest, intent.api_config_revision, " + + "intent.config_map_name, intent.config_map_uid, intent.jwks_json, " + + "receipt.receipt_digest, receipt.observed_resource_version, " + + "mount.observation_digest FROM account_jwt_jwks_prepublication_intents AS intent " + + "JOIN account_jwt_jwks_publication_receipts AS receipt " + + "ON receipt.operation_id = intent.operation_id " + + "AND receipt.intent_digest = intent.intent_digest " + + "JOIN account_jwt_jwks_mount_observations AS mount " + + "ON mount.operation_id = intent.operation_id " + + "WHERE intent.operation_id = ? FOR UPDATE OF intent, receipt, mount", + result.operationId()); + if (evidence == null + || !preparation + .prepublicationIntentDigest() + .equals(evidence.get("intent_digest", String.class)) + || !preparation + .prepublicationReceiptDigest() + .equals(evidence.get("receipt_digest", String.class)) + || !preparation + .mountedObservationDigest() + .equals(evidence.get("observation_digest", String.class)) + || !preparation + .publicConfigMapUid() + .equals(evidence.get("config_map_uid", UUID.class).toString()) + || !preparation + .expectedPublicResourceVersion() + .equals(evidence.get("observed_resource_version", String.class)) + || !preparation.apiBindingDigest().equals(evidence.get("api_binding_digest", String.class)) + || !preparation + .apiConfigRevision() + .equals(evidence.get("api_config_revision", String.class)) + || !preparation.expectedPublicJwksJson().equals(evidence.get("jwks_json", String.class)) + || !result.operationId().equals(evidence.get("operation_id", UUID.class)) + || !result.operationDigest().equals(evidence.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(evidence.get("generation_request_digest", String.class)) + || !result.receiptDigest().equals(evidence.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != evidence.get("desired_state_version", Long.class)) { + throw new PromotionPrerequisitesIncompleteException( + "Exact Account JWKS prepublication, API readback, or mount receipt is unavailable"); + } + } + + private void requireCurrentReadinessForPreparation( + GenerationResult result, PromotionPreparation preparation) { + Record plan = + dsl.fetchOne( + "SELECT plan_digest, operation_digest, generation_request_digest, " + + "generation_receipt_digest, desired_state_version, target_generation, target_kid, " + + "target_public_key_fingerprint, publication_intent_digest, " + + "publication_receipt_digest, mounted_observation_digest, " + + "validator_inventory_complete, expires_at_epoch_seconds " + + "FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = ? " + + "AND plan_digest = ? FOR UPDATE", + result.operationId(), + preparation.readinessPlanDigest()); + if (plan == null + || !Boolean.TRUE.equals(plan.get("validator_inventory_complete", Boolean.class)) + || plan.get("expires_at_epoch_seconds", Long.class) == null + || plan.get("expires_at_epoch_seconds", Long.class) == null + || !result.operationDigest().equals(plan.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(plan.get("generation_request_digest", String.class)) + || !result.receiptDigest().equals(plan.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != plan.get("desired_state_version", Long.class) + || !result + .targetGeneration() + .equals(String.valueOf(plan.get("target_generation", Long.class))) + || !result.targetKid().equals(plan.get("target_kid", String.class)) + || !result + .publicKeyFingerprint() + .equals(plan.get("target_public_key_fingerprint", String.class)) + || !preparation + .prepublicationIntentDigest() + .equals(plan.get("publication_intent_digest", String.class)) + || !preparation + .prepublicationReceiptDigest() + .equals(plan.get("publication_receipt_digest", String.class)) + || !preparation + .mountedObservationDigest() + .equals(plan.get("mounted_observation_digest", String.class))) { + throw new PromotionPrerequisitesIncompleteException( + "Complete current Account JWT readiness proof is unavailable"); + } + Record entries = + dsl.fetchOne( + "SELECT count(*) AS total, count(*) FILTER (WHERE state = 'VERIFIED' " + + "AND verification_receipt_sha256 IS NOT NULL " + + "AND verified_at_epoch_seconds < expires_at_epoch_seconds) AS verified " + + "FROM account_jwt_readiness_probe_entries WHERE rotation_operation_id = ? " + + "AND plan_digest = ? AND EXISTS (SELECT 1 FROM account_jwt_readiness_probe_plans " + + "WHERE rotation_operation_id = ? AND plan_digest = ? " + + "AND expires_at_epoch_seconds > floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT)", + result.operationId(), + preparation.readinessPlanDigest(), + result.operationId(), + preparation.readinessPlanDigest()); + if (entries == null + || entries.get("total", Long.class) == null + || entries.get("total", Long.class) <= 0 + || !entries.get("total", Long.class).equals(entries.get("verified", Long.class))) { + throw new PromotionPrerequisitesIncompleteException( + "Every exact current Account JWT validator probe must be VERIFIED"); + } + } + + /** Enforces readiness freshness at the last reversible boundary before private mutation. */ + private int requireFreshReadinessBeforeDispatch( + StoredPromotion promotion, GenerationResult result) { + int expectedProbeCount = frozenReadinessProbeCount(promotion); + Record currentPlan = + dsl.fetchOne( + "SELECT plan_digest, operation_digest, generation_request_digest, " + + "generation_receipt_digest, desired_state_version, target_generation, target_kid, " + + "target_public_key_fingerprint, publication_intent_digest, " + + "publication_receipt_digest, mounted_observation_digest, validator_inventory_complete, " + + "not_before_epoch_seconds, expires_at_epoch_seconds, " + + "floor(extract(epoch FROM clock_timestamp()))::bigint AS checked_epoch " + + "FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = ? " + + "AND plan_digest = ? FOR SHARE", + result.operationId(), + promotion.readinessPlanDigest()); + if (currentPlan == null + || !Boolean.TRUE.equals(currentPlan.get("validator_inventory_complete", Boolean.class)) + || !promotion.readinessPlanDigest().equals(currentPlan.get("plan_digest", String.class)) + || !result.operationDigest().equals(currentPlan.get("operation_digest", String.class)) + || !result + .generationRequestDigest() + .equals(currentPlan.get("generation_request_digest", String.class)) + || !result + .receiptDigest() + .equals(currentPlan.get("generation_receipt_digest", String.class)) + || result.desiredStateVersion() != currentPlan.get("desired_state_version", Long.class) + || !result + .targetGeneration() + .equals(String.valueOf(currentPlan.get("target_generation", Long.class))) + || !result.targetKid().equals(currentPlan.get("target_kid", String.class)) + || !result + .publicKeyFingerprint() + .equals(currentPlan.get("target_public_key_fingerprint", String.class)) + || !promotion + .prepublicationIntentDigest() + .equals(currentPlan.get("publication_intent_digest", String.class)) + || !promotion + .prepublicationReceiptDigest() + .equals(currentPlan.get("publication_receipt_digest", String.class)) + || !promotion + .mountedObservationDigest() + .equals(currentPlan.get("mounted_observation_digest", String.class)) + || currentPlan.get("checked_epoch", Long.class) == null + || currentPlan.get("checked_epoch", Long.class) + < currentPlan.get("not_before_epoch_seconds", Long.class) + || currentPlan.get("checked_epoch", Long.class) + >= currentPlan.get("expires_at_epoch_seconds", Long.class)) { + throw new PromotionPrerequisitesIncompleteException( + "Exact Account readiness proof is missing, changed, or expired before private dispatch"); + } + + Record currentEntries = + dsl.fetchOne( + "SELECT count(*) AS total, count(*) FILTER (WHERE state = 'VERIFIED' " + + "AND verification_receipt_sha256 IS NOT NULL " + + "AND verified_at_epoch_seconds < expires_at_epoch_seconds " + + "AND expires_at_epoch_seconds > floor(extract(epoch FROM clock_timestamp()))::bigint) " + + "AS verified FROM account_jwt_readiness_probe_entries " + + "WHERE rotation_operation_id = ? AND plan_digest = ?", + result.operationId(), + promotion.readinessPlanDigest()); + Long total = currentEntries == null ? null : currentEntries.get("total", Long.class); + Long verified = currentEntries == null ? null : currentEntries.get("verified", Long.class); + if (total == null + || verified == null + || total <= 0L + || total != expectedProbeCount + || !total.equals(verified)) { + throw new PromotionPrerequisitesIncompleteException( + "Every exact Account validator proof must remain VERIFIED and unexpired before private dispatch"); + } + return expectedProbeCount; + } + + private static int frozenReadinessProbeCount(StoredPromotion promotion) { + try { + JsonNode proof = STRICT_JSON.readTree(promotion.readinessEvidencePreimage()); + JsonNode probes = proof == null ? null : proof.get("verifiedProbes"); + if (proof == null + || !proof.isObject() + || probes == null + || !probes.isArray() + || probes.isEmpty() + || probes.size() > 32) { + throw new IllegalArgumentException("Frozen readiness probe set is malformed"); + } + return probes.size(); + } catch (Exception failure) { + throw new QuarantinedStateException( + "Frozen Account readiness proof cannot be read before private dispatch", failure); + } + } + + private void insertPromotion(StoredPromotion promotion) { + int inserted = + dsl.execute( + "INSERT INTO " + + PROMOTION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "request_digest_version, request_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, target_generation, target_kid, " + + "target_algorithm, target_public_key_fingerprint, " + + "expected_private_secret_resource_version, expected_public_jwks_resource_version, " + + "expected_public_active_generation, expected_public_active_kid, operation_action, " + + "allowed_private_slots_canonical_bytes, status, generation_operation_id, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, " + + "materializer_trust_binding_digest, materializer_trust_config_revision, " + + "api_binding_digest, api_config_revision, expected_private_secret_uid, " + + "expected_public_config_map_uid, prepublication_intent_digest, " + + "prepublication_receipt_digest, mounted_observation_digest, readiness_plan_digest, " + + "readiness_evidence_digest, readiness_evidence_preimage, expected_public_jwks_json, " + + "expected_active_generation_marker_json) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'RS256', ?, ?, ?, ?, ?, " + + "'PROMOTE_PENDING', ?, 'PREPARED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + promotion.operationId(), + promotion.binding().environmentId(), + promotion.binding().clusterId(), + promotion.binding().namespace(), + promotion.binding().mode().value(), + promotion.requestDigest(), + promotion.expectedRecordVersion(), + generationValue(promotion.expectedPreviousActive()), + kidValue(promotion.expectedPreviousActive()), + parseGeneration(promotion.targetGeneration()), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint(), + promotion.expectedPrivateResourceVersion(), + promotion.expectedPublicResourceVersion(), + generationValue(promotion.expectedPublishedActive()), + kidValue(promotion.expectedPublishedActive()), + PROMOTION_SLOTS_CANONICAL_BYTES, + promotion.generationOperationId(), + UUID.fromString(promotion.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(promotion.trustFence().expectedNamespaceUid()), + promotion.trustFence().bindingDigest(), + promotion.trustFence().configRevision(), + promotion.apiBindingDigest(), + promotion.apiConfigRevision(), + UUID.fromString(promotion.secretUid()), + UUID.fromString(promotion.publicConfigMapUid()), + promotion.prepublicationIntentDigest(), + promotion.prepublicationReceiptDigest(), + promotion.mountedObservationDigest(), + promotion.readinessPlanDigest(), + promotion.readinessEvidenceDigest(), + promotion.readinessEvidencePreimage().getBytes(StandardCharsets.UTF_8), + promotion.expectedPublicJwksJson(), + promotion.expectedActiveMarkerJson()); + if (inserted != 1) { + throw new StorageUnavailableException("Account promotion operation insert was ambiguous"); + } + } + + private int advanceToPrepared(DesiredState state, UUID promotionOperationId) { + return dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, generation_operation_id = NULL, " + + "prepared_operation_id = ?, updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? " + + "AND cluster_id = ? AND kubernetes_namespace = ? AND custody_mode = ? " + + "AND record_version = ? AND generation_operation_id = ? AND prepared_operation_id IS NULL " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ?", + promotionOperationId, + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + state.generationOperationId().orElseThrow(), + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + } + + private int advanceToGenerationRequest(DesiredState state, UUID operationId) { + return dsl.execute( + "UPDATE " + + STATE_TABLE + + " SET record_version = record_version + 1, generation_operation_id = ?, " + + "updated_at = CURRENT_TIMESTAMP WHERE environment_id = ? AND cluster_id = ? " + + "AND kubernetes_namespace = ? AND custody_mode = ? " + + "AND private_secret_name = 'jwt-signing-keys' " + + "AND public_jwks_config_map_name = 'jwt-jwks' AND record_version = ? " + + "AND durable_active_generation IS NOT DISTINCT FROM ? " + + "AND durable_active_kid IS NOT DISTINCT FROM ? " + + "AND published_active_generation IS NOT DISTINCT FROM ? " + + "AND published_active_kid IS NOT DISTINCT FROM ? " + + "AND generation_operation_id IS NULL AND prepared_operation_id IS NULL", + operationId, + state.binding().environmentId(), + state.binding().clusterId(), + state.binding().namespace(), + state.binding().mode().value(), + state.recordVersion(), + generationValue(state.durableActive()), + kidValue(state.durableActive()), + generationValue(state.publishedActive()), + kidValue(state.publishedActive())); + } + + private void insertSecretObservation(SecretObservation observation) { + int inserted = + dsl.execute( + "INSERT INTO " + + OBSERVATION_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest_version, operation_digest, expected_record_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, observed_resource_version, " + + "observation_digest_version, observation_digest, generation_request_digest) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, 'jwt-signing-keys', ?, ?, 1, ?, ?)", + observation.operationId(), + observation.binding().environmentId(), + observation.binding().clusterId(), + observation.binding().namespace(), + observation.binding().mode().value(), + observation.operationDigest(), + observation.expectedRecordVersion(), + UUID.fromString(observation.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(observation.trustFence().expectedNamespaceUid()), + observation.trustFence().bindingDigest(), + observation.trustFence().configRevision(), + UUID.fromString(observation.secretUid()), + observation.observedResourceVersion(), + observation.observationDigest(), + observation.generationRequestDigest()); + if (inserted != 1) { + throw new StorageUnavailableException("Account JWT Secret observation insert was ambiguous"); + } + } + + private void insertGenerationResult(GenerationResult result) { + int inserted = + dsl.execute( + "INSERT INTO " + + RESULT_TABLE + + " (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, desired_state_version, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, trust_binding_digest, " + + "trust_config_revision, private_secret_name, secret_uid, " + + "expected_prior_resource_version, observed_resource_version, target_generation, " + + "target_kid, target_algorithm, public_key_fingerprint, public_jwk_json, receipt_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'jwt-signing-keys', ?, ?, ?, ?, ?, 'RS256', ?, ?, ?)", + result.operationId(), + result.binding().environmentId(), + result.binding().clusterId(), + result.binding().namespace(), + result.binding().mode().value(), + result.operationDigest(), + result.generationRequestDigest(), + result.desiredStateVersion(), + UUID.fromString(result.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(result.trustFence().expectedNamespaceUid()), + result.trustFence().bindingDigest(), + result.trustFence().configRevision(), + UUID.fromString(result.secretUid()), + result.expectedPriorResourceVersion(), + result.observedResourceVersion(), + parseGeneration(result.targetGeneration()), + result.targetKid(), + result.publicKeyFingerprint(), + result.publicJwkJson(), + result.receiptDigest()); + if (inserted != 1) { + throw new StorageUnavailableException("Account JWT generation result insert was ambiguous"); + } + } + + private DesiredState decodeState(Record row) { + try { + if (!PRIVATE_SECRET_NAME.equals(row.get("private_secret_name", String.class)) + || !PUBLIC_JWKS_CONFIG_MAP_NAME.equals( + row.get("public_jwks_config_map_name", String.class))) { + throw new QuarantinedStateException("Account JWT signer resource binding is malformed"); + } + return new DesiredState( + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + positive(row.get("record_version", Long.class), "Account JWT signer record version"), + activeOptional( + row.get("durable_active_generation", Long.class), + row.get("durable_active_kid", String.class), + "durable active signer"), + activeOptional( + row.get("published_active_generation", Long.class), + row.get("published_active_kid", String.class), + "published active signer"), + Optional.ofNullable(row.get("generation_operation_id", UUID.class)), + Optional.ofNullable(row.get("prepared_operation_id", UUID.class)), + enrollmentIdentity(row)); + } catch (RuntimeException ex) { + throw new QuarantinedStateException("Account JWT signer desired state is malformed", ex); + } + } + + private static Optional enrollmentIdentity(Record row) { + UUID clusterUid = row.get("enrollment_cluster_incarnation_uid", UUID.class); + UUID namespaceUid = row.get("enrollment_namespace_uid", UUID.class); + String materializerDigest = row.get("enrollment_materializer_binding_digest", String.class); + String materializerRevision = row.get("enrollment_materializer_config_revision", String.class); + String apiDigest = row.get("enrollment_api_binding_digest", String.class); + String apiRevision = row.get("enrollment_api_config_revision", String.class); + UUID configMapUid = row.get("enrollment_public_config_map_uid", UUID.class); + String resourceVersion = row.get("enrollment_public_config_map_resource_version", String.class); + String snapshotDigest = row.get("enrollment_public_config_map_snapshot_digest", String.class); + boolean allAbsent = + clusterUid == null + && namespaceUid == null + && materializerDigest == null + && materializerRevision == null + && apiDigest == null + && apiRevision == null + && configMapUid == null + && resourceVersion == null + && snapshotDigest == null; + if (allAbsent) { + return Optional.empty(); + } + if (clusterUid == null + || namespaceUid == null + || materializerDigest == null + || materializerRevision == null + || apiDigest == null + || apiRevision == null + || configMapUid == null + || resourceVersion == null + || snapshotDigest == null) { + throw new QuarantinedStateException("Account JWT signer enrollment pins are partial"); + } + return Optional.of( + new EnrollmentIdentity( + clusterUid.toString(), + namespaceUid.toString(), + materializerDigest, + materializerRevision, + apiDigest, + apiRevision, + configMapUid.toString(), + resourceVersion, + snapshotDigest)); + } + + private StoredGenerationOperation decodeGenerationOperation(Record row) { + try { + String slotBytes = + new String( + row.get("allowed_private_slots_canonical_bytes", byte[].class), + StandardCharsets.UTF_8); + if (!"[\"pending\"]".equals(slotBytes)) { + throw new QuarantinedStateException("JWT signer operation private slots are malformed"); + } + Integer digestVersion = row.get("operation_digest_version", Integer.class); + StoredGenerationOperation operation = + new StoredGenerationOperation( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + digestVersion != null && digestVersion == 1 ? REQUEST_DIGEST_VERSION : "unsupported", + row.get("operation_digest", String.class), + positive(row.get("expected_record_version", Long.class), "expected state version"), + activeOptional( + row.get("expected_previous_generation", Long.class), + row.get("expected_previous_kid", String.class), + "expected active signer"), + activeOptional( + row.get("expected_published_generation", Long.class), + row.get("expected_published_kid", String.class), + "expected published signer"), + canonicalGeneration(row.get("target_generation", Long.class), "target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class))); + if (!ACTION.equals(row.get("operation_action", String.class))) { + throw new QuarantinedStateException("JWT signer operation action is unsupported"); + } + if (!generationOperationDigest(operation).equals(operation.operationDigest())) { + throw new QuarantinedStateException("JWT signer operation digest is invalid"); + } + return operation; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException( + "Account JWT signer generation operation is malformed", ex); + } + } + + private SecretObservation decodeSecretObservation(Record row) { + try { + SecretObservation observation = + new SecretObservation( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + row.get("operation_digest", String.class), + positive(row.get("expected_record_version", Long.class), "expected state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("private_secret_name", String.class), + row.get("secret_uid", UUID.class).toString(), + row.get("observed_resource_version", String.class), + row.get("observation_digest", String.class), + row.get("generation_request_digest", String.class)); + if (!observationDigest( + observation.operationDigest(), + observation.trustFence(), + observation.secretUid(), + observation.observedResourceVersion()) + .equals(observation.observationDigest()) + || !generationRequestDigest(observation).equals(observation.generationRequestDigest())) { + throw new QuarantinedStateException("JWT signer Secret observation digest is invalid"); + } + return observation; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account JWT Secret observation is malformed", ex); + } + } + + private GenerationResult decodeGenerationResult(Record row) { + try { + GenerationResult result = + new GenerationResult( + row.get("operation_id", UUID.class), + new Binding( + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("kubernetes_namespace", String.class), + CustodyMode.fromValue(row.get("custody_mode", String.class))), + row.get("operation_digest", String.class), + row.get("generation_request_digest", String.class), + positive(row.get("desired_state_version", Long.class), "desired state version"), + new TrustFence( + row.get("expected_cluster_incarnation_uid", UUID.class).toString(), + row.get("expected_namespace_uid", UUID.class).toString(), + row.get("trust_binding_digest", String.class), + row.get("trust_config_revision", String.class)), + row.get("private_secret_name", String.class), + row.get("secret_uid", UUID.class).toString(), + row.get("expected_prior_resource_version", String.class), + row.get("observed_resource_version", String.class), + canonicalGeneration(row.get("target_generation", Long.class), "target generation"), + row.get("target_kid", String.class), + row.get("target_algorithm", String.class), + row.get("public_key_fingerprint", String.class), + row.get("public_jwk_json", String.class), + row.get("receipt_digest", String.class)); + PublicJwk jwk = parsePublicJwk(result.publicJwkJson()); + if (!jwk.kid().equals(result.targetKid()) + || !jwk.fingerprint().equals(result.publicKeyFingerprint()) + || !generationReceiptDigest(result).equals(result.receiptDigest())) { + throw new QuarantinedStateException("JWT signer generation receipt digest is invalid"); + } + return result; + } catch (RuntimeException ex) { + if (ex instanceof QuarantinedStateException) { + throw ex; + } + throw new QuarantinedStateException("Account JWT generation result is malformed", ex); + } + } + + private static void verifyPreparedIsUnavailable(DesiredState state) { + if (state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Existing PREPARED signer state requires unavailable lifecycle evidence"); + } + } + + private static void requireBinding(DesiredState state, Binding expected) { + if (!state.binding().equals(expected)) { + throw new BindingMismatchException( + "Account JWT signer environment, cluster, namespace, or custody binding changed"); + } + } + + private static String generationOperationDigest(StoredGenerationOperation operation) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", REQUEST_DIGEST_VERSION); + preimage.put("environmentId", operation.binding().environmentId()); + preimage.put("clusterId", operation.binding().clusterId()); + preimage.put("namespace", operation.binding().namespace()); + preimage.put("custodyMode", operation.binding().mode().value()); + preimage.put("privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("operationId", operation.operationId().toString()); + preimage.put("expectedRecordVersion", Long.toString(operation.expectedRecordVersion())); + preimage.put("expectedPreviousActive", activeDigestValue(operation.expectedPreviousActive())); + preimage.put("expectedPublishedActive", activeDigestValue(operation.expectedPublishedActive())); + preimage.put("targetGeneration", operation.targetGeneration()); + preimage.put("targetKid", operation.targetKid()); + preimage.put("targetAlgorithm", operation.targetAlgorithm()); + preimage.put("operationAction", ACTION); + preimage.put("allowedPrivateSlots", List.of(PENDING_SLOT)); + preimage.put( + "expectedClusterIncarnationUid", operation.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", operation.trustFence().expectedNamespaceUid()); + preimage.put("trustBindingDigest", operation.trustFence().bindingDigest()); + preimage.put("trustConfigRevision", operation.trustFence().configRevision()); + return digest(preimage); + } + + private static String observationDigest( + String operationDigest, TrustFence trust, String secretUid, String resourceVersion) { + return digest( + Map.of( + "digestVersion", OBSERVATION_DIGEST_VERSION, + "operationDigest", operationDigest, + "privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME), + "expectedClusterIncarnationUid", trust.expectedClusterIncarnationUid(), + "expectedNamespaceUid", trust.expectedNamespaceUid(), + "trustBindingDigest", trust.bindingDigest(), + "trustConfigRevision", trust.configRevision(), + "secretUid", secretUid, + "observedResourceVersion", resourceVersion)); + } + + private static String generationRequestDigest(SecretObservation observation) { + return digest( + Map.of( + "digestVersion", GENERATION_REQUEST_DIGEST_VERSION, + "operationDigest", observation.operationDigest(), + "observationDigest", observation.observationDigest(), + "secretUid", observation.secretUid(), + "expectedPriorResourceVersion", observation.observedResourceVersion(), + "target", "pending")); + } + + private static String generationReceiptDigest(GenerationResult result) { + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", RECEIPT_DIGEST_VERSION); + preimage.put("operationId", result.operationId().toString()); + preimage.put("operationDigest", result.operationDigest()); + preimage.put("generationRequestDigest", result.generationRequestDigest()); + preimage.put("desiredStateVersion", Long.toString(result.desiredStateVersion())); + preimage.put("environmentId", result.binding().environmentId()); + preimage.put("clusterId", result.binding().clusterId()); + preimage.put("namespace", result.binding().namespace()); + preimage.put( + "expectedClusterIncarnationUid", result.trustFence().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", result.trustFence().expectedNamespaceUid()); + preimage.put("trustBindingDigest", result.trustFence().bindingDigest()); + preimage.put("trustConfigRevision", result.trustFence().configRevision()); + preimage.put("privateResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("secretUid", result.secretUid()); + preimage.put("expectedPriorResourceVersion", result.expectedPriorResourceVersion()); + preimage.put("observedResourceVersion", result.observedResourceVersion()); + preimage.put("targetGeneration", result.targetGeneration()); + preimage.put("targetKid", result.targetKid()); + preimage.put("targetAlgorithm", result.targetAlgorithm()); + preimage.put("publicKeyFingerprint", result.publicKeyFingerprint()); + preimage.put("publicJwk", result.publicJwkJson()); + return digest(preimage); + } + + private static String digest(Object value) { + try { + byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } catch (IOException | NoSuchAlgorithmException ex) { + throw new IllegalStateException("Account JWT signer evidence digest is unavailable", ex); + } + } + + private static String sha256(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable for JWT promotion evidence", ex); + } + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable for JWT promotion evidence", ex); + } + } + + private static String readinessPreimageText(byte[] value, String expectedDigest) { + if (value == null + || value.length == 0 + || value.length > 1024 * 1024 + || expectedDigest == null + || !expectedDigest.equals(sha256(value))) { + throw new QuarantinedStateException( + "Persisted readiness proof preimage does not match its exact digest"); + } + String text = new String(value, StandardCharsets.UTF_8); + if (!Arrays.equals(value, text.getBytes(StandardCharsets.UTF_8))) { + throw new QuarantinedStateException("Persisted readiness proof preimage is not valid UTF-8"); + } + return text; + } + + private static Object activeDigestValue(Optional active) { + if (active.isEmpty()) { + return Map.of("present", false); + } + ActiveSigner value = active.orElseThrow(); + return Map.of("present", true, "generation", value.generation(), "kid", value.kid()); + } + + private static PublicJwk parsePublicJwk(String json) { + if (json == null || json.isEmpty() || json.getBytes(StandardCharsets.UTF_8).length > 8_192) { + throw new IllegalArgumentException("JWT signer public JWK is missing or too large"); + } + try { + JsonNode node = STRICT_JSON.readTree(json); + if (node == null || !node.isObject() || node.size() != PUBLIC_JWK_FIELDS.size()) { + throw new IllegalArgumentException("JWT signer public JWK has an unsupported shape"); + } + for (Map.Entry property : node.properties()) { + if (!PUBLIC_JWK_FIELDS.contains(property.getKey())) { + throw new IllegalArgumentException("JWT signer public JWK has an unsupported field"); + } + } + String canonicalJson = + new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8); + if (!canonicalJson.equals(json)) { + throw new IllegalArgumentException("JWT signer public JWK must be canonical RFC 8785 JSON"); + } + String kty = requiredText(node, "kty", 8); + String use = requiredText(node, "use", 8); + String algorithm = requiredText(node, "alg", 8); + String kid = requiredText(node, "kid", 64); + String modulus = requiredText(node, "n", 4_096); + String exponent = requiredText(node, "e", 16); + JsonNode keyOps = node.get("key_ops"); + if (!"RSA".equals(kty) + || !"sig".equals(use) + || !ALGORITHM.equals(algorithm) + || !KID.matcher(kid).matches() + || keyOps == null + || !keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw new IllegalArgumentException("JWT signer public JWK does not meet RS256 policy"); + } + byte[] modulusBytes = decodeCanonicalBase64Url(modulus, 2_048); + byte[] exponentBytes = decodeCanonicalBase64Url(exponent, 8); + try { + if (modulusBytes.length == 0 + || modulusBytes[0] == 0 + || exponentBytes.length == 0 + || exponentBytes[0] == 0) { + throw new IllegalArgumentException("JWT signer RSA public numbers are malformed"); + } + BigInteger modulusInteger = new BigInteger(1, modulusBytes); + BigInteger exponentInteger = new BigInteger(1, exponentBytes); + if (modulusInteger.bitLength() < 3_072 + || modulusInteger.bitLength() > 16_384 + || !modulusInteger.testBit(0) + || !BigInteger.valueOf(65_537).equals(exponentInteger)) { + throw new IllegalArgumentException("JWT signer RSA public key is outside policy"); + } + } finally { + java.util.Arrays.fill(modulusBytes, (byte) 0); + java.util.Arrays.fill(exponentBytes, (byte) 0); + } + String fingerprint = + digest( + Map.of( + "e", exponent, + "kty", "RSA", + "n", modulus)); + return new PublicJwk(kid, canonicalJson, fingerprint); + } catch (IllegalArgumentException ex) { + throw ex; + } catch (Exception ex) { + throw new IllegalArgumentException("JWT signer public JWK is malformed", ex); + } + } + + private static byte[] decodeCanonicalBase64Url(String encoded, int maxBytes) { + final byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(encoded); + } catch (IllegalArgumentException ex) { + throw new IllegalArgumentException("JWT signer RSA public number is malformed", ex); + } + byte[] canonical = Base64.getUrlEncoder().withoutPadding().encode(decoded); + boolean matches = canonical.length == encoded.length(); + for (int index = 0; matches && index < canonical.length; index++) { + matches = (char) Byte.toUnsignedInt(canonical[index]) == encoded.charAt(index); + } + java.util.Arrays.fill(canonical, (byte) 0); + if (decoded.length == 0 || decoded.length > maxBytes || !matches) { + java.util.Arrays.fill(decoded, (byte) 0); + throw new IllegalArgumentException("JWT signer RSA public number is not canonical"); + } + return decoded; + } + + private static ActiveSigner active(Long generation, String kid, String field) { + if (generation == null && kid == null) { + return null; + } + if (generation == null || kid == null) { + throw new QuarantinedStateException(field + " has an incomplete generation/kid pair"); + } + return new ActiveSigner(Long.toString(positive(generation, field + " generation")), kid); + } + + private static Optional activeOptional(Long generation, String kid, String field) { + return Optional.ofNullable(active(generation, kid, field)); + } + + private static Long generationValue(Optional active) { + return active.map(value -> parseGeneration(value.generation())).orElse(null); + } + + private static String kidValue(Optional active) { + return active.map(ActiveSigner::kid).orElse(null); + } + + private static String canonicalGeneration(Long value, String field) { + return Long.toString(positive(value, field)); + } + + private static long positive(Long value, String field) { + if (value == null || value <= 0) { + throw new QuarantinedStateException(field + " must be positive"); + } + return value; + } + + private static long parseGeneration(String value) { + if (value == null || !POSITIVE_DECIMAL.matcher(value).matches()) { + throw new IllegalArgumentException("Signer generation must be canonical positive decimal"); + } + try { + return Long.parseLong(value); + } catch (NumberFormatException ex) { + throw new IllegalArgumentException("Signer generation is outside its supported range", ex); + } + } + + private static void requireOperationId(UUID operationId) { + Objects.requireNonNull(operationId, "Account JWT signer operation ID is required"); + if (operationId.version() != 4) { + throw new IllegalArgumentException("Account JWT signer operation ID must be UUIDv4"); + } + } + + private static void requireUuid(String value, String field) { + if (value == null) { + throw new IllegalArgumentException("JWT signer " + field + " is missing"); + } + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } catch (RuntimeException ex) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed", ex); + } + } + + private static void requireMatch(Pattern pattern, String value, String field) { + if (value == null || !pattern.matcher(value).matches()) { + throw new IllegalArgumentException("JWT signer " + field + " is malformed"); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("Account transaction is required for JWT signer state"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Writable Account transaction is required for JWT signer state"); + } + } + + public enum CustodyMode { + INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK(MODE); + + private final String value; + + CustodyMode(String value) { + this.value = value; + } + + public String value() { + return value; + } + + private static CustodyMode fromValue(String value) { + for (CustodyMode candidate : values()) { + if (candidate.value.equals(value)) { + return candidate; + } + } + throw new QuarantinedStateException("JWT signer custody mode is unsupported"); + } + } + + public enum GenerationPhase { + OBSERVE_PRIVATE_SECRET, + GENERATE_PENDING, + GENERATION_RECORDED + } + + public record Binding( + String environmentId, String clusterId, String namespace, CustodyMode mode) { + public Binding { + requireMatch(ENVIRONMENT_ID, environmentId, "environment ID"); + requireMatch(CLUSTER_ID, clusterId, "cluster ID"); + requireMatch(ENVIRONMENT_ID, namespace, "Kubernetes namespace"); + Objects.requireNonNull(mode, "JWT signer custody mode is required"); + } + } + + /** Independently protected trust identity captured by every immutable operation and receipt. */ + public record TrustFence( + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String bindingDigest, + String configRevision) { + public TrustFence { + requireUuid(expectedClusterIncarnationUid, "expected cluster incarnation UID"); + requireUuid(expectedNamespaceUid, "expected namespace UID"); + requireMatch(SHA256_HEX, bindingDigest, "materializer trust binding digest"); + requireMatch(CLUSTER_ID, configRevision, "materializer trust configuration revision"); + } + } + + /** + * Immutable independently protected trust and first ConfigMap observation used for enrollment. + */ + public record EnrollmentIdentity( + String expectedClusterIncarnationUid, + String expectedNamespaceUid, + String materializerTrustBindingDigest, + String materializerTrustConfigRevision, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String publicConfigMapResourceVersion, + String publicConfigMapSnapshotDigest) { + public EnrollmentIdentity { + requireUuid(expectedClusterIncarnationUid, "enrollment cluster incarnation UID"); + requireUuid(expectedNamespaceUid, "enrollment namespace UID"); + requireMatch(SHA256_HEX, materializerTrustBindingDigest, "materializer trust digest"); + requireMatch(CLUSTER_ID, materializerTrustConfigRevision, "materializer trust revision"); + requireMatch(SHA256_HEX, apiBindingDigest, "public JWKS API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "public JWKS API configuration revision"); + requireUuid(publicConfigMapUid, "pre-created public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, publicConfigMapResourceVersion, "initial ConfigMap resourceVersion"); + requireMatch(SHA256_HEX, publicConfigMapSnapshotDigest, "initial ConfigMap snapshot digest"); + } + + /** Stable pin equality deliberately excludes the historical first ConfigMap RV/data digest. */ + public boolean sameStablePins(EnrollmentIdentity other) { + Objects.requireNonNull(other, "Enrollment identity is required"); + return expectedClusterIncarnationUid.equals(other.expectedClusterIncarnationUid) + && expectedNamespaceUid.equals(other.expectedNamespaceUid) + && materializerTrustBindingDigest.equals(other.materializerTrustBindingDigest) + && materializerTrustConfigRevision.equals(other.materializerTrustConfigRevision) + && apiBindingDigest.equals(other.apiBindingDigest) + && apiConfigRevision.equals(other.apiConfigRevision) + && publicConfigMapUid.equals(other.publicConfigMapUid); + } + } + + public record ActiveSigner(String generation, String kid) { + public ActiveSigner { + parseGeneration(generation); + requireMatch(KID, kid, "active signer kid"); + } + } + + public record DesiredState( + Binding binding, + long recordVersion, + Optional durableActive, + Optional publishedActive, + Optional generationOperationId, + Optional preparedOperationId, + Optional enrollmentIdentity) { + public DesiredState { + Objects.requireNonNull(binding, "JWT signer binding is required"); + if (recordVersion <= 0) { + throw new IllegalArgumentException("JWT signer record version must be positive"); + } + durableActive = Objects.requireNonNull(durableActive, "Durable active signer is required"); + publishedActive = + Objects.requireNonNull(publishedActive, "Published active signer is required"); + generationOperationId = + Objects.requireNonNull(generationOperationId, "Generation operation state is required"); + preparedOperationId = + Objects.requireNonNull(preparedOperationId, "Prepared operation state is required"); + enrollmentIdentity = + Objects.requireNonNull(enrollmentIdentity, "Enrollment identity state is required"); + if (generationOperationId.isPresent() && preparedOperationId.isPresent()) { + throw new IllegalArgumentException("Generation and PREPARED pointers cannot coexist"); + } + } + } + + public record GenerationRequest( + GenerationPhase phase, + UUID operationId, + String operationDigest, + String generationRequestDigest, + long desiredStateVersion, + Binding binding, + TrustFence trustFence, + String privateSecretName, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String operationAction, + List allowedPrivateSlots, + Optional expectedActive, + Optional expectedPublishedActive, + String secretUid, + String expectedSecretResourceVersion, + String generationReceiptDigest, + String publicKeyFingerprint, + String publicJwkJson, + String observedSecretResourceVersion) { + public GenerationRequest { + Objects.requireNonNull(phase, "Generation phase is required"); + requireOperationId(operationId); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + if (phase != GenerationPhase.OBSERVE_PRIVATE_SECRET) { + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } else if (generationRequestDigest != null && !generationRequestDigest.isEmpty()) { + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } + if (desiredStateVersion <= 1) { + throw new QuarantinedStateException("JWT generation request state version is invalid"); + } + Objects.requireNonNull(binding, "Generation request binding is required"); + Objects.requireNonNull(trustFence, "Generation request trust fence is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName) + || !ALGORITHM.equals(targetAlgorithm) + || !ACTION.equals(operationAction) + || !List.of(PENDING_SLOT).equals(allowedPrivateSlots)) { + throw new QuarantinedStateException("JWT generation request fixed operation is malformed"); + } + allowedPrivateSlots = List.copyOf(allowedPrivateSlots); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + expectedActive = Objects.requireNonNull(expectedActive, "Expected active signer is required"); + expectedPublishedActive = + Objects.requireNonNull(expectedPublishedActive, "Expected published signer is required"); + secretUid = secretUid == null ? "" : secretUid; + expectedSecretResourceVersion = + expectedSecretResourceVersion == null ? "" : expectedSecretResourceVersion; + generationReceiptDigest = generationReceiptDigest == null ? "" : generationReceiptDigest; + publicKeyFingerprint = publicKeyFingerprint == null ? "" : publicKeyFingerprint; + publicJwkJson = publicJwkJson == null ? "" : publicJwkJson; + observedSecretResourceVersion = + observedSecretResourceVersion == null ? "" : observedSecretResourceVersion; + if (phase != GenerationPhase.OBSERVE_PRIVATE_SECRET) { + requireUuid(secretUid, "observed fixed Secret UID"); + requireMatch( + RESOURCE_VERSION, expectedSecretResourceVersion, "observed Secret resourceVersion"); + } + if (phase == GenerationPhase.GENERATION_RECORDED) { + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + requireMatch(SHA256_HEX, publicKeyFingerprint, "RFC 7638 public-key fingerprint"); + parsePublicJwk(publicJwkJson); + requireMatch( + RESOURCE_VERSION, observedSecretResourceVersion, "result Secret resourceVersion"); + } else if (!generationReceiptDigest.isEmpty() + || !publicKeyFingerprint.isEmpty() + || !publicJwkJson.isEmpty() + || !observedSecretResourceVersion.isEmpty()) { + throw new QuarantinedStateException( + "Incomplete JWT generation request contains result evidence"); + } + } + } + + public record GenerationResult( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + long desiredStateVersion, + TrustFence trustFence, + String privateSecretName, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String publicKeyFingerprint, + String publicJwkJson, + String receiptDigest) { + public GenerationResult { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Generation result binding is required"); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + if (desiredStateVersion <= 1) { + throw new QuarantinedStateException("JWT generation result state version is invalid"); + } + Objects.requireNonNull(trustFence, "Generation result trust fence is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName)) { + throw new IllegalArgumentException("JWT generation result must name the fixed Secret"); + } + requireUuid(secretUid, "generation result Secret UID"); + requireMatch( + RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret resourceVersion"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + if (expectedPriorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException("JWT signer Secret resourceVersion did not advance"); + } + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new IllegalArgumentException("Only RS256 JWT signer results are supported"); + } + requireMatch(SHA256_HEX, publicKeyFingerprint, "RFC 7638 public-key fingerprint"); + requireMatch(SHA256_HEX, receiptDigest, "generation receipt digest"); + PublicJwk jwk = parsePublicJwk(publicJwkJson); + if (!jwk.kid().equals(targetKid) || !jwk.fingerprint().equals(publicKeyFingerprint)) { + throw new QuarantinedStateException( + "JWT generation result public key does not match receipt"); + } + } + + private static GenerationResult from( + StoredGenerationOperation operation, + long desiredStateVersion, + SecretObservation observation, + String observedResourceVersion, + PublicJwk jwk) { + GenerationResult candidate = + new GenerationResult( + operation.operationId(), + operation.binding(), + operation.operationDigest(), + observation.generationRequestDigest(), + desiredStateVersion, + operation.trustFence(), + PRIVATE_SECRET_NAME, + observation.secretUid(), + observation.observedResourceVersion(), + observedResourceVersion, + operation.targetGeneration(), + operation.targetKid(), + operation.targetAlgorithm(), + jwk.fingerprint(), + jwk.canonicalJson(), + "0".repeat(64)); + return new GenerationResult( + candidate.operationId(), + candidate.binding(), + candidate.operationDigest(), + candidate.generationRequestDigest(), + candidate.desiredStateVersion(), + candidate.trustFence(), + candidate.privateSecretName(), + candidate.secretUid(), + candidate.expectedPriorResourceVersion(), + candidate.observedResourceVersion(), + candidate.targetGeneration(), + candidate.targetKid(), + candidate.targetAlgorithm(), + candidate.publicKeyFingerprint(), + candidate.publicJwkJson(), + generationReceiptDigest(candidate)); + } + } + + private record StoredGenerationOperation( + UUID operationId, + Binding binding, + String digestVersion, + String operationDigest, + long expectedRecordVersion, + Optional expectedPreviousActive, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + TrustFence trustFence) { + private StoredGenerationOperation { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Generation operation binding is required"); + requireMatch(SHA256_HEX, operationDigest, "generation operation digest"); + if (expectedRecordVersion <= 0 || expectedRecordVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException("Generation operation state version is invalid"); + } + expectedPreviousActive = + Objects.requireNonNull(expectedPreviousActive, "Expected active signer is required"); + expectedPublishedActive = + Objects.requireNonNull(expectedPublishedActive, "Expected published signer is required"); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new IllegalArgumentException("Only RS256 generation operations are supported"); + } + Objects.requireNonNull(trustFence, "Generation operation trust is required"); + } + + private static StoredGenerationOperation create( + DesiredState state, + TrustFence trust, + UUID operationId, + long targetGeneration, + String targetKid) { + StoredGenerationOperation unsigned = + new StoredGenerationOperation( + operationId, + state.binding(), + REQUEST_DIGEST_VERSION, + "0".repeat(64), + state.recordVersion(), + state.durableActive(), + state.publishedActive(), + Long.toString(targetGeneration), + targetKid, + ALGORITHM, + trust); + return new StoredGenerationOperation( + unsigned.operationId(), + unsigned.binding(), + unsigned.digestVersion(), + generationOperationDigest(unsigned), + unsigned.expectedRecordVersion(), + unsigned.expectedPreviousActive(), + unsigned.expectedPublishedActive(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.targetAlgorithm(), + unsigned.trustFence()); + } + } + + private record SecretObservation( + UUID operationId, + Binding binding, + String operationDigest, + long expectedRecordVersion, + TrustFence trustFence, + String privateSecretName, + String secretUid, + String observedResourceVersion, + String observationDigest, + String generationRequestDigest) { + private SecretObservation { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Secret observation binding is required"); + if (expectedRecordVersion <= 0 || expectedRecordVersion == Long.MAX_VALUE) { + throw new IllegalArgumentException("Secret observation state version is invalid"); + } + requireMatch(SHA256_HEX, operationDigest, "operation digest"); + Objects.requireNonNull(trustFence, "Secret observation trust is required"); + if (!PRIVATE_SECRET_NAME.equals(privateSecretName)) { + throw new IllegalArgumentException("Secret observation must name the fixed Secret"); + } + requireUuid(secretUid, "observed Secret UID"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret resourceVersion"); + requireMatch(SHA256_HEX, observationDigest, "Secret observation digest"); + requireMatch(SHA256_HEX, generationRequestDigest, "generation request digest"); + } + + private static SecretObservation from( + StoredGenerationOperation operation, String secretUid, String resourceVersion) { + String observationDigest = + AccountJwtSignerDesiredStateRepository.observationDigest( + operation.operationDigest(), operation.trustFence(), secretUid, resourceVersion); + String generationRequestDigest = + AccountJwtSignerDesiredStateRepository.generationRequestDigest( + operation.operationDigest(), observationDigest, secretUid, resourceVersion); + return new SecretObservation( + operation.operationId(), + operation.binding(), + operation.operationDigest(), + operation.expectedRecordVersion(), + operation.trustFence(), + PRIVATE_SECRET_NAME, + secretUid, + resourceVersion, + observationDigest, + generationRequestDigest); + } + } + + private record PublicJwk(String kid, String canonicalJson, String fingerprint) {} + + private record LockedCurrent(DesiredState state, StoredGenerationOperation operation) {} + + private record StoredPromotion( + UUID operationId, + Binding binding, + int requestDigestVersion, + String requestDigest, + long expectedRecordVersion, + Optional expectedPreviousActive, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String targetPublicKeyFingerprint, + String expectedPrivateResourceVersion, + String expectedPublicResourceVersion, + TrustFence trustFence, + UUID generationOperationId, + String generationOperationDigest, + String generationReceiptDigest, + String apiBindingDigest, + String apiConfigRevision, + String secretUid, + String publicConfigMapUid, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String readinessEvidencePreimage, + String expectedPublicJwksJson, + String expectedActiveMarkerJson, + String status, + boolean privatePromotionDispatched, + String privatePromotionObservedResourceVersion, + String privatePromotionReceiptDigest, + String activeJwksObservedResourceVersion, + String activeJwksPublicDataDigest, + String activeJwksReceiptDigest) { + private StoredPromotion { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Promotion binding is required"); + if (requestDigestVersion != 1 + || expectedRecordVersion <= 0L + || expectedRecordVersion == Long.MAX_VALUE) { + throw new QuarantinedStateException("Promotion version fence is malformed"); + } + requireMatch(SHA256_HEX, requestDigest, "promotion request digest"); + expectedPreviousActive = Objects.requireNonNull(expectedPreviousActive); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + parseGeneration(targetGeneration); + requireMatch(KID, targetKid, "promotion target kid"); + if (!ALGORITHM.equals(targetAlgorithm)) { + throw new QuarantinedStateException("Promotion target algorithm is unsupported"); + } + requireMatch(SHA256_HEX, targetPublicKeyFingerprint, "promotion target fingerprint"); + requireMatch( + RESOURCE_VERSION, expectedPrivateResourceVersion, "expected private Secret version"); + requireMatch( + RESOURCE_VERSION, expectedPublicResourceVersion, "expected public ConfigMap version"); + Objects.requireNonNull(trustFence, "Promotion trust fence is required"); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + requireMatch(SHA256_HEX, apiBindingDigest, "public API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "public API config revision"); + requireUuid(secretUid, "promotion Secret UID"); + requireUuid(publicConfigMapUid, "promotion ConfigMap UID"); + requireMatch(SHA256_HEX, prepublicationIntentDigest, "prepublication intent digest"); + requireMatch(SHA256_HEX, prepublicationReceiptDigest, "prepublication receipt digest"); + requireMatch(SHA256_HEX, mountedObservationDigest, "mounted observation digest"); + requireMatch(SHA256_HEX, readinessPlanDigest, "readiness plan digest"); + requireMatch(SHA256_HEX, readinessEvidenceDigest, "readiness evidence digest"); + if (readinessEvidencePreimage == null + || readinessEvidencePreimage.isBlank() + || readinessEvidencePreimage.getBytes(StandardCharsets.UTF_8).length > 1024 * 1024 + || !readinessEvidenceDigest.equals( + sha256(readinessEvidencePreimage.getBytes(StandardCharsets.UTF_8)))) { + throw new QuarantinedStateException( + "Promotion readiness preimage does not match its exact digest"); + } + if (expectedPublicJwksJson == null + || expectedPublicJwksJson.isBlank() + || expectedPublicJwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024 + || expectedActiveMarkerJson == null + || expectedActiveMarkerJson.isBlank() + || expectedActiveMarkerJson.getBytes(StandardCharsets.UTF_8).length > 16 * 1024) { + throw new QuarantinedStateException("Promotion public payload is missing or oversized"); + } + if (!Set.of("PREPARED", "COMMITTED", "ABORTED").contains(status)) { + throw new QuarantinedStateException("Promotion status is malformed"); + } + boolean noActiveJwksReceipt = + activeJwksObservedResourceVersion == null + && activeJwksPublicDataDigest == null + && activeJwksReceiptDigest == null; + boolean completeActiveJwksReceipt = + activeJwksObservedResourceVersion != null + && activeJwksPublicDataDigest != null + && activeJwksReceiptDigest != null; + if ((privatePromotionObservedResourceVersion == null) + != (privatePromotionReceiptDigest == null) + || !(noActiveJwksReceipt || completeActiveJwksReceipt)) { + throw new QuarantinedStateException("Promotion resource receipts are partial"); + } + if ((privatePromotionReceiptDigest != null && !privatePromotionDispatched) + || ("COMMITTED".equals(status) && !privatePromotionDispatched) + || ("ABORTED".equals(status) && privatePromotionDispatched)) { + throw new QuarantinedStateException( + "Promotion dispatch state is inconsistent with its receipts or terminal status"); + } + if (privatePromotionObservedResourceVersion != null) { + requireMatch( + RESOURCE_VERSION, + privatePromotionObservedResourceVersion, + "private promotion readback version"); + requireMatch(SHA256_HEX, privatePromotionReceiptDigest, "private promotion receipt digest"); + } + if (activeJwksObservedResourceVersion != null) { + requireMatch( + RESOURCE_VERSION, activeJwksObservedResourceVersion, "active JWKS readback version"); + requireMatch(SHA256_HEX, activeJwksPublicDataDigest, "active JWKS public data digest"); + requireMatch(SHA256_HEX, activeJwksReceiptDigest, "active JWKS receipt digest"); + } + } + + private static StoredPromotion create( + PromotionPreparation preparation, + DesiredState state, + StoredGenerationOperation generation, + GenerationResult result, + TrustFence trust, + Binding binding, + ReadinessPromotionProof readinessProof) { + if (!preparation.generationOperationId().equals(generation.operationId()) + || !preparation.generationResult().equals(result) + || !preparation + .enrollmentIdentity() + .sameStablePins(state.enrollmentIdentity().orElseThrow()) + || !generation.binding().equals(binding) + || !result.binding().equals(binding) + || !generation.trustFence().equals(trust) + || !result.trustFence().equals(trust) + || !preparation.readinessEvidenceDigest().equals(readinessProof.readinessEvidenceDigest()) + || !state.generationOperationId().equals(Optional.of(generation.operationId())) + || state.preparedOperationId().isPresent()) { + throw new PromotionPrerequisitesIncompleteException( + "Promotion preparation is not bound to the current Account generation and enrollment"); + } + UUID promotionId = UUID.randomUUID(); + StoredPromotion unsigned = + new StoredPromotion( + promotionId, + binding, + 1, + "0".repeat(64), + state.recordVersion(), + state.durableActive(), + state.publishedActive(), + result.targetGeneration(), + result.targetKid(), + result.targetAlgorithm(), + result.publicKeyFingerprint(), + result.observedResourceVersion(), + preparation.expectedPublicResourceVersion(), + trust, + generation.operationId(), + generation.operationDigest(), + result.receiptDigest(), + preparation.apiBindingDigest(), + preparation.apiConfigRevision(), + result.secretUid(), + preparation.publicConfigMapUid(), + preparation.prepublicationIntentDigest(), + preparation.prepublicationReceiptDigest(), + preparation.mountedObservationDigest(), + preparation.readinessPlanDigest(), + preparation.readinessEvidenceDigest(), + new String(readinessProof.readinessEvidencePreimage(), StandardCharsets.UTF_8), + preparation.expectedPublicJwksJson(), + "{}", + "PREPARED", + false, + null, + null, + null, + null, + null); + StoredPromotion signed = + new StoredPromotion( + unsigned.operationId(), + unsigned.binding(), + unsigned.requestDigestVersion(), + promotionRequestDigest(unsigned), + unsigned.expectedRecordVersion(), + unsigned.expectedPreviousActive(), + unsigned.expectedPublishedActive(), + unsigned.targetGeneration(), + unsigned.targetKid(), + unsigned.targetAlgorithm(), + unsigned.targetPublicKeyFingerprint(), + unsigned.expectedPrivateResourceVersion(), + unsigned.expectedPublicResourceVersion(), + unsigned.trustFence(), + unsigned.generationOperationId(), + unsigned.generationOperationDigest(), + unsigned.generationReceiptDigest(), + unsigned.apiBindingDigest(), + unsigned.apiConfigRevision(), + unsigned.secretUid(), + unsigned.publicConfigMapUid(), + unsigned.prepublicationIntentDigest(), + unsigned.prepublicationReceiptDigest(), + unsigned.mountedObservationDigest(), + unsigned.readinessPlanDigest(), + unsigned.readinessEvidenceDigest(), + unsigned.readinessEvidencePreimage(), + unsigned.expectedPublicJwksJson(), + "{}", + unsigned.status(), + unsigned.privatePromotionDispatched(), + null, + null, + null, + null, + null); + return new StoredPromotion( + signed.operationId(), + signed.binding(), + signed.requestDigestVersion(), + signed.requestDigest(), + signed.expectedRecordVersion(), + signed.expectedPreviousActive(), + signed.expectedPublishedActive(), + signed.targetGeneration(), + signed.targetKid(), + signed.targetAlgorithm(), + signed.targetPublicKeyFingerprint(), + signed.expectedPrivateResourceVersion(), + signed.expectedPublicResourceVersion(), + signed.trustFence(), + signed.generationOperationId(), + signed.generationOperationDigest(), + signed.generationReceiptDigest(), + signed.apiBindingDigest(), + signed.apiConfigRevision(), + signed.secretUid(), + signed.publicConfigMapUid(), + signed.prepublicationIntentDigest(), + signed.prepublicationReceiptDigest(), + signed.mountedObservationDigest(), + signed.readinessPlanDigest(), + signed.readinessEvidenceDigest(), + signed.readinessEvidencePreimage(), + signed.expectedPublicJwksJson(), + activeMarkerJson(signed), + signed.status(), + signed.privatePromotionDispatched(), + null, + null, + null, + null, + null); + } + + private String operationDigestForGeneration() { + return generationOperationDigest; + } + + private boolean matchesPreparation( + PromotionPreparation preparation, + StoredGenerationOperation generation, + GenerationResult result, + EnrollmentIdentity enrollment, + ReadinessPromotionProof readinessProof) { + return generation.operationId().equals(preparation.generationOperationId()) + && result.equals(preparation.generationResult()) + && preparation.enrollmentIdentity().sameStablePins(enrollment) + && apiBindingDigest.equals(preparation.apiBindingDigest()) + && apiConfigRevision.equals(preparation.apiConfigRevision()) + && publicConfigMapUid.equals(preparation.publicConfigMapUid()) + && expectedPublicResourceVersion.equals(preparation.expectedPublicResourceVersion()) + && prepublicationIntentDigest.equals(preparation.prepublicationIntentDigest()) + && prepublicationReceiptDigest.equals(preparation.prepublicationReceiptDigest()) + && mountedObservationDigest.equals(preparation.mountedObservationDigest()) + && readinessPlanDigest.equals(preparation.readinessPlanDigest()) + && readinessEvidenceDigest.equals(preparation.readinessEvidenceDigest()) + && readinessEvidencePreimage.equals( + new String(readinessProof.readinessEvidencePreimage(), StandardCharsets.UTF_8)) + && expectedPublicJwksJson.equals(preparation.expectedPublicJwksJson()) + && generationOperationId.equals(generation.operationId()) + && generationOperationDigest.equals(generation.operationDigest()) + && generationReceiptDigest.equals(result.receiptDigest()) + && secretUid.equals(result.secretUid()) + && expectedPrivateResourceVersion.equals(result.observedResourceVersion()) + && targetGeneration.equals(result.targetGeneration()) + && targetKid.equals(result.targetKid()) + && targetPublicKeyFingerprint.equals(result.publicKeyFingerprint()); + } + + private PromotionOperationEvidence publicEvidence() { + return new PromotionOperationEvidence( + operationId, + requestDigest, + expectedRecordVersion, + binding, + expectedPreviousActive, + expectedPreviousActive.map( + active -> publicFingerprintForKid(expectedPublicJwksJson, active.kid())), + expectedPublishedActive, + targetGeneration, + targetKid, + targetAlgorithm, + targetPublicKeyFingerprint, + trustFence, + generationOperationId, + generationOperationDigest, + generationReceiptDigest, + secretUid, + expectedPrivateResourceVersion, + apiBindingDigest, + apiConfigRevision, + publicConfigMapUid, + expectedPublicResourceVersion, + prepublicationIntentDigest, + prepublicationReceiptDigest, + mountedObservationDigest, + readinessPlanDigest, + readinessEvidenceDigest, + expectedPublicJwksJson, + expectedActiveMarkerJson, + status, + privatePromotionDispatched, + Optional.ofNullable(privatePromotionObservedResourceVersion), + Optional.ofNullable(privatePromotionReceiptDigest), + Optional.ofNullable(activeJwksObservedResourceVersion), + Optional.ofNullable(activeJwksPublicDataDigest), + Optional.ofNullable(activeJwksReceiptDigest)); + } + } + + public record PreparedGenerationEvidence( + DesiredState desiredState, + PromotionOperationEvidence promotion, + GenerationResult generationResult) { + public PreparedGenerationEvidence { + Objects.requireNonNull(desiredState); + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + if (!"PREPARED".equals(promotion.status()) + || !promotion.generationOperationId().equals(generationResult.operationId())) { + throw new QuarantinedStateException("Prepared generation evidence is inconsistent"); + } + } + } + + /** Exact current owner-readback values required to freeze one PREPARED operation. */ + public record PromotionPreparation( + UUID generationOperationId, + GenerationResult generationResult, + EnrollmentIdentity enrollmentIdentity, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String expectedPublicResourceVersion, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson) { + public PromotionPreparation { + requireOperationId(generationOperationId); + Objects.requireNonNull(generationResult, "Persisted generation result is required"); + Objects.requireNonNull(enrollmentIdentity, "Pinned Account enrollment is required"); + requireMatch(SHA256_HEX, apiBindingDigest, "promotion API binding digest"); + requireMatch(CLUSTER_ID, apiConfigRevision, "promotion API config revision"); + requireUuid(publicConfigMapUid, "promotion public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, expectedPublicResourceVersion, "promotion ConfigMap resourceVersion"); + requireMatch(SHA256_HEX, prepublicationIntentDigest, "prepublication intent digest"); + requireMatch(SHA256_HEX, prepublicationReceiptDigest, "prepublication receipt digest"); + requireMatch(SHA256_HEX, mountedObservationDigest, "mounted observation digest"); + requireMatch(SHA256_HEX, readinessPlanDigest, "readiness plan digest"); + requireMatch(SHA256_HEX, readinessEvidenceDigest, "readiness evidence digest"); + if (expectedPublicJwksJson == null + || expectedPublicJwksJson.isBlank() + || expectedPublicJwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024) { + throw new PromotionPrerequisitesIncompleteException( + "Account promotion public projection is missing or oversized"); + } + } + } + + public record ActiveJwksPromotionObservation( + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String jwksJson, + String activeMarkerJson) { + public ActiveJwksPromotionObservation { + requireUuid(configMapUid, "active public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, priorResourceVersion, "active ConfigMap prior resourceVersion"); + requireMatch( + RESOURCE_VERSION, observedResourceVersion, "active ConfigMap readback resourceVersion"); + if (priorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap resourceVersion did not advance"); + } + if (jwksJson == null + || jwksJson.isBlank() + || jwksJson.getBytes(StandardCharsets.UTF_8).length > 256 * 1024 + || activeMarkerJson == null + || activeMarkerJson.isBlank() + || activeMarkerJson.getBytes(StandardCharsets.UTF_8).length > 16 * 1024) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap projection is missing or oversized"); + } + } + } + + public record ActiveJwksPromotionReceipt( + UUID promotionOperationId, + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String publicDataDigest, + String receiptDigest) { + public ActiveJwksPromotionReceipt { + requireOperationId(promotionOperationId); + requireUuid(configMapUid, "active public ConfigMap UID"); + requireMatch( + RESOURCE_VERSION, priorResourceVersion, "active ConfigMap prior resourceVersion"); + requireMatch( + RESOURCE_VERSION, observedResourceVersion, "active ConfigMap readback resourceVersion"); + requireMatch(SHA256_HEX, publicDataDigest, "active public ConfigMap data digest"); + requireMatch(SHA256_HEX, receiptDigest, "active public ConfigMap receipt digest"); + if (priorResourceVersion.equals(observedResourceVersion)) { + throw new QuarantinedStateException( + "Account ACTIVE ConfigMap resourceVersion did not advance"); + } + } + + private static ActiveJwksPromotionReceipt from( + StoredPromotion promotion, ActiveJwksPromotionObservation observation) { + String dataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest( + observation.jwksJson(), observation.activeMarkerJson()); + return create( + promotion, + observation.configMapUid(), + observation.priorResourceVersion(), + observation.observedResourceVersion(), + dataDigest); + } + + private static ActiveJwksPromotionReceipt fromStored(StoredPromotion promotion) { + if (promotion.activeJwksObservedResourceVersion() == null + || promotion.activeJwksPublicDataDigest() == null + || promotion.activeJwksReceiptDigest() == null) { + throw new QuarantinedStateException("Committed signer has no active JWKS receipt"); + } + ActiveJwksPromotionReceipt calculated = + create( + promotion, + promotion.publicConfigMapUid(), + promotion.expectedPublicResourceVersion(), + promotion.activeJwksObservedResourceVersion(), + promotion.activeJwksPublicDataDigest()); + if (!calculated.receiptDigest().equals(promotion.activeJwksReceiptDigest())) { + throw new QuarantinedStateException("Committed active JWKS receipt digest is invalid"); + } + return calculated; + } + + private static ActiveJwksPromotionReceipt create( + StoredPromotion promotion, + String configMapUid, + String priorResourceVersion, + String observedResourceVersion, + String dataDigest) { + Map preimage = new LinkedHashMap<>(); + preimage.put("receiptVersion", "account-jwt-active-jwks-promotion-receipt/v1"); + preimage.put("promotionOperationId", promotion.operationId().toString()); + preimage.put("promotionRequestDigest", promotion.requestDigest()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("configMapName", PUBLIC_JWKS_CONFIG_MAP_NAME); + preimage.put("configMapUid", configMapUid); + preimage.put("priorResourceVersion", priorResourceVersion); + preimage.put("observedResourceVersion", observedResourceVersion); + preimage.put("action", "MARK_ACTIVE"); + preimage.put("publicDataDigest", dataDigest); + return new ActiveJwksPromotionReceipt( + promotion.operationId(), + configMapUid, + priorResourceVersion, + observedResourceVersion, + dataDigest, + digest(preimage)); + } + } + + /** Durable non-authorizing result for Account's current committed active signer. */ + public record CommittedSignerEvidence( + PromotionOperationEvidence promotion, + GenerationResult generationResult, + DesiredState desiredState, + PrivatePromotionReceipt privateReceipt, + ActiveJwksPromotionReceipt publicReceipt) { + public CommittedSignerEvidence { + Objects.requireNonNull(promotion); + Objects.requireNonNull(generationResult); + Objects.requireNonNull(desiredState); + Objects.requireNonNull(privateReceipt); + Objects.requireNonNull(publicReceipt); + ActiveSigner target = new ActiveSigner(promotion.targetGeneration(), promotion.targetKid()); + if (!"COMMITTED".equals(promotion.status()) + || !promotion.operationId().equals(privateReceipt.promotionOperationId()) + || !promotion.operationId().equals(publicReceipt.promotionOperationId()) + || !promotion.generationOperationId().equals(generationResult.operationId()) + || desiredState.durableActive().filter(target::equals).isEmpty() + || desiredState.publishedActive().filter(target::equals).isEmpty() + || desiredState.preparedOperationId().isPresent()) { + throw new QuarantinedStateException("Committed signer evidence is inconsistent"); + } + } + } + + public record AbortedPromotion( + UUID operationId, + long desiredStateVersion, + Optional durableActive, + Optional publishedActive) { + public AbortedPromotion { + requireOperationId(operationId); + if (desiredStateVersion <= 0) + throw new IllegalArgumentException("Aborted state version is invalid"); + durableActive = Objects.requireNonNull(durableActive); + publishedActive = Objects.requireNonNull(publishedActive); + if (!durableActive.equals(publishedActive)) { + throw new QuarantinedStateException("Aborted signer operation changed active fences"); + } + } + } + + /** Terminal, non-authorizing receipt for one exact unprepared generation operation. */ + public record GenerationAbortReceipt( + UUID operationId, + Binding binding, + String operationDigest, + String generationRequestDigest, + String generationReceiptDigest, + long expectedStateVersion, + long resultingStateVersion, + TrustFence trustFence, + Optional durableActive, + Optional publishedActive) { + public GenerationAbortReceipt { + requireOperationId(operationId); + Objects.requireNonNull(binding, "Generation abort binding is required"); + requireMatch(SHA256_HEX, operationDigest, "aborted generation operation digest"); + requireMatch(SHA256_HEX, generationRequestDigest, "aborted generation request digest"); + requireMatch(SHA256_HEX, generationReceiptDigest, "aborted generation result digest"); + if (expectedStateVersion <= 1L + || expectedStateVersion == Long.MAX_VALUE + || resultingStateVersion != expectedStateVersion + 1L) { + throw new QuarantinedStateException("Generation abort state-version fence is malformed"); + } + Objects.requireNonNull(trustFence, "Generation abort trust fence is required"); + durableActive = Objects.requireNonNull(durableActive); + publishedActive = Objects.requireNonNull(publishedActive); + } + + private static GenerationAbortReceipt from( + DesiredState state, + StoredGenerationOperation operation, + GenerationResult result, + TrustFence trust) { + if (state.recordVersion() != result.desiredStateVersion() + || !state.binding().equals(operation.binding()) + || !state.durableActive().equals(operation.expectedPreviousActive()) + || !state.publishedActive().equals(operation.expectedPublishedActive()) + || !operation.operationId().equals(result.operationId()) + || !operation.operationDigest().equals(result.operationDigest()) + || !result.trustFence().equals(trust) + || !operation.trustFence().equals(trust)) { + throw new QuarantinedStateException( + "Generation abort source does not match current Account owner evidence"); + } + return new GenerationAbortReceipt( + operation.operationId(), + operation.binding(), + operation.operationDigest(), + result.generationRequestDigest(), + result.receiptDigest(), + state.recordVersion(), + state.recordVersion() + 1L, + trust, + state.durableActive(), + state.publishedActive()); + } + + private boolean matches( + StoredGenerationOperation operation, GenerationResult result, TrustFence trust) { + return binding.equals(operation.binding()) + && operationId.equals(operation.operationId()) + && operationDigest.equals(operation.operationDigest()) + && generationRequestDigest.equals(result.generationRequestDigest()) + && generationReceiptDigest.equals(result.receiptDigest()) + && expectedStateVersion == result.desiredStateVersion() + && trustFence.equals(trust) + && trustFence.equals(operation.trustFence()) + && trustFence.equals(result.trustFence()) + && durableActive.equals(operation.expectedPreviousActive()) + && publishedActive.equals(operation.expectedPublishedActive()); + } + } + + /** Public-only immutable promotion row needed by the materializer and Account reconciler. */ + public record PromotionOperationEvidence( + UUID operationId, + String requestDigest, + long expectedRecordVersion, + Binding binding, + Optional expectedPreviousActive, + Optional expectedPreviousPublicKeyFingerprint, + Optional expectedPublishedActive, + String targetGeneration, + String targetKid, + String targetAlgorithm, + String targetPublicKeyFingerprint, + TrustFence trustFence, + UUID generationOperationId, + String generationOperationDigest, + String generationReceiptDigest, + String secretUid, + String expectedPrivateResourceVersion, + String apiBindingDigest, + String apiConfigRevision, + String publicConfigMapUid, + String expectedPublicResourceVersion, + String prepublicationIntentDigest, + String prepublicationReceiptDigest, + String mountedObservationDigest, + String readinessPlanDigest, + String readinessEvidenceDigest, + String expectedPublicJwksJson, + String expectedActiveMarkerJson, + String status, + boolean privatePromotionDispatched, + Optional privatePromotionObservedResourceVersion, + Optional privatePromotionReceiptDigest, + Optional activeJwksObservedResourceVersion, + Optional activeJwksPublicDataDigest, + Optional activeJwksReceiptDigest) { + public PromotionOperationEvidence { + Objects.requireNonNull(operationId); + requireMatch(SHA256_HEX, requestDigest, "promotion request digest"); + Objects.requireNonNull(binding); + expectedPreviousActive = Objects.requireNonNull(expectedPreviousActive); + expectedPreviousPublicKeyFingerprint = + Objects.requireNonNull(expectedPreviousPublicKeyFingerprint); + expectedPublishedActive = Objects.requireNonNull(expectedPublishedActive); + if (expectedPreviousActive.isPresent() != expectedPreviousPublicKeyFingerprint.isPresent()) { + throw new QuarantinedStateException("Promotion prior public identity is incomplete"); + } + expectedPreviousPublicKeyFingerprint.ifPresent( + value -> requireMatch(SHA256_HEX, value, "prior public-key fingerprint")); + Objects.requireNonNull(trustFence); + Objects.requireNonNull(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireMatch(SHA256_HEX, generationReceiptDigest, "generation receipt digest"); + privatePromotionObservedResourceVersion = + Objects.requireNonNull(privatePromotionObservedResourceVersion); + privatePromotionReceiptDigest = Objects.requireNonNull(privatePromotionReceiptDigest); + activeJwksObservedResourceVersion = Objects.requireNonNull(activeJwksObservedResourceVersion); + activeJwksPublicDataDigest = Objects.requireNonNull(activeJwksPublicDataDigest); + activeJwksReceiptDigest = Objects.requireNonNull(activeJwksReceiptDigest); + } + } + + public record PublicKeyIdentity(String generation, String kid, String publicKeyFingerprint) { + public PublicKeyIdentity { + parseGeneration(generation); + requireMatch(KID, kid, "observed public key kid"); + requireMatch(SHA256_HEX, publicKeyFingerprint, "observed public key fingerprint"); + } + } + + public record PrivatePromotionObservation( + UUID promotionOperationId, + String promotionRequestDigest, + UUID generationOperationId, + String generationOperationDigest, + String secretUid, + String expectedPriorResourceVersion, + String observedResourceVersion, + PublicKeyIdentity current, + Optional previous, + List resultingSlots) { + public PrivatePromotionObservation { + requireOperationId(promotionOperationId); + requireMatch(SHA256_HEX, promotionRequestDigest, "promotion request digest"); + requireOperationId(generationOperationId); + requireMatch(SHA256_HEX, generationOperationDigest, "generation operation digest"); + requireUuid(secretUid, "observed fixed Secret UID"); + requireMatch(RESOURCE_VERSION, expectedPriorResourceVersion, "expected Secret version"); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "observed Secret version"); + Objects.requireNonNull(current); + previous = Objects.requireNonNull(previous); + resultingSlots = List.copyOf(resultingSlots); + if (expectedPriorResourceVersion.equals(observedResourceVersion) + || !(resultingSlots.equals(List.of("current")) + || resultingSlots.equals(List.of("current", "previous")))) { + throw new QuarantinedStateException("Private promotion readback identity is malformed"); + } + } + } + + public record PrivatePromotionReceipt( + UUID promotionOperationId, + UUID generationOperationId, + String observedResourceVersion, + String receiptDigest) { + public PrivatePromotionReceipt { + requireOperationId(promotionOperationId); + requireOperationId(generationOperationId); + requireMatch(RESOURCE_VERSION, observedResourceVersion, "private promotion readback version"); + requireMatch(SHA256_HEX, receiptDigest, "private promotion receipt digest"); + } + + private static PrivatePromotionReceipt from( + StoredPromotion promotion, PrivatePromotionObservation observation) { + Map preimage = new LinkedHashMap<>(); + preimage.put("receiptVersion", 1); + preimage.put("promotionOperationId", promotion.operationId().toString()); + preimage.put("promotionRequestDigest", promotion.requestDigest()); + preimage.put("generationOperationId", promotion.generationOperationId().toString()); + preimage.put("generationOperationDigest", promotion.generationOperationDigest()); + preimage.put("generationReceiptDigest", promotion.generationReceiptDigest()); + preimage.put("secretResource", Map.of("kind", "Secret", "name", PRIVATE_SECRET_NAME)); + preimage.put("secretUid", observation.secretUid()); + preimage.put("expectedPriorResourceVersion", observation.expectedPriorResourceVersion()); + preimage.put("observedResourceVersion", observation.observedResourceVersion()); + preimage.put("action", "PROMOTE_PENDING"); + preimage.put("resultingSlots", observation.resultingSlots()); + preimage.put("current", publicKeyIdentityMap(observation.current())); + preimage.put( + "previous", + observation + .previous() + .map(AccountJwtSignerDesiredStateRepository::publicKeyIdentityMap) + .orElseGet(() -> Map.of("present", false))); + return new PrivatePromotionReceipt( + promotion.operationId(), + promotion.generationOperationId(), + observation.observedResourceVersion(), + digest(preimage)); + } + + private static PrivatePromotionReceipt fromStored(StoredPromotion promotion) { + if (promotion.privatePromotionObservedResourceVersion() == null + || promotion.privatePromotionReceiptDigest() == null) { + throw new QuarantinedStateException("Committed signer has no private promotion receipt"); + } + Optional previous = + promotion + .expectedPreviousActive() + .map( + active -> + new PublicKeyIdentity( + active.generation(), + active.kid(), + publicFingerprintForKid( + promotion.expectedPublicJwksJson(), active.kid()))); + PrivatePromotionReceipt calculated = + from( + promotion, + new PrivatePromotionObservation( + promotion.operationId(), + promotion.requestDigest(), + promotion.generationOperationId(), + promotion.generationOperationDigest(), + promotion.secretUid(), + promotion.expectedPrivateResourceVersion(), + promotion.privatePromotionObservedResourceVersion(), + new PublicKeyIdentity( + promotion.targetGeneration(), + promotion.targetKid(), + promotion.targetPublicKeyFingerprint()), + previous, + previous.isPresent() ? List.of("current", "previous") : List.of("current"))); + if (!calculated.receiptDigest().equals(promotion.privatePromotionReceiptDigest())) { + throw new QuarantinedStateException( + "Committed private promotion receipt digest is invalid"); + } + return calculated; + } + } + + private static Map publicKeyIdentityMap(PublicKeyIdentity identity) { + return Map.of( + "generation", identity.generation(), + "kid", identity.kid(), + "publicKeyFingerprint", identity.publicKeyFingerprint()); + } + + public record PreparedPromotion(UUID operationId, String requestDigest, String status) { + public PreparedPromotion { + requireOperationId(operationId); + requireMatch(SHA256_HEX, requestDigest, "prepared promotion digest"); + if (!"PREPARED".equals(status)) { + throw new IllegalArgumentException("Only PREPARED JWT signer operations are represented"); + } + } + } + + private static String generationRequestDigest( + String operationDigest, String observationDigest, String secretUid, String resourceVersion) { + return digest( + Map.of( + "digestVersion", GENERATION_REQUEST_DIGEST_VERSION, + "operationDigest", operationDigest, + "observationDigest", observationDigest, + "secretUid", secretUid, + "expectedPriorResourceVersion", resourceVersion, + "target", "pending")); + } + + public static class MissingDesiredStateException extends IllegalStateException { + public MissingDesiredStateException(String environmentId) { + super("Account JWT signer desired state is missing for environment " + environmentId); + } + } + + public static class MissingGenerationOperationException extends IllegalStateException { + public MissingGenerationOperationException(String message) { + super(message); + } + } + + public static class MissingGenerationObservationException extends IllegalStateException { + public MissingGenerationObservationException(String message) { + super(message); + } + } + + public static class StaleGenerationOperationException extends IllegalStateException { + public StaleGenerationOperationException(String message) { + super(message); + } + } + + public static class BindingMismatchException extends IllegalStateException { + public BindingMismatchException(String message) { + super(message); + } + } + + public static class VersionConflictException extends IllegalStateException { + public VersionConflictException(String message) { + super(message); + } + } + + public static class IdempotencyConflictException extends IllegalStateException { + public IdempotencyConflictException(String message) { + super(message); + } + } + + public static class QuarantinedStateException extends IllegalStateException { + public QuarantinedStateException(String message) { + super(message); + } + + public QuarantinedStateException(String message, Throwable cause) { + super(message, cause); + } + } + + public static class PromotionPrerequisitesIncompleteException extends IllegalStateException { + public PromotionPrerequisitesIncompleteException(String message) { + super(message); + } + } + + public static class NoPreparedPromotionException extends IllegalStateException { + public NoPreparedPromotionException() { + super("Account has no PREPARED JWT signer promotion"); + } + } + + public static class StorageUnavailableException extends IllegalStateException { + public StorageUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java new file mode 100644 index 0000000000..d0f47c12de --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepository.java @@ -0,0 +1,280 @@ +package net.firedevops.firemud.accountservice.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +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; + +/** + * Immutable persistence for an Account-observed, non-authorizing validator inventory snapshot. The + * table stores only the source's closed canonical public/runtime observation, never API response + * objects or credentials. + */ +@Repository +public class AccountJwtValidatorInventoryRepository { + public static final int MAX_SNAPSHOT_BYTES = 4 * 1024 * 1024; + private static final String TABLE = "account_jwt_validator_inventory_snapshots"; + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "The constructor only validates its trusted injected DSLContext; it performs no I/O or resource acquisition and defines no finalizer.") + public AccountJwtValidatorInventoryRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "DSLContext is required"); + } + + /** Inserts once or proves that a same-digest retry reads back the exact immutable bytes. */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSnapshot persistOrReadback( + InventorySnapshot snapshot, Binding binding, TrustFence trustFence) { + requireWritableAccountTransaction(); + Objects.requireNonNull(snapshot, "Owner-observed inventory snapshot is required"); + requireBinding(snapshot, binding, trustFence); + byte[] canonicalBytes = snapshot.canonicalBytes(); + requireSnapshotBytes(canonicalBytes, snapshot.digest()); + dsl.execute( + "INSERT INTO " + + TABLE + + " (snapshot_digest, environment_id, cluster_id, cluster_incarnation_uid, " + + "kubernetes_namespace, namespace_uid, api_binding_revision, api_binding_digest, " + + "inventory_binding_revision, inventory_binding_digest, observed_at, canonical_snapshot) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "ON CONFLICT (snapshot_digest) DO NOTHING", + snapshot.digest(), + snapshot.environmentId(), + snapshot.clusterId(), + UUID.fromString(snapshot.clusterIncarnationUid()), + snapshot.namespace(), + UUID.fromString(snapshot.namespaceUid()), + snapshot.apiBindingRevision(), + snapshot.apiBindingDigest(), + snapshot.inventoryBindingRevision(), + snapshot.inventoryBindingDigest(), + snapshot.observedAt().toString(), + canonicalBytes); + Record row = + dsl.fetchOne( + "SELECT * FROM " + TABLE + " WHERE snapshot_digest = ? FOR UPDATE", snapshot.digest()); + StoredSnapshot stored = decode(row); + requireSameSnapshot(snapshot, stored); + requireBinding(stored, binding, trustFence); + return stored; + } + + /** Reads the exact previously persisted snapshot and rechecks its Account binding. */ + @Transactional(propagation = Propagation.MANDATORY) + public StoredSnapshot readRequired(String digest, Binding binding, TrustFence trustFence) { + requireWritableAccountTransaction(); + if (digest == null || !DIGEST.matcher(digest).matches()) { + throw new InventorySnapshotUnavailableException(); + } + Record row = + dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE snapshot_digest = ? FOR SHARE", digest); + StoredSnapshot stored = decode(row); + requireBinding(stored, binding, trustFence); + return stored; + } + + private static StoredSnapshot decode(Record row) { + if (row == null) { + throw new InventorySnapshotUnavailableException(); + } + try { + String digest = row.get("snapshot_digest", String.class); + byte[] bytes = row.get("canonical_snapshot", byte[].class); + requireSnapshotBytes(bytes, digest); + StoredSnapshot stored = + new StoredSnapshot( + digest, + row.get("environment_id", String.class), + row.get("cluster_id", String.class), + row.get("cluster_incarnation_uid", UUID.class).toString(), + row.get("kubernetes_namespace", String.class), + row.get("namespace_uid", UUID.class).toString(), + row.get("api_binding_revision", String.class), + row.get("api_binding_digest", String.class), + row.get("inventory_binding_revision", String.class), + row.get("inventory_binding_digest", String.class), + Instant.parse(row.get("observed_at", String.class)), + bytes); + return stored; + } catch (InventorySnapshotUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireSnapshotBytes(byte[] bytes, String digest) { + if (bytes == null + || bytes.length < 2 + || bytes.length > MAX_SNAPSHOT_BYTES + || digest == null + || !DIGEST.matcher(digest).matches() + || !digest(bytes).equals(digest)) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static String digest(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireSameSnapshot(InventorySnapshot expected, StoredSnapshot actual) { + // A content digest can be observed again later. Keep the first persisted timestamp immutable; + // callers separately use the fresh observation's timestamp for the bounded freshness check. + if (!expected.digest().equals(actual.digest()) + || !expected.environmentId().equals(actual.environmentId()) + || !expected.clusterId().equals(actual.clusterId()) + || !expected.clusterIncarnationUid().equals(actual.clusterIncarnationUid()) + || !expected.namespace().equals(actual.namespace()) + || !expected.namespaceUid().equals(actual.namespaceUid()) + || !expected.apiBindingRevision().equals(actual.apiBindingRevision()) + || !expected.apiBindingDigest().equals(actual.apiBindingDigest()) + || !expected.inventoryBindingRevision().equals(actual.inventoryBindingRevision()) + || !expected.inventoryBindingDigest().equals(actual.inventoryBindingDigest()) + || !MessageDigest.isEqual(expected.canonicalBytes(), actual.canonicalBytes())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireBinding( + InventorySnapshot snapshot, Binding binding, TrustFence trustFence) { + Objects.requireNonNull(binding, "Account generation binding is required"); + Objects.requireNonNull(trustFence, "Account trust fence is required"); + if (!binding.environmentId().equals(snapshot.environmentId()) + || !binding.clusterId().equals(snapshot.clusterId()) + || !binding.namespace().equals(snapshot.namespace()) + || !trustFence.expectedClusterIncarnationUid().equals(snapshot.clusterIncarnationUid()) + || !trustFence.expectedNamespaceUid().equals(snapshot.namespaceUid())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireBinding( + StoredSnapshot snapshot, Binding binding, TrustFence trustFence) { + Objects.requireNonNull(binding, "Account generation binding is required"); + Objects.requireNonNull(trustFence, "Account trust fence is required"); + if (!binding.environmentId().equals(snapshot.environmentId()) + || !binding.clusterId().equals(snapshot.clusterId()) + || !binding.namespace().equals(snapshot.namespace()) + || !trustFence.expectedClusterIncarnationUid().equals(snapshot.clusterIncarnationUid()) + || !trustFence.expectedNamespaceUid().equals(snapshot.namespaceUid())) { + throw new InventorySnapshotUnavailableException(); + } + } + + private static void requireAccountTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive()) { + throw new IllegalStateException("An owning Account transaction is required"); + } + } + + private static void requireWritableAccountTransaction() { + requireAccountTransaction(); + if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException("A writable Account transaction is required"); + } + } + + public record StoredSnapshot( + String digest, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + Instant observedAt, + byte[] canonicalBytes) { + public StoredSnapshot { + Objects.requireNonNull(digest); + Objects.requireNonNull(environmentId); + Objects.requireNonNull(clusterId); + Objects.requireNonNull(clusterIncarnationUid); + Objects.requireNonNull(namespace); + Objects.requireNonNull(namespaceUid); + Objects.requireNonNull(apiBindingRevision); + Objects.requireNonNull(apiBindingDigest); + Objects.requireNonNull(inventoryBindingRevision); + Objects.requireNonNull(inventoryBindingDigest); + Objects.requireNonNull(observedAt); + canonicalBytes = canonicalBytes.clone(); + requireSnapshotBytes(canonicalBytes, digest); + } + + @Override + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof StoredSnapshot that)) { + return false; + } + return digest.equals(that.digest) + && environmentId.equals(that.environmentId) + && clusterId.equals(that.clusterId) + && clusterIncarnationUid.equals(that.clusterIncarnationUid) + && namespace.equals(that.namespace) + && namespaceUid.equals(that.namespaceUid) + && apiBindingRevision.equals(that.apiBindingRevision) + && apiBindingDigest.equals(that.apiBindingDigest) + && inventoryBindingRevision.equals(that.inventoryBindingRevision) + && inventoryBindingDigest.equals(that.inventoryBindingDigest) + && observedAt.equals(that.observedAt) + && Arrays.equals(canonicalBytes, that.canonicalBytes); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + digest, + environmentId, + clusterId, + clusterIncarnationUid, + namespace, + namespaceUid, + apiBindingRevision, + apiBindingDigest, + inventoryBindingRevision, + inventoryBindingDigest, + observedAt) + + Arrays.hashCode(canonicalBytes); + } + } + + public static final class InventorySnapshotUnavailableException extends RuntimeException { + public InventorySnapshotUnavailableException() { + super("Account validator inventory snapshot is unavailable or inconsistent"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningSpec.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningSpec.java new file mode 100644 index 0000000000..c2c7cb5777 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningSpec.java @@ -0,0 +1,79 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.time.Instant; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; + +/** One canonical initial creator's immutable signing input, never an authentication result. */ +final class AccountControlUiSigningSpec { + private final UUID operationId; + private final UUID requestId; + private final UUID jti; + private final Map claims; + + AccountControlUiSigningSpec( + UUID operationId, + UUID requestId, + UUID jti, + AccountControlUiAuthority.Snapshot source, + Instant issuedAt, + Instant expiresAt) { + if (operationId == null + || requestId == null + || jti == null + || source == null + || issuedAt == null + || expiresAt == null + || issuedAt.getNano() != 0 + || expiresAt.getNano() != 0 + || !expiresAt.isAfter(issuedAt) + || expiresAt.isAfter(issuedAt.plusSeconds(300))) { + throw new IllegalArgumentException("Exact bounded control-ui signing input required"); + } + this.operationId = operationId; + this.requestId = requestId; + this.jti = jti; + var values = new java.util.LinkedHashMap(); + values.put("iss", "firemud-account-service"); + values.put("aud", ControlUiJwtProfileValidator.AUDIENCE); + values.put("sub", source.actor().toString()); + values.put("accountId", source.actor().toString()); + values.put("jti", jti.toString()); + values.put("iat", issuedAt.getEpochSecond()); + values.put("nbf", issuedAt.getEpochSecond()); + values.put("exp", expiresAt.getEpochSecond()); + values.put("tokenGeneration", 1L); + values.put("authorityTuple", source.authorityTuple()); + values.put("membershipVersion", source.membershipVersion()); + values.put("issuanceFence", source.issuanceFence()); + values.put("scopedRoles", Map.of(source.tenant().toString(), java.util.List.of("tenantAdmin"))); + ControlUiJwtProfileValidator.validateClaims(values, 1); + if (AccountControlUiAuthority.canonical(values).length > 12288) { + throw new IllegalArgumentException("Control-ui claim encoding exceeds its finite ceiling"); + } + this.claims = Map.copyOf(values); + } + + UUID operationId() { + return operationId; + } + + UUID requestId() { + return requestId; + } + + UUID jti() { + return jti; + } + + Map claims() { + return claims; + } + + @Override + public String toString() { + return "AccountControlUiSigningSpec[redacted]"; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java new file mode 100644 index 0000000000..3344965501 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerSelector.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.net.URI; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; + +/** Closed, bounded selector for an authenticated read of one current V2 readiness entry. */ +public record AccountJwtReadinessProbeOwnerSelector( + UUID rotationOperationId, + String operationDigest, + String planDigest, + int planVersion, + int registryVersion, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + ProbeExpectation expectedOutcome, + UUID jti, + long entryVersion, + String targetGeneration, + String targetKid, + Optional expectedActive, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + long planExpiresAtEpochSecond, + String compactTokenSha256, + LocalIdentity localIdentity) { + private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,62}"); + private static final Pattern PROFILE = Pattern.compile("[a-z][a-z0-9-]{0,62}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}"); + + public AccountJwtReadinessProbeOwnerSelector { + Objects.requireNonNull(rotationOperationId, "operation ID is required"); + if (rotationOperationId.version() != 4 || rotationOperationId.variant() != 2) { + throw new IllegalArgumentException("Canonical readiness operation UUIDv4 is required"); + } + requireDigest(operationDigest, "operation digest"); + requireDigest(planDigest, "plan digest"); + if (planVersion != AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION + || registryVersion != 1 + || entryVersion <= 0L) { + throw new IllegalArgumentException("Current V2 readiness coordinates are required"); + } + requireId(validatorId, "validator ID"); + requireProfile(tokenProfile); + requireProfile(audience); + Objects.requireNonNull(probeKind, "probe kind is required"); + Objects.requireNonNull(expectedOutcome, "expected outcome is required"); + Objects.requireNonNull(jti, "probe JTI is required"); + if (jti.version() != 4 || jti.variant() != 2) { + throw new IllegalArgumentException("Canonical readiness JTI is required"); + } + requireGeneration(targetGeneration); + requireKid(targetKid); + expectedActive = Objects.requireNonNull(expectedActive, "active fence state is required"); + if (issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || planExpiresAtEpochSecond <= 0L + || expiresAtEpochSecond > planExpiresAtEpochSecond) { + throw new IllegalArgumentException("Readiness probe time bounds are malformed"); + } + requireDigest(compactTokenSha256, "compact token digest"); + Objects.requireNonNull(localIdentity, "protected local identity is required"); + } + + public record LocalIdentity( + String validatorId, + String deploymentUid, + String podUid, + String podIp, + String directPodEndpoint, + String canonicalServiceUri, + String image, + String verifierConfigSha256, + String applicabilityMatrixDigest, + String sourceInventoryRevision, + String sourceInventoryDigest, + String serverLeafSpkiSha256) { + public LocalIdentity { + requireId(validatorId, "validator ID"); + requireCanonicalUuid(deploymentUid, "deployment UID"); + requireCanonicalUuid(podUid, "Pod UID"); + if (!net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding + .canonicalPodIp(podIp) + .equals(podIp)) { + throw new IllegalArgumentException("Pod IP is not canonical"); + } + requireText(directPodEndpoint, 256, "direct Pod endpoint"); + requireText(canonicalServiceUri, 256, "canonical service URI"); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Validator image must be digest-pinned"); + } + requireDigest(verifierConfigSha256, "verifier configuration digest"); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + if (sourceInventoryRevision == null || !REVISION.matcher(sourceInventoryRevision).matches()) { + throw new IllegalArgumentException("Receiver source inventory revision is malformed"); + } + requireDigest(sourceInventoryDigest, "receiver source inventory digest"); + requireDigest(serverLeafSpkiSha256, "receiver TLS SPKI digest"); + URI endpoint = URI.create(directPodEndpoint); + if (!endpoint.toString().equals(directPodEndpoint) + || !canonicalServiceUri.matches( + "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])?")) { + throw new IllegalArgumentException("Receiver endpoint or service identity is malformed"); + } + } + } + + private static void requireCanonicalUuid(String value, String label) { + if (value == null + || !value.matches("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}") + || !UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException(label + " is not canonical"); + } + } + + private static void requireDigest(String value, String label) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is malformed"); + } + } + + private static void requireId(String value, String label) { + if (value == null || !ID.matcher(value).matches()) { + throw new IllegalArgumentException(label + " is malformed"); + } + } + + private static void requireProfile(String value) { + if (value == null || !PROFILE.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness profile or audience is malformed"); + } + } + + private static void requireKid(String value) { + if (value == null || !KID.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness target key ID is malformed"); + } + } + + private static void requireGeneration(String value) { + if (value == null || !GENERATION.matcher(value).matches()) { + throw new IllegalArgumentException("Readiness target generation is malformed"); + } + } + + private static void requireText(String value, int maximum, String label) { + if (value == null + || value.isBlank() + || value.length() > maximum + || value.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException(label + " is malformed"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java new file mode 100644 index 0000000000..88acaea9a6 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java @@ -0,0 +1,593 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; + +/** + * Account-owned internal invocation boundary for one exact validator Pod and one exact probe. + * + *

The production implementation must route to the observed Pod endpoint, verify the TLS peer + * against its protected Pod-specific pin while retaining the canonical service SAN, and return an + * {@link AuthenticatedAcceptance} only after validating the receiver's production-verifier result + * and local Pod identity. No RPC request or harness DTO is an implementation of this port. + */ +public abstract class AccountJwtReadinessReceiverInvocationPort { + private static final Pattern UUID_V4 = + Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); + private static final Pattern UUID_CANONICAL = + 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 Pattern DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,62}"); + private static final Pattern SERVICE_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])?"); + + /** Invokes one Pod; implementations must fail closed if any target binding is unavailable. */ + public abstract AuthenticatedAcceptance invoke(Invocation invocation); + + /** Availability guard called before one-shot signing or delivery is durably claimed. */ + public abstract void requireAvailable(); + + /** No remote receiver or Pod-bound transport identity is currently composed. */ + public static AccountJwtReadinessReceiverInvocationPort defaultDenied() { + return new AccountJwtReadinessReceiverInvocationPort() { + @Override + public AuthenticatedAcceptance invoke(Invocation invocation) { + throw new ReceiverUnavailableException(); + } + + @Override + public void requireAvailable() { + throw new ReceiverUnavailableException(); + } + }; + } + + /** Owner-package factory for a response already authenticated by the real Pod-bound client. */ + static AuthenticatedAcceptance authenticatedAcceptance( + String podUid, + String actualPodEndpoint, + String image, + String verifierConfigSha256, + String actualServiceUri, + String actualPeerSpkiSha256, + UUID jti, + String compactTokenSha256, + String verifiedKid, + ProbeExpectation result, + long observedAtEpochSecond) { + return new AuthenticatedAcceptance( + podUid, + actualPodEndpoint, + image, + verifierConfigSha256, + actualServiceUri, + actualPeerSpkiSha256, + jti, + compactTokenSha256, + verifiedKid, + result, + observedAtEpochSecond); + } + + /** Exact, non-secret Pod target derived by Account from one protected inventory snapshot. */ + public record PodTarget( + String inventorySnapshotDigest, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + String validatorId, + String deploymentUid, + String podUid, + String podIp, + String image, + String verifierConfigSha256, + String applicabilityMatrixDigest, + ProbeExpectation expectation, + Optional exactPodEndpoint, + Optional canonicalServiceUri, + Optional podLeafSpkiSha256) { + public PodTarget { + requireDigest(inventorySnapshotDigest, "inventory snapshot digest"); + requireIdentity(environmentId, "environment ID"); + requireCluster(clusterId); + requireCanonicalUuid(clusterIncarnationUid, "cluster incarnation UID"); + requireIdentity(namespace, "Kubernetes namespace"); + requireCanonicalUuid(namespaceUid, "namespace UID"); + requireRevision(apiBindingRevision, "Kubernetes API binding revision"); + requireDigest(apiBindingDigest, "Kubernetes API binding digest"); + requireRevision(inventoryBindingRevision, "inventory binding revision"); + requireDigest(inventoryBindingDigest, "inventory binding digest"); + requireId(validatorId, "validator ID"); + requireCanonicalUuid(deploymentUid, "validator Deployment UID"); + requireCanonicalUuid(podUid, "validator Pod UID"); + if (!AccountJwtValidatorInventoryBinding.canonicalPodIp(podIp).equals(podIp)) { + throw new IllegalArgumentException("Protected validator Pod IP is not canonical"); + } + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Validator image must be pinned by digest"); + } + requireDigest(verifierConfigSha256, "verifier configuration digest"); + requireDigest(applicabilityMatrixDigest, "applicability matrix digest"); + Objects.requireNonNull(expectation, "probe expectation is required"); + exactPodEndpoint = Objects.requireNonNull(exactPodEndpoint); + canonicalServiceUri = Objects.requireNonNull(canonicalServiceUri); + podLeafSpkiSha256 = Objects.requireNonNull(podLeafSpkiSha256); + exactPodEndpoint.ifPresent(endpoint -> requirePodEndpoint(endpoint, podIp)); + canonicalServiceUri.ifPresent(AccountJwtReadinessReceiverInvocationPort::requireServiceUri); + podLeafSpkiSha256.ifPresent(value -> requireDigest(value, "Pod TLS leaf SPKI digest")); + } + + /** Missing addressing or a Pod-specific peer pin makes this target non-invocable. */ + public void requireRoutablePodIdentity() { + if (exactPodEndpoint.isEmpty() + || canonicalServiceUri.isEmpty() + || podLeafSpkiSha256.isEmpty()) { + throw new ReceiverUnavailableException(); + } + } + } + + /** One exact logical registry probe, including transient signed bytes but no signer authority. */ + public static final class Invocation { + private final UUID rotationOperationId; + private final String operationDigest; + private final String planDigest; + private final int planVersion; + private final long planExpiresAtEpochSecond; + private final String validatorId; + private final String tokenProfile; + private final String audience; + private final ProbeKind probeKind; + private final ProbeExpectation expectation; + private final int registryVersion; + private final long sourceEntryVersion; + private final UUID jti; + private final String compactJwt; + private final String compactTokenSha256; + private final String targetGeneration; + private final String targetKid; + private final Optional expectedActiveGeneration; + private final Optional expectedActiveKid; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final PodTarget target; + + Invocation( + UUID rotationOperationId, + String operationDigest, + String planDigest, + int planVersion, + long planExpiresAtEpochSecond, + String validatorId, + String tokenProfile, + String audience, + ProbeKind probeKind, + ProbeExpectation expectation, + int registryVersion, + long sourceEntryVersion, + UUID jti, + String compactJwt, + String compactTokenSha256, + String targetGeneration, + String targetKid, + Optional expectedActiveGeneration, + Optional expectedActiveKid, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + PodTarget target) { + this.rotationOperationId = Objects.requireNonNull(rotationOperationId); + requireUuid(rotationOperationId.toString(), "rotation operation ID"); + requireDigest(operationDigest, "generation operation digest"); + requireDigest(planDigest, "readiness plan digest"); + if (planVersion != AccountJwtReadinessProbeRepository.INVENTORY_PLAN_VERSION + || planExpiresAtEpochSecond <= 0L) { + throw new IllegalArgumentException("Exact V2 readiness plan coordinates are required"); + } + requireId(validatorId, "validator ID"); + if (tokenProfile == null || !tokenProfile.matches("[a-z][a-z0-9-]{0,127}")) { + throw new IllegalArgumentException("Token profile is malformed"); + } + if (audience == null || !audience.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("Token audience is malformed"); + } + this.operationDigest = operationDigest; + this.planDigest = planDigest; + this.planVersion = planVersion; + this.planExpiresAtEpochSecond = planExpiresAtEpochSecond; + this.validatorId = validatorId; + this.tokenProfile = tokenProfile; + this.audience = audience; + this.probeKind = Objects.requireNonNull(probeKind); + this.expectation = Objects.requireNonNull(expectation); + if (registryVersion != 1 || sourceEntryVersion <= 0L) { + throw new IllegalArgumentException("Readiness entry version is malformed"); + } + this.registryVersion = registryVersion; + this.sourceEntryVersion = sourceEntryVersion; + this.jti = Objects.requireNonNull(jti); + requireUuid(jti.toString(), "probe JTI"); + if (compactJwt == null + || compactJwt.isBlank() + || compactJwt.length() > 16 * 1024 + || !compactJwt.matches("[A-Za-z0-9_=-]+\\.[A-Za-z0-9_=-]+\\.[A-Za-z0-9_=-]+")) { + throw new IllegalArgumentException("Compact readiness token is malformed"); + } + requireDigest(compactTokenSha256, "compact readiness token digest"); + if (!compactTokenSha256.equals(sha256(compactJwt))) { + throw new IllegalArgumentException("Compact readiness token digest does not match bytes"); + } + this.compactJwt = compactJwt; + this.compactTokenSha256 = compactTokenSha256; + if (targetGeneration == null || !targetGeneration.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Target generation is malformed"); + } + if (targetKid == null || !targetKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Target key ID is malformed"); + } + this.targetGeneration = targetGeneration; + this.targetKid = targetKid; + this.expectedActiveGeneration = Objects.requireNonNull(expectedActiveGeneration); + this.expectedActiveKid = Objects.requireNonNull(expectedActiveKid); + if (expectedActiveGeneration.isPresent() != expectedActiveKid.isPresent()) { + throw new IllegalArgumentException("Expected active signer fence is partial"); + } + this.expectedActiveGeneration.ifPresent( + value -> { + if (!value.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Expected active generation is malformed"); + } + }); + this.expectedActiveKid.ifPresent( + value -> { + if (!value.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Expected active key ID is malformed"); + } + }); + if (issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond > planExpiresAtEpochSecond) { + throw new IllegalArgumentException("Readiness token lifetime is malformed"); + } + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.target = Objects.requireNonNull(target); + if (!validatorId.equals(target.validatorId())) { + throw new IllegalArgumentException("Readiness probe and Pod validator differ"); + } + } + + public UUID rotationOperationId() { + return rotationOperationId; + } + + public String operationDigest() { + return operationDigest; + } + + public String planDigest() { + return planDigest; + } + + public int planVersion() { + return planVersion; + } + + public long planExpiresAtEpochSecond() { + return planExpiresAtEpochSecond; + } + + public String validatorId() { + return validatorId; + } + + public String tokenProfile() { + return tokenProfile; + } + + public String audience() { + return audience; + } + + public ProbeKind probeKind() { + return probeKind; + } + + public ProbeExpectation expectation() { + return expectation; + } + + public int registryVersion() { + return registryVersion; + } + + public long sourceEntryVersion() { + return sourceEntryVersion; + } + + public UUID jti() { + return jti; + } + + public String compactJwt() { + return compactJwt; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + public String targetGeneration() { + return targetGeneration; + } + + public String targetKid() { + return targetKid; + } + + public Optional expectedActiveGeneration() { + return expectedActiveGeneration; + } + + public Optional expectedActiveKid() { + return expectedActiveKid; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public PodTarget target() { + return target; + } + + @Override + public String toString() { + return "AccountJwtReadinessReceiverInvocation[rotationOperationId=" + + rotationOperationId + + ", validatorId=" + + validatorId + + ", podUid=" + + target.podUid() + + ", jti=" + + jti + + ", tokenRedacted=true]"; + } + } + + public enum ProbeExpectation { + ACCEPT, + INAPPLICABLE_REJECT + } + + /** + * Internal result established by the Account-owned receiver client after mTLS and response + * identity checks. Its package-private constructor is not available to an RPC adapter/harness. + */ + public static final class AuthenticatedAcceptance { + private final String podUid; + private final String actualPodEndpoint; + private final String image; + private final String verifierConfigSha256; + private final String actualServiceUri; + private final String actualPeerSpkiSha256; + private final UUID jti; + private final String compactTokenSha256; + private final String verifiedKid; + private final ProbeExpectation result; + private final long observedAtEpochSecond; + + private AuthenticatedAcceptance( + String podUid, + String actualPodEndpoint, + String image, + String verifierConfigSha256, + String actualServiceUri, + String actualPeerSpkiSha256, + UUID jti, + String compactTokenSha256, + String verifiedKid, + ProbeExpectation result, + long observedAtEpochSecond) { + requireCanonicalUuid(podUid, "receiver-reported local Pod UID"); + requirePodEndpointShape(actualPodEndpoint); + if (image == null || !image.matches("[^\\s@]+@sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("Receiver image is not pinned by digest"); + } + requireDigest(verifierConfigSha256, "receiver verifier configuration digest"); + requireServiceUri(actualServiceUri); + requireDigest(actualPeerSpkiSha256, "authenticated peer SPKI digest"); + Objects.requireNonNull(jti); + requireUuid(jti.toString(), "receiver probe JTI"); + requireDigest(compactTokenSha256, "receiver compact token digest"); + if (verifiedKid == null || !verifiedKid.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Receiver verified key ID is malformed"); + } + this.result = Objects.requireNonNull(result); + if (observedAtEpochSecond <= 0L) { + throw new IllegalArgumentException("Receiver observation time is malformed"); + } + this.podUid = podUid; + this.actualPodEndpoint = actualPodEndpoint; + this.image = image; + this.verifierConfigSha256 = verifierConfigSha256; + this.actualServiceUri = actualServiceUri; + this.actualPeerSpkiSha256 = actualPeerSpkiSha256; + this.jti = jti; + this.compactTokenSha256 = compactTokenSha256; + this.verifiedKid = verifiedKid; + this.observedAtEpochSecond = observedAtEpochSecond; + } + + public String podUid() { + return podUid; + } + + public String actualPodEndpoint() { + return actualPodEndpoint; + } + + public String image() { + return image; + } + + public String verifierConfigSha256() { + return verifierConfigSha256; + } + + public String actualServiceUri() { + return actualServiceUri; + } + + public String actualPeerSpkiSha256() { + return actualPeerSpkiSha256; + } + + public UUID jti() { + return jti; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + public String verifiedKid() { + return verifiedKid; + } + + public ProbeExpectation result() { + return result; + } + + public long observedAtEpochSecond() { + return observedAtEpochSecond; + } + + @Override + public String toString() { + return "AccountJwtReadinessAuthenticatedAcceptance[podUid=" + + podUid + + ", jti=" + + jti + + ", tokenRedacted=true]"; + } + } + + public static final class ReceiverUnavailableException extends IllegalStateException { + public ReceiverUnavailableException() { + super("Account JWT readiness receiver transport is unavailable"); + } + } + + private static void requirePodEndpoint(URI endpoint, String podIp) { + String endpointHost = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + if (!"grpcs".equals(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() < 1 + || endpoint.getPort() > 65535 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null && !endpoint.getRawPath().isEmpty()) + || !endpoint.toString().equals("grpcs://" + endpointHost + ":" + endpoint.getPort())) { + throw new IllegalArgumentException("Exact Pod endpoint is malformed"); + } + } + + private static void requirePodEndpointShape(String value) { + try { + URI endpoint = URI.create(value); + if (!"grpcs".equals(endpoint.getScheme()) + || endpoint.getHost() == null + || endpoint.getPort() < 1 + || endpoint.getPort() > 65535 + || endpoint.getRawUserInfo() != null + || endpoint.getRawQuery() != null + || endpoint.getRawFragment() != null + || (endpoint.getRawPath() != null && !endpoint.getRawPath().isEmpty())) { + throw new IllegalArgumentException("Observed Pod endpoint is malformed"); + } + } catch (RuntimeException failure) { + throw new IllegalArgumentException("Observed Pod endpoint is malformed", failure); + } + } + + private static void requireServiceUri(String value) { + if (value == null || !SERVICE_URI.matcher(value).matches()) { + throw new IllegalArgumentException("Canonical validator service SAN is malformed"); + } + } + + private static void requireDigest(String value, String name) { + if (value == null || !DIGEST.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireUuid(String value, String name) { + if (value == null || !UUID_V4.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireCanonicalUuid(String value, String name) { + if (value == null || !UUID_CANONICAL.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireId(String value, String name) { + if (value == null || !ID.matcher(value).matches()) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireIdentity(String value, String name) { + if (value == null || !value.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static void requireCluster(String value) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException("cluster ID is malformed"); + } + } + + private static void requireRevision(String value, String name) { + if (value == null || !value.matches("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}")) { + throw new IllegalArgumentException(name + " is malformed"); + } + } + + private static String sha256(String value) { + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.US_ASCII))); + } catch (NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 is unavailable", failure); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java new file mode 100644 index 0000000000..6531a91cf3 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java @@ -0,0 +1,1375 @@ +package net.firedevops.firemud.accountservice.service.session; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +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.AccountJwtJwksApiBinding.ApiOperation; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ReceiverPodPin; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ValidatorExpectation; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Default-inactive reader for one protected expected validator inventory and its live Kubernetes + * Deployment/Pod observations. The snapshot is non-authorizing evidence only; it does not prove + * per-Pod token acceptance, readiness completeness, promotion eligibility, or convergence. + */ +public final class AccountJwtValidatorInventorySource { + private static final int MAX_PAGES = 16; + private static final int MAX_PODS_PER_VALIDATOR = 128; + private static final int MAX_CANONICAL_SNAPSHOT_BYTES = 4 * 1024 * 1024; + private static final String INVENTORY_DOMAIN = "firemud-account-validator-inventory/v2"; + private static final String SELF_REVIEW_REQUEST = + "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}"; + private static final String RUNTIME_CONFIG_ENV = "FIREMUD_JWT_VERIFIER_CONFIG"; + 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 Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}"); + private static final Pattern IMAGE_DIGEST = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final Pattern OPERATION_DIGEST = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POD_TEMPLATE_HASH = Pattern.compile("[a-z0-9]{5,20}"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final AccountJwtJwksApiBinding apiBinding; + private final AccountJwtValidatorInventoryBinding inventoryBinding; + private final Clock clock; + + /** No Spring stereotype or automatic activation is provided. */ + public AccountJwtValidatorInventorySource( + AccountJwtJwksApiBinding apiBinding, + AccountJwtValidatorInventoryBinding inventoryBinding, + Clock clock) { + this.apiBinding = + Objects.requireNonNull(apiBinding, "protected Kubernetes API binding is required"); + this.inventoryBinding = + Objects.requireNonNull( + inventoryBinding, "protected validator inventory binding is required"); + this.clock = Objects.requireNonNull(clock, "clock is required"); + } + + /** + * Produces a fresh immutable observation. Any unavailable, changed, partial, ambiguous, legacy, + * or unpinned state is returned as one redacted failure; no Kubernetes response body is retained. + */ + public InventorySnapshot observe() { + return observeInternal(null); + } + + /** + * Produces an observation bound to an Account-selected durable generation operation. Only an + * initial operation with no durable or published active signer may enumerate non-ready Running + * Pods as candidates; those candidates still require the existing authenticated per-Pod probes + * before they can satisfy a promotion proof. + */ + public InventorySnapshot observe(ObservationContext observationContext) { + return observeInternal(Objects.requireNonNull(observationContext)); + } + + private InventorySnapshot observeInternal(ObservationContext observationContext) { + ProtectedInventory expected = + inventoryBinding.current().orElseThrow(InventoryUnavailableException::new); + boolean requireOrdinaryReady = + observationContext == null || observationContext.purpose().requiresOrdinaryReady(); + try (ApiOperation operation = apiBinding.beginOperation()) { + ParsedBinding api = operation.binding(); + if (!expected.matchesApiBinding(api)) { + throw new InventoryUnavailableException(); + } + verifyApiIdentity(operation, expected); + List observations = new ArrayList<>(); + for (ValidatorExpectation validator : expected.validators()) { + DeploymentObservation beforeDeployment = + readDeployment(operation, expected, validator, requireOrdinaryReady); + List beforePods = + readPods(operation, expected, validator, beforeDeployment, requireOrdinaryReady); + List beforeReplicaSets = + readReplicaSets( + operation, expected, validator, beforeDeployment, beforePods, requireOrdinaryReady); + DeploymentObservation afterDeployment = + readDeployment(operation, expected, validator, requireOrdinaryReady); + List afterPods = + readPods(operation, expected, validator, afterDeployment, requireOrdinaryReady); + List afterReplicaSets = + readReplicaSets( + operation, expected, validator, afterDeployment, afterPods, requireOrdinaryReady); + if (!beforeDeployment.equals(afterDeployment) + || !beforePods.equals(afterPods) + || !beforeReplicaSets.equals(afterReplicaSets)) { + throw new InventoryUnavailableException(); + } + observations.add( + new ValidatorObservation( + validator.validatorId(), + beforeDeployment.name(), + beforeDeployment.uid(), + beforeDeployment.generation(), + beforeDeployment.resourceVersion(), + beforeDeployment.replicas(), + beforeDeployment.image(), + beforeDeployment.verifierConfigSha256(), + validator.maxCacheAgeSeconds(), + validator.profiles(), + beforePods, + beforeReplicaSets)); + } + verifyApiIdentity(operation, expected); + ProtectedInventory afterExpected = + inventoryBinding.current().orElseThrow(InventoryUnavailableException::new); + if (!expected.bindingDigest().equals(afterExpected.bindingDigest()) + || !expected.configRevision().equals(afterExpected.configRevision())) { + throw new InventoryUnavailableException(); + } + Instant observedAt = clock.instant(); + if (observedAt == null || observedAt.isBefore(Instant.EPOCH)) { + throw new InventoryUnavailableException(); + } + return createSnapshot(expected, observations, observedAt, observationContext); + } catch (InventoryUnavailableException failure) { + throw failure; + } catch (RuntimeException failure) { + // Do not expose tokens, API bodies, file paths, parser details, or exception causes. + throw new InventoryUnavailableException(); + } + } + + private static void verifyApiIdentity(ApiOperation operation, ProtectedInventory expected) { + ParsedBinding binding = operation.binding(); + if (!expected.matchesApiBinding(binding)) { + throw new InventoryUnavailableException(); + } + ApiResponse selfReview = + operation.send( + AccountJwtJwksApiBinding.ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + SELF_REVIEW_REQUEST.getBytes(StandardCharsets.UTF_8)); + if (selfReview.statusCode() != 200 && selfReview.statusCode() != 201) { + throw new InventoryUnavailableException(); + } + JsonNode review = parseJson(selfReview.body()); + JsonNode status = review.get("status"); + JsonNode userInfo = status == null ? null : status.get("userInfo"); + JsonNode username = userInfo == null ? null : userInfo.get("username"); + JsonNode evaluationError = status == null ? null : status.get("evaluationError"); + if (!"authentication.k8s.io/v1".equals(text(review.get("apiVersion"))) + || !"SelfSubjectReview".equals(text(review.get("kind"))) + || !binding.expectedApiUsername().equals(text(username)) + || (evaluationError != null + && !evaluationError.isNull() + && (!evaluationError.isTextual() || !evaluationError.asText().isEmpty()))) { + throw new InventoryUnavailableException(); + } + verifyNamespace( + operation.send(AccountJwtJwksApiBinding.ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null), + "kube-system", + expected.expectedClusterIncarnationUid()); + verifyNamespace( + operation.send(AccountJwtJwksApiBinding.ApiCall.READ_TARGET_NAMESPACE, null), + expected.namespace(), + expected.expectedNamespaceUid()); + } + + private static void verifyNamespace(ApiResponse response, String name, String expectedUid) { + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + 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 InventoryUnavailableException(); + } + } + + private static DeploymentObservation readDeployment( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + boolean requireOrdinaryReady) { + ApiResponse response = operation.readValidatorDeployment(inventory, expected); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode spec = root.get("spec"); + JsonNode status = root.get("status"); + JsonNode selector = spec == null ? null : spec.get("selector"); + JsonNode template = spec == null ? null : spec.get("template"); + JsonNode templateMetadata = template == null ? null : template.get("metadata"); + JsonNode templateSpec = template == null ? null : template.get("spec"); + if (!"apps/v1".equals(text(root.get("apiVersion"))) + || !"Deployment".equals(text(root.get("kind"))) + || metadata == null + || !expected.deploymentName().equals(text(metadata.get("name"))) + || !inventory.namespace().equals(text(metadata.get("namespace"))) + || !expected.deploymentUid().equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || spec == null + || status == null + || selector == null + || !selectorMatches(selector.get("matchLabels"), expected.selector()) + || (selector.has("matchExpressions") + && selector.get("matchExpressions") != null + && !selector.get("matchExpressions").isNull() + && (!selector.get("matchExpressions").isArray() + || !selector.get("matchExpressions").isEmpty())) + || templateMetadata == null + || !labelsMatch(templateMetadata.get("labels"), expected.selector()) + || templateSpec == null) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + long generation = positiveLong(metadata.get("generation")); + int replicas = exactInt(spec.get("replicas"), 1, 128); + int readyReplicas = observedReplicaCount(status, "readyReplicas", !requireOrdinaryReady); + int updatedReplicas = exactInt(status.get("updatedReplicas"), 0, 128); + int availableReplicas = + observedReplicaCount(status, "availableReplicas", !requireOrdinaryReady); + int unavailableReplicas = + status.has("unavailableReplicas") && !status.get("unavailableReplicas").isNull() + ? exactInt(status.get("unavailableReplicas"), 0, 128) + : 0; + if (replicas != expected.replicas() + || positiveLong(status.get("observedGeneration")) != generation + || readyReplicas > replicas + || updatedReplicas != replicas + || availableReplicas > readyReplicas + || unavailableReplicas > replicas + || (requireOrdinaryReady + && (readyReplicas != replicas + || availableReplicas != replicas + || unavailableReplicas != 0))) { + throw new InventoryUnavailableException(); + } + rejectSigningMaterialPodSpec(templateSpec); + ContainerConfig container = + findVerifiedContainer( + templateSpec.get("containers"), expected, templateSpec.get("volumes")); + return new DeploymentObservation( + expected.deploymentName(), + expected.deploymentUid(), + resourceVersion, + generation, + replicas, + readyReplicas, + availableReplicas, + container.image(), + container.runtimeConfigSha256()); + } + + private static int observedReplicaCount( + JsonNode status, String fieldName, boolean allowOmittedZero) { + if (!status.has(fieldName)) { + if (allowOmittedZero) { + // Kubernetes omits zero-valued optional status replica counts. This is safe only for the + // owner-bound initial candidate observation; strict readiness still requires both fields. + return 0; + } + throw new InventoryUnavailableException(); + } + return exactInt(status.get(fieldName), 0, 128); + } + + private static List readPods( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + DeploymentObservation deployment, + boolean requireOrdinaryReady) { + String continuation = null; + String listResourceVersion = null; + int pageCount = 0; + List pods = new ArrayList<>(); + Set podUids = new LinkedHashSet<>(); + Set podNames = new LinkedHashSet<>(); + do { + if (++pageCount > MAX_PAGES) { + throw new InventoryUnavailableException(); + } + ApiResponse response = operation.listValidatorPods(inventory, expected, continuation); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + JsonNode root = parseJson(response.body()); + JsonNode metadata = root.get("metadata"); + JsonNode items = root.get("items"); + if (!"v1".equals(text(root.get("apiVersion"))) + || !"PodList".equals(text(root.get("kind"))) + || metadata == null + || items == null + || !items.isArray()) { + throw new InventoryUnavailableException(); + } + String pageVersion = resourceVersion(text(metadata.get("resourceVersion"))); + if (listResourceVersion == null) { + listResourceVersion = pageVersion; + } else if (!listResourceVersion.equals(pageVersion)) { + throw new InventoryUnavailableException(); + } + for (JsonNode item : items) { + if (pods.size() >= MAX_PODS_PER_VALIDATOR) { + throw new InventoryUnavailableException(); + } + PodObservation pod = + parsePod(item, inventory.namespace(), expected, deployment, requireOrdinaryReady); + if (!podUids.add(pod.uid()) || !podNames.add(pod.name())) { + throw new InventoryUnavailableException(); + } + pods.add(pod); + } + JsonNode continueNode = metadata.get("continue"); + if (continueNode == null || continueNode.isNull() || !continueNode.isTextual()) { + continuation = null; + } else { + continuation = continueNode.asText(); + if (continuation.isEmpty()) { + continuation = null; + } else if (continuation.length() > 2048) { + throw new InventoryUnavailableException(); + } + } + } while (continuation != null); + if (pods.size() != expected.replicas()) { + throw new InventoryUnavailableException(); + } + pods.sort(Comparator.comparing(PodObservation::uid)); + List observedPodUids = pods.stream().map(PodObservation::uid).toList(); + List protectedPodUids = + expected.receiverPods().stream().map(ReceiverPodPin::podUid).sorted().toList(); + if (!observedPodUids.equals(protectedPodUids)) { + throw new InventoryUnavailableException(); + } + return List.copyOf(pods); + } + + private static PodObservation parsePod( + JsonNode pod, + String namespace, + ValidatorExpectation expected, + DeploymentObservation deployment, + boolean requireOrdinaryReady) { + if (pod == null || pod.isNull()) { + throw new InventoryUnavailableException(); + } + JsonNode metadata = pod.get("metadata"); + JsonNode spec = pod.get("spec"); + JsonNode status = pod.get("status"); + if (!"v1".equals(text(pod.get("apiVersion"))) + || !"Pod".equals(text(pod.get("kind"))) + || metadata == null + || spec == null + || status == null + || !namespace.equals(text(metadata.get("namespace"))) + || metadata.hasNonNull("deletionTimestamp") + || !labelsMatch(metadata.get("labels"), expected.selector()) + || !"Running".equals(text(status.get("phase")))) { + throw new InventoryUnavailableException(); + } + String name = dnsLabel(text(metadata.get("name"))); + String uid = canonicalUid(text(metadata.get("uid"))); + String podIp = canonicalPodIp(text(status.get("podIP"))); + ReceiverPodPin receiverPin = + expected.receiverPods().stream() + .filter(pin -> pin.podUid().equals(uid)) + .findFirst() + .orElseThrow(InventoryUnavailableException::new); + if (!receiverPin.podIp().equals(podIp)) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + String templateHash = podTemplateHash(metadata.get("labels")); + JsonNode owners = metadata.get("ownerReferences"); + if (owners == null || !owners.isArray() || owners.size() != 1) { + throw new InventoryUnavailableException(); + } + JsonNode owner = owners.get(0); + if (!"apps/v1".equals(text(owner.get("apiVersion"))) + || !"ReplicaSet".equals(text(owner.get("kind"))) + || !Boolean.TRUE.equals(booleanValue(owner.get("controller")))) { + throw new InventoryUnavailableException(); + } + String ownerName = dnsLabel(text(owner.get("name"))); + String ownerUid = canonicalUid(text(owner.get("uid"))); + rejectSigningMaterialPodSpec(spec); + ContainerConfig container = + findVerifiedContainer(spec.get("containers"), expected, spec.get("volumes")); + if (!deployment.image().equals(container.image()) + || !deployment.verifierConfigSha256().equals(container.runtimeConfigSha256())) { + throw new InventoryUnavailableException(); + } + verifyReadyCondition(status.get("conditions"), requireOrdinaryReady); + verifyContainerReady( + status.get("containerStatuses"), expected, deployment.image(), requireOrdinaryReady); + return new PodObservation( + name, + uid, + resourceVersion, + ownerName, + ownerUid, + templateHash, + deployment.image(), + deployment.verifierConfigSha256(), + podIp, + podEndpoint(podIp, expected.receiverPort()), + expected.receiverServiceUri(), + receiverPin.leafSpkiSha256()); + } + + private static List readReplicaSets( + ApiOperation operation, + ProtectedInventory inventory, + ValidatorExpectation expected, + DeploymentObservation deployment, + List pods, + boolean requireOrdinaryReady) { + Map observedOwners = new LinkedHashMap<>(); + Map templateHashes = new LinkedHashMap<>(); + for (PodObservation pod : pods) { + String prior = observedOwners.putIfAbsent(pod.ownerName(), pod.ownerUid()); + String priorHash = templateHashes.putIfAbsent(pod.ownerName(), pod.podTemplateHash()); + if ((prior != null && !prior.equals(pod.ownerUid())) + || (priorHash != null && !priorHash.equals(pod.podTemplateHash()))) { + throw new InventoryUnavailableException(); + } + } + List observations = new ArrayList<>(observedOwners.size()); + for (Map.Entry owner : observedOwners.entrySet()) { + ApiResponse response = operation.readValidatorReplicaSet(inventory, expected, owner.getKey()); + if (response.statusCode() != 200) { + throw new InventoryUnavailableException(); + } + observations.add( + parseReplicaSet( + response.body(), + inventory.namespace(), + expected, + deployment, + owner.getKey(), + owner.getValue(), + templateHashes.get(owner.getKey()), + requireOrdinaryReady)); + } + observations.sort(Comparator.comparing(ReplicaSetObservation::uid)); + return List.copyOf(observations); + } + + private static ReplicaSetObservation parseReplicaSet( + byte[] responseBody, + String namespace, + ValidatorExpectation expected, + DeploymentObservation deployment, + String expectedName, + String expectedUid, + String expectedTemplateHash, + boolean requireOrdinaryReady) { + JsonNode root = parseJson(responseBody); + JsonNode metadata = root.get("metadata"); + JsonNode spec = root.get("spec"); + JsonNode status = root.get("status"); + JsonNode owners = metadata == null ? null : metadata.get("ownerReferences"); + JsonNode selector = spec == null ? null : spec.get("selector"); + JsonNode template = spec == null ? null : spec.get("template"); + JsonNode templateMetadata = template == null ? null : template.get("metadata"); + JsonNode templateSpec = template == null ? null : template.get("spec"); + if (!"apps/v1".equals(text(root.get("apiVersion"))) + || !"ReplicaSet".equals(text(root.get("kind"))) + || metadata == null + || !expectedName.equals(text(metadata.get("name"))) + || !namespace.equals(text(metadata.get("namespace"))) + || !expectedUid.equals(canonicalUid(text(metadata.get("uid")))) + || metadata.hasNonNull("deletionTimestamp") + || owners == null + || !owners.isArray() + || owners.size() != 1 + || spec == null + || status == null + || selector == null + || !replicaSetSelectorMatches( + selector.get("matchLabels"), expected.selector(), expectedTemplateHash) + || (selector.has("matchExpressions") + && selector.get("matchExpressions") != null + && !selector.get("matchExpressions").isNull() + && (!selector.get("matchExpressions").isArray() + || !selector.get("matchExpressions").isEmpty())) + || templateMetadata == null + || !labelsMatch(templateMetadata.get("labels"), expected.selector()) + || !expectedTemplateHash.equals( + text(templateMetadata.get("labels").get("pod-template-hash"))) + || templateSpec == null) { + throw new InventoryUnavailableException(); + } + JsonNode owner = owners.get(0); + if (!"apps/v1".equals(text(owner.get("apiVersion"))) + || !"Deployment".equals(text(owner.get("kind"))) + || !deployment.name().equals(text(owner.get("name"))) + || !deployment.uid().equals(canonicalUid(text(owner.get("uid")))) + || !Boolean.TRUE.equals(booleanValue(owner.get("controller")))) { + throw new InventoryUnavailableException(); + } + String resourceVersion = resourceVersion(text(metadata.get("resourceVersion"))); + long generation = positiveLong(metadata.get("generation")); + int replicas = exactInt(spec.get("replicas"), 1, 128); + int readyReplicas = observedReplicaCount(status, "readyReplicas", !requireOrdinaryReady); + if (positiveLong(status.get("observedGeneration")) != generation + || readyReplicas > replicas + || replicas != expected.replicas() + || (requireOrdinaryReady && readyReplicas != replicas)) { + throw new InventoryUnavailableException(); + } + rejectSigningMaterialPodSpec(templateSpec); + ContainerConfig container = + findVerifiedContainer( + templateSpec.get("containers"), expected, templateSpec.get("volumes")); + if (!deployment.image().equals(container.image()) + || !deployment.verifierConfigSha256().equals(container.runtimeConfigSha256())) { + throw new InventoryUnavailableException(); + } + return new ReplicaSetObservation( + expectedName, + expectedUid, + resourceVersion, + generation, + replicas, + deployment.name(), + deployment.uid(), + expectedTemplateHash, + container.image(), + container.runtimeConfigSha256()); + } + + private static boolean replicaSetSelectorMatches( + JsonNode actual, Map expected, String expectedTemplateHash) { + if (actual == null + || !actual.isObject() + || expectedTemplateHash == null + || actual.size() != expected.size() + 1 + || !expectedTemplateHash.equals(text(actual.get("pod-template-hash")))) { + return false; + } + for (Map.Entry entry : expected.entrySet()) { + if (!entry.getValue().equals(text(actual.get(entry.getKey())))) { + return false; + } + } + return true; + } + + private static String podTemplateHash(JsonNode labels) { + if (labels == null || !labels.isObject()) { + throw new InventoryUnavailableException(); + } + String value = text(labels.get("pod-template-hash")); + if (value == null || !POD_TEMPLATE_HASH.matcher(value).matches()) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static ContainerConfig findVerifiedContainer( + JsonNode containers, ValidatorExpectation expected, JsonNode volumes) { + if (containers == null + || !containers.isArray() + || containers.isEmpty() + || containers.size() > 32) { + throw new InventoryUnavailableException(); + } + JsonNode selected = null; + for (JsonNode container : containers) { + String name = text(container.get("name")); + rejectSigningMaterialEnvironment(container.get("env")); + rejectSigningSecretMounts(container.get("volumeMounts")); + if (expected.containerName().equals(name)) { + if (selected != null) { + throw new InventoryUnavailableException(); + } + selected = container; + } + } + rejectSigningSecretVolumes(volumes); + if (selected == null || !expected.image().equals(text(selected.get("image")))) { + throw new InventoryUnavailableException(); + } + JsonNode env = selected.get("env"); + rejectValidatorEnvFrom(selected.get("envFrom")); + JsonNode configNode = null; + Set environmentNames = new LinkedHashSet<>(); + if (env != null && !env.isNull()) { + if (!env.isArray() || env.size() > 256) { + throw new InventoryUnavailableException(); + } + for (JsonNode variable : env) { + String envName = text(variable.get("name")); + if (envName == null || !environmentNames.add(envName)) { + throw new InventoryUnavailableException(); + } + if (RUNTIME_CONFIG_ENV.equals(envName)) { + if (variable.has("valueFrom") + || !expected.canonicalRuntimeConfig().equals(text(variable.get("value")))) { + throw new InventoryUnavailableException(); + } + configNode = variable; + } + if ("SPRING_APPLICATION_JSON".equals(envName) + || "JAVA_TOOL_OPTIONS".equals(envName) + || "JDK_JAVA_OPTIONS".equals(envName)) { + throw new InventoryUnavailableException(); + } + } + } + if (configNode == null) { + throw new InventoryUnavailableException(); + } + return new ContainerConfig( + expected.image(), + sha256(expected.canonicalRuntimeConfig().getBytes(StandardCharsets.UTF_8))); + } + + /** Reject private signer access anywhere in the observed PodSpec, not only the main container. */ + static void rejectSigningMaterialPodSpec(JsonNode podSpec) { + if (podSpec == null || !podSpec.isObject()) { + throw new InventoryUnavailableException(); + } + for (String field : List.of("containers", "initContainers", "ephemeralContainers")) { + JsonNode containers = podSpec.get(field); + if (containers == null || containers.isNull()) { + continue; + } + if (!containers.isArray() || containers.size() > 32) { + throw new InventoryUnavailableException(); + } + for (JsonNode container : containers) { + if (container == null || !container.isObject()) { + throw new InventoryUnavailableException(); + } + rejectSigningMaterialEnvironment(container.get("env")); + rejectSigningMaterialEnvFrom(container.get("envFrom")); + rejectSigningSecretMounts(container.get("volumeMounts")); + } + } + rejectSigningSecretVolumes(podSpec.get("volumes")); + } + + private static void rejectSigningMaterialEnvFrom(JsonNode envFrom) { + if (envFrom == null || envFrom.isNull()) { + return; + } + if (!envFrom.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode source : envFrom) { + if (source == null || !source.isObject()) { + throw new InventoryUnavailableException(); + } + JsonNode secretRef = source.get("secretRef"); + if (secretRef != null && !secretRef.isNull()) { + if (!secretRef.isObject()) { + throw new InventoryUnavailableException(); + } + if ("jwt-signing-keys".equals(text(secretRef.get("name")))) { + throw new InventoryUnavailableException(); + } + } + } + } + + private static void rejectValidatorEnvFrom(JsonNode envFrom) { + if (envFrom == null || envFrom.isNull()) { + return; + } + if (!envFrom.isArray() || envFrom.size() != 0) { + throw new InventoryUnavailableException(); + } + } + + private static void rejectSigningMaterialEnvironment(JsonNode env) { + if (env == null || env.isNull()) { + return; + } + if (!env.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode variable : env) { + String name = text(variable.get("name")); + if (name != null + && (name.equals("FIREMUD_AUTH_JWT_SECRET") + || name.equals("FIREMUD_AUTH_JWT_SECRET_PATH") + || name.contains("JWT_HMAC") + || name.contains("JWT_SIGNING_KEY"))) { + throw new InventoryUnavailableException(); + } + JsonNode valueFrom = variable.get("valueFrom"); + JsonNode secretKeyRef = valueFrom == null ? null : valueFrom.get("secretKeyRef"); + if (secretKeyRef != null && !secretKeyRef.isNull()) { + String secretName = text(secretKeyRef.get("name")); + if ("jwt-signing-keys".equals(secretName)) { + throw new InventoryUnavailableException(); + } + } + } + } + + private static void rejectSigningSecretMounts(JsonNode mounts) { + if (mounts == null || mounts.isNull()) { + return; + } + if (!mounts.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode mount : mounts) { + String name = text(mount.get("name")); + String path = text(mount.get("mountPath")); + if ("jwt-signing-keys".equals(name) + || (path != null && path.startsWith("/var/run/secrets/firemud/jwt"))) { + throw new InventoryUnavailableException(); + } + } + } + + private static void rejectSigningSecretVolumes(JsonNode volumes) { + if (volumes == null || volumes.isNull()) { + return; + } + if (!volumes.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode volume : volumes) { + if (volume == null || !volume.isObject()) { + throw new InventoryUnavailableException(); + } + String name = text(volume.get("name")); + JsonNode secret = volume.get("secret"); + if ("jwt-signing-keys".equals(name) + || (secret != null + && !secret.isNull() + && "jwt-signing-keys".equals(text(secret.get("secretName"))))) { + throw new InventoryUnavailableException(); + } + JsonNode projected = volume.get("projected"); + if (projected != null && !projected.isNull()) { + JsonNode sources = projected.get("sources"); + if (!projected.isObject() || sources == null || !sources.isArray()) { + throw new InventoryUnavailableException(); + } + for (JsonNode source : sources) { + if (source == null || !source.isObject()) { + throw new InventoryUnavailableException(); + } + JsonNode projectedSecret = source.get("secret"); + if (projectedSecret != null && !projectedSecret.isNull()) { + if (!projectedSecret.isObject()) { + throw new InventoryUnavailableException(); + } + if ("jwt-signing-keys".equals(text(projectedSecret.get("name")))) { + throw new InventoryUnavailableException(); + } + } + } + } + } + } + + private static void verifyReadyCondition(JsonNode conditions, boolean requireOrdinaryReady) { + if (conditions == null || !conditions.isArray() || conditions.size() > 64) { + throw new InventoryUnavailableException(); + } + boolean ready = false; + for (JsonNode condition : conditions) { + if ("Ready".equals(text(condition.get("type")))) { + String status = text(condition.get("status")); + if (ready || (!"True".equals(status) && !"False".equals(status))) { + throw new InventoryUnavailableException(); + } + if (requireOrdinaryReady && !"True".equals(status)) { + throw new InventoryUnavailableException(); + } + ready = true; + } + } + if (!ready) { + throw new InventoryUnavailableException(); + } + } + + private static void verifyContainerReady( + JsonNode statuses, + ValidatorExpectation expected, + String expectedImage, + boolean requireOrdinaryReady) { + if (statuses == null || !statuses.isArray() || statuses.isEmpty() || statuses.size() > 32) { + throw new InventoryUnavailableException(); + } + JsonNode found = null; + for (JsonNode status : statuses) { + if (expected.containerName().equals(text(status.get("name")))) { + if (found != null) { + throw new InventoryUnavailableException(); + } + found = status; + } + } + String imageId = found == null ? null : text(found.get("imageID")); + String digest = imageDigest(imageId); + String expectedDigest = expected.image().substring(expected.image().lastIndexOf('@') + 1); + Boolean ready = found == null ? null : booleanValue(found.get("ready")); + if (found == null + || ready == null + || (requireOrdinaryReady && !ready) + || !expectedDigest.equals(digest)) { + throw new InventoryUnavailableException(); + } + } + + private static InventorySnapshot createSnapshot( + ProtectedInventory expected, + List validators, + Instant observedAt, + ObservationContext observationContext) { + List sorted = + validators.stream() + .sorted(Comparator.comparing(ValidatorObservation::validatorId)) + .toList(); + Map preimage = new LinkedHashMap<>(); + preimage.put("domain", INVENTORY_DOMAIN); + // Acquisition time is independently bounded freshness metadata, not inventory content. The + // v2 digest must remain stable across an unchanged later reread while retaining this time in + // the immutable snapshot row and in the in-memory observation. + preimage.put("environmentId", expected.environmentId()); + preimage.put("clusterId", expected.clusterId()); + preimage.put("clusterIncarnationUid", expected.expectedClusterIncarnationUid()); + preimage.put("namespace", expected.namespace()); + preimage.put("namespaceUid", expected.expectedNamespaceUid()); + preimage.put("apiBindingRevision", expected.apiBindingRevision()); + preimage.put("apiBindingDigest", expected.apiBindingDigest()); + preimage.put("inventoryBindingRevision", expected.configRevision()); + preimage.put("inventoryBindingDigest", expected.bindingDigest()); + if (observationContext != null) { + preimage.put("observationContext", observationContext.canonicalMap()); + } + preimage.put( + "validators", + sorted.stream().map(AccountJwtValidatorInventorySource::validatorMap).toList()); + byte[] canonicalSnapshot = canonicalBytes(preimage); + if (canonicalSnapshot.length > MAX_CANONICAL_SNAPSHOT_BYTES) { + throw new InventoryUnavailableException(); + } + String digest = sha256(canonicalSnapshot); + return new InventorySnapshot( + observedAt, + expected.environmentId(), + expected.clusterId(), + expected.expectedClusterIncarnationUid(), + expected.namespace(), + expected.expectedNamespaceUid(), + expected.apiBindingRevision(), + expected.apiBindingDigest(), + expected.configRevision(), + expected.bindingDigest(), + sorted, + Optional.ofNullable(observationContext), + canonicalSnapshot, + digest); + } + + private static Map validatorMap(ValidatorObservation validator) { + 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(AccountJwtValidatorInventorySource::podMap).toList()); + result.put("receiverServiceUri", validator.pods().getFirst().receiverServiceUri()); + result.put("receiverPort", validator.pods().getFirst().endpoint().getPort()); + result.put( + "replicaSets", + validator.replicaSets().stream() + .map(AccountJwtValidatorInventorySource::replicaSetMap) + .toList()); + return result; + } + + private static Map replicaSetMap(ReplicaSetObservation replicaSet) { + return Map.of( + "name", replicaSet.name(), + "uid", replicaSet.uid(), + "resourceVersion", replicaSet.resourceVersion(), + "generation", Long.toString(replicaSet.generation()), + "replicas", Integer.toString(replicaSet.replicas()), + "ownerDeploymentName", replicaSet.ownerDeploymentName(), + "ownerDeploymentUid", replicaSet.ownerDeploymentUid(), + "podTemplateHash", replicaSet.podTemplateHash(), + "image", replicaSet.image(), + "verifierConfigSha256", replicaSet.verifierConfigSha256()); + } + + private static Map podMap(PodObservation pod) { + return 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())); + } + + private static URI podEndpoint(String podIp, int port) { + String host = podIp.indexOf(':') >= 0 ? "[" + podIp + "]" : podIp; + return URI.create("grpcs://" + host + ":" + port); + } + + private static String canonicalPodIp(String value) { + try { + return AccountJwtValidatorInventoryBinding.canonicalPodIp(value); + } catch (RuntimeException failure) { + throw new InventoryUnavailableException(); + } + } + + private static boolean selectorMatches(JsonNode actual, Map expected) { + if (actual == null || !actual.isObject() || actual.size() != expected.size()) { + return false; + } + return labelsMatch(actual, expected); + } + + private static boolean labelsMatch(JsonNode labels, Map expected) { + if (labels == null || !labels.isObject()) { + return false; + } + for (Map.Entry entry : expected.entrySet()) { + if (!entry.getValue().equals(text(labels.get(entry.getKey())))) { + return false; + } + } + return true; + } + + private static JsonNode parseJson(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > 1024 * 1024) { + throw new InventoryUnavailableException(); + } + try { + JsonNode parsed = JSON.readTree(decodeUtf8(bytes)); + if (parsed == null || !parsed.isObject()) { + throw new InventoryUnavailableException(); + } + return parsed; + } catch (InventoryUnavailableException failure) { + throw failure; + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private static byte[] canonicalBytes(Object value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private static String imageDigest(String imageId) { + if (imageId == null) { + throw new InventoryUnavailableException(); + } + int marker = imageId.lastIndexOf("sha256:"); + if (marker < 0) { + throw new InventoryUnavailableException(); + } + String digest = imageId.substring(marker); + if (!IMAGE_DIGEST.matcher(digest).matches()) { + throw new InventoryUnavailableException(); + } + return digest; + } + + private static String canonicalUid(String value) { + if (value == null || !UID.matcher(value).matches() || value.startsWith("00000000-")) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static String resourceVersion(String value) { + if (value == null || !RESOURCE_VERSION.matcher(value).matches()) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static String dnsLabel(String value) { + if (value == null || !value.matches("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?")) { + throw new InventoryUnavailableException(); + } + return value; + } + + private static long positiveLong(JsonNode node) { + long value = exactLong(node, 1L, Long.MAX_VALUE); + return value; + } + + private static int exactInt(JsonNode node, int minimum, int maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToLong()) { + throw new InventoryUnavailableException(); + } + long value = node.longValue(); + if (value < minimum || value > maximum) { + throw new InventoryUnavailableException(); + } + return (int) value; + } + + private static long exactLong(JsonNode node, long minimum, long maximum) { + if (node == null || !node.isIntegralNumber() || !node.canConvertToLong()) { + throw new InventoryUnavailableException(); + } + long value = node.longValue(); + if (value < minimum || value > maximum) { + throw new InventoryUnavailableException(); + } + return value; + } + + @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 text(JsonNode node) { + return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null; + } + + 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 failure) { + throw new InventoryUnavailableException(); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new InventoryUnavailableException(); + } + } + + private record ContainerConfig(String image, String runtimeConfigSha256) {} + + private record DeploymentObservation( + String name, + String uid, + String resourceVersion, + long generation, + int replicas, + int readyReplicas, + int availableReplicas, + String image, + String verifierConfigSha256) {} + + public record ReplicaSetObservation( + String name, + String uid, + String resourceVersion, + long generation, + int replicas, + String ownerDeploymentName, + String ownerDeploymentUid, + String podTemplateHash, + String image, + String verifierConfigSha256) {} + + /** No Pod or Kubernetes API body is retained, only closed non-secret identity fields. */ + public record PodObservation( + String name, + String uid, + String resourceVersion, + String ownerName, + String ownerUid, + String podTemplateHash, + String image, + String verifierConfigSha256, + String podIp, + URI endpoint, + String receiverServiceUri, + String leafSpkiSha256) {} + + public record ValidatorObservation( + String validatorId, + String deploymentName, + String deploymentUid, + long deploymentGeneration, + String deploymentResourceVersion, + int replicas, + String image, + String verifierConfigSha256, + int maxCacheAgeSeconds, + List profiles, + List pods, + List replicaSets) { + public ValidatorObservation { + profiles = List.copyOf(profiles); + pods = List.copyOf(pods); + replicaSets = List.copyOf(replicaSets); + } + } + + /** + * Account-owner-derived context for one validator inventory acquisition. Bootstrap candidate + * observation is available only for the exact current operation whose active signer fence is + * absent; the repository re-derives and checks this context before consuming the snapshot. + */ + public record ObservationContext( + ObservationPurpose purpose, UUID operationId, String operationDigest) { + public ObservationContext { + Objects.requireNonNull(purpose, "Inventory observation purpose is required"); + Objects.requireNonNull(operationId, "Inventory observation operation is required"); + if (operationId.version() != 4 + || operationId.variant() != 2 + || operationDigest == null + || !OPERATION_DIGEST.matcher(operationDigest).matches()) { + throw new InventoryUnavailableException(); + } + } + + public boolean isInitialNoActiveSigner() { + return purpose == ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES; + } + + private Map canonicalMap() { + return Map.of( + "purpose", purpose.name(), + "operationId", operationId.toString(), + "operationDigest", operationDigest); + } + } + + public enum ObservationPurpose { + STRICT_READY, + INITIAL_NO_ACTIVE_SIGNER_CANDIDATES; + + private boolean requiresOrdinaryReady() { + return this == STRICT_READY; + } + } + + public static final class InventorySnapshot { + private final Instant observedAt; + private final String environmentId; + private final String clusterId; + private final String clusterIncarnationUid; + private final String namespace; + private final String namespaceUid; + private final String apiBindingRevision; + private final String apiBindingDigest; + private final String inventoryBindingRevision; + private final String inventoryBindingDigest; + private final List validators; + private final Optional observationContext; + private final byte[] canonicalBytes; + private final String digest; + + private InventorySnapshot( + Instant observedAt, + String environmentId, + String clusterId, + String clusterIncarnationUid, + String namespace, + String namespaceUid, + String apiBindingRevision, + String apiBindingDigest, + String inventoryBindingRevision, + String inventoryBindingDigest, + List validators, + Optional observationContext, + byte[] canonicalBytes, + String digest) { + this.observedAt = Objects.requireNonNull(observedAt); + this.environmentId = Objects.requireNonNull(environmentId); + this.clusterId = Objects.requireNonNull(clusterId); + this.clusterIncarnationUid = Objects.requireNonNull(clusterIncarnationUid); + this.namespace = Objects.requireNonNull(namespace); + this.namespaceUid = Objects.requireNonNull(namespaceUid); + this.apiBindingRevision = Objects.requireNonNull(apiBindingRevision); + this.apiBindingDigest = Objects.requireNonNull(apiBindingDigest); + this.inventoryBindingRevision = Objects.requireNonNull(inventoryBindingRevision); + this.inventoryBindingDigest = Objects.requireNonNull(inventoryBindingDigest); + this.validators = List.copyOf(validators); + this.observationContext = Objects.requireNonNull(observationContext); + this.canonicalBytes = Objects.requireNonNull(canonicalBytes).clone(); + this.digest = Objects.requireNonNull(digest); + if (this.canonicalBytes.length == 0 + || this.canonicalBytes.length > MAX_CANONICAL_SNAPSHOT_BYTES + || !sha256(this.canonicalBytes).equals(digest)) { + throw new InventoryUnavailableException(); + } + } + + public Instant observedAt() { + return observedAt; + } + + public String environmentId() { + return environmentId; + } + + public String clusterId() { + return clusterId; + } + + public String clusterIncarnationUid() { + return clusterIncarnationUid; + } + + public String namespace() { + return namespace; + } + + public String namespaceUid() { + return namespaceUid; + } + + public String apiBindingRevision() { + return apiBindingRevision; + } + + public String apiBindingDigest() { + return apiBindingDigest; + } + + public String inventoryBindingRevision() { + return inventoryBindingRevision; + } + + public String inventoryBindingDigest() { + return inventoryBindingDigest; + } + + public List validators() { + return validators; + } + + public Optional observationContext() { + return observationContext; + } + + public byte[] canonicalBytes() { + return canonicalBytes.clone(); + } + + public String digest() { + return digest; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof InventorySnapshot that)) return false; + return observedAt.equals(that.observedAt) + && environmentId.equals(that.environmentId) + && clusterId.equals(that.clusterId) + && clusterIncarnationUid.equals(that.clusterIncarnationUid) + && namespace.equals(that.namespace) + && namespaceUid.equals(that.namespaceUid) + && apiBindingRevision.equals(that.apiBindingRevision) + && apiBindingDigest.equals(that.apiBindingDigest) + && inventoryBindingRevision.equals(that.inventoryBindingRevision) + && inventoryBindingDigest.equals(that.inventoryBindingDigest) + && validators.equals(that.validators) + && observationContext.equals(that.observationContext) + && java.util.Arrays.equals(canonicalBytes, that.canonicalBytes) + && digest.equals(that.digest); + } + + @Override + public int hashCode() { + return 31 + * Objects.hash( + observedAt, + environmentId, + clusterId, + clusterIncarnationUid, + namespace, + namespaceUid, + apiBindingRevision, + apiBindingDigest, + inventoryBindingRevision, + inventoryBindingDigest, + validators, + observationContext, + digest) + + java.util.Arrays.hashCode(canonicalBytes); + } + } + + public static final class InventoryUnavailableException extends RuntimeException { + public InventoryUnavailableException() { + super("Account validator inventory is unavailable or inconsistent"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java new file mode 100644 index 0000000000..a46894c1a8 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundle.java @@ -0,0 +1,1446 @@ +package net.firedevops.firemud.accountservice.service.session; + +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.security.GeneralSecurityException; +import java.security.KeyFactory; +import java.security.MessageDigest; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.Signature; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.RSAPublicKeySpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.IdentityHashMap; +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.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.PlayerBootstrapJwtProfileValidator; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Bounded Account-local parser and correspondence proof for the interim mounted JWT signer. + * + *

This class exposes no general private-key operation or caller-facing token response. Its + * package-private signing operations are closed readiness probes and the exact Account-owned + * initial Game Session delegation candidate; compact bytes are delivered only to an owner callback + * and wiped after it returns. Local correspondence alone proves no lifecycle or authorization. + */ +public final class AccountMountedJwtSignerBundle { + public static final int MAX_PRIVATE_BUNDLE_BYTES = 64 * 1024; + public static final int MAX_PUBLIC_JWKS_BYTES = 256 * 1024; + private static final int MAX_READINESS_COMPACT_JWT_BYTES = 16 * 1024; + private static final int MAX_DELEGATION_COMPACT_JWT_BYTES = + GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES; + private static final int MAX_RSA_BITS = 16_384; + private static final int MIN_RSA_BITS = 3_072; + private static final int MAX_JWKS_KEYS = 64; + private static final int MAX_PRIVATE_KEY_DER_BYTES = 16 * 1024; + private static final int CHALLENGE_NONCE_BYTES = 32; + private static final SecureRandom CHALLENGE_RANDOM = new SecureRandom(); + private static final String ALGORITHM = "RS256"; + static final String READINESS_CANARY_PROFILE = "account-jwt-readiness-canary"; + static final String READINESS_CANARY_TYPE = "account_jwt_readiness_canary"; + static final String READINESS_CANARY_AUDIENCE = "firemud-account-jwt-readiness"; + static final String READINESS_VALIDATOR_ID = "account-service"; + static final String GAME_SESSION_VALIDATOR_ID = "game-session-service"; + static final String REPRESENTATIVE_PROFILE = GameSessionAccountDelegationProfile.PROFILE; + static final String REPRESENTATIVE_AUDIENCE = GameSessionAccountDelegationProfile.AUDIENCE; + private static final String ISSUER = "firemud-account-service"; + private static final String RESERVED_SUBJECT = "00000000-0000-4000-8000-000000000001"; + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Pattern GENERATION = Pattern.compile("[1-9][0-9]{0,63}"); + private static final Pattern FINGERPRINT = Pattern.compile("[0-9a-f]{64}"); + private static final Set PRIVATE_BUNDLE_FIELDS = + Set.of( + "version", + "environmentId", + "clusterId", + "namespace", + "operationId", + "generation", + "kid", + "algorithm", + "privateKeyPkcs8", + "publicKeyFingerprint"); + private static final Set JWKS_FIELDS = Set.of("keys"); + private static final Set JWK_FIELDS = + Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e"); + private static final byte[] CHALLENGE_DOMAIN = + new byte[] { + 0, 'F', 'i', 'r', 'e', 'M', 'U', 'D', '/', 'A', 'c', 'c', 'o', 'u', 'n', 't', '/', 'm', 'o', + 'u', 'n', 't', 'e', 'd', '-', 's', 'i', 'g', 'n', 'e', 'r', '-', 'c', 'o', 'r', 'r', 'e', + 's', 'p', 'o', 'n', 'd', 'e', 'n', 'c', 'e', '/', 'v', '1', 0 + }; + private static final JsonMapper STRICT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private AccountMountedJwtSignerBundle() {} + + /** + * Reads the explicitly configured Account-only private projection and public JWKS projection. + * Relative file paths must remain beneath their respective configured mount roots. Kubernetes + * projected-volume symlinks are accepted only when their resolved regular files stay beneath + * those roots. + */ + public static LocalObservation observeMounted( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity) { + return readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity) + .observation(); + } + + /** + * Signs only one fixed non-authorizing canary or one fixed-shape representative profile, passes + * the exact compact bytes transiently to the Account-owned callback, then wipes them and returns + * only their digest plus immutable planned identity. This method is package-private so no route, + * ordinary issuer, or other service can request arbitrary JWT signing from the mounted pending + * key. + */ + static SignedProbeDigest signReadinessProbeDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + ReadinessProbeSigningSpec spec, + ProbeDeliveryConsumer deliveryConsumer) { + Objects.requireNonNull(spec, "Readiness probe signing specification is required"); + Objects.requireNonNull(deliveryConsumer, "Readiness probe delivery consumer is required"); + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + if (!mounted.observation().expectedIdentity().equals(expectedIdentity) + || !spec.targetGeneration().equals(expectedIdentity.generation()) + || !spec.targetKid().equals(expectedIdentity.kid())) { + throw invalid(); + } + + byte[] header = null; + byte[] claims = null; + byte[] encodedHeader = null; + byte[] encodedClaims = null; + byte[] signingInput = null; + byte[] signatureBytes = null; + byte[] encodedSignature = null; + byte[] compactBytes = null; + byte[] tokenDigest = null; + byte[] deliveryBytes = null; + try { + SignedProbeDigest result; + try { + Map headerFields = new LinkedHashMap<>(); + headerFields.put("alg", ALGORITHM); + headerFields.put("kid", expectedIdentity.kid()); + headerFields.put("typ", "JWT"); + header = canonicalJsonBytes(headerFields); + claims = canonicalJsonBytes(readinessClaims(spec)); + encodedHeader = Base64.getUrlEncoder().withoutPadding().encode(header); + encodedClaims = Base64.getUrlEncoder().withoutPadding().encode(claims); + signingInput = joinCompactParts(encodedHeader, encodedClaims, null); + + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(mounted.privateKey()); + signer.update(signingInput); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(mounted.publicKey()); + verifier.update(signingInput); + if (!verifier.verify(signatureBytes)) { + throw invalid(); + } + encodedSignature = Base64.getUrlEncoder().withoutPadding().encode(signatureBytes); + compactBytes = joinCompactParts(encodedHeader, encodedClaims, encodedSignature); + if (compactBytes.length > MAX_READINESS_COMPACT_JWT_BYTES) { + throw invalid(); + } + tokenDigest = MessageDigest.getInstance("SHA-256").digest(compactBytes); + result = + new SignedProbeDigest( + expectedIdentity.operationId(), + spec.validatorId(), + spec.probeKind(), + spec.tokenProfile(), + spec.audience(), + spec.jti(), + expectedIdentity.generation(), + expectedIdentity.kid(), + expectedIdentity.publicKeyFingerprint(), + spec.issuedAtEpochSecond(), + spec.expiresAtEpochSecond(), + java.util.HexFormat.of().formatHex(tokenDigest)); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + throw invalid(); + } + deliveryBytes = compactBytes.clone(); + try { + deliveryConsumer.persistAttemptAndDeliver(result, deliveryBytes); + } catch (RuntimeException failure) { + throw invalid(); + } + if (!sha256(deliveryBytes).equals(result.compactTokenSha256())) { + throw invalid(); + } + return result; + } finally { + wipe(header); + wipe(claims); + wipe(encodedHeader); + wipe(encodedClaims); + wipe(signingInput); + wipe(signatureBytes); + wipe(encodedSignature); + wipe(compactBytes); + wipe(tokenDigest); + wipe(deliveryBytes); + } + } + + /** + * Signs only the exact Account-owned, initial Game Session delegation claim shape with the + * already committed signer identity supplied by the owner service. The compact credential is + * passed once to the Account persistence callback and wiped before this method returns. + */ + static SignedDelegationDigest signCommittedGameplayDelegationDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + DelegationSigningSpec spec, + DelegationCandidateConsumer candidateConsumer) { + Objects.requireNonNull(spec, "Gameplay delegation signing specification is required"); + Objects.requireNonNull(candidateConsumer, "Gameplay delegation owner callback is required"); + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + AccountGameplayDelegationPendingIdentity identity = spec.identity(); + AccountAuthoritySnapshot authority = spec.authoritySnapshot(); + if (!mounted.observation().expectedIdentity().equals(expectedIdentity) + || !authority.accountId().equals(identity.accountId())) { + throw invalid(); + } + + byte[] header = null; + byte[] claims = null; + byte[] encodedHeader = null; + byte[] encodedClaims = null; + byte[] signingInput = null; + byte[] signatureBytes = null; + byte[] encodedSignature = null; + byte[] compactBytes = null; + byte[] tokenDigest = null; + byte[] callbackBytes = null; + try { + Map headerFields = new LinkedHashMap<>(); + headerFields.put("alg", ALGORITHM); + headerFields.put("kid", expectedIdentity.kid()); + headerFields.put("typ", "JWT"); + header = canonicalJsonBytes(headerFields); + Map delegation = delegationClaims(identity, authority); + if (spec.bound().isPresent()) { + var bound = spec.bound().orElseThrow(); + delegation.put("tenantId", bound.tenantId()); + delegation.put("authorityTuple", mergeBoundAuthorityTuple(authority, bound)); + delegation.put("membershipVersion", bound.membershipVersion()); + } + net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator + .validateClaims(delegation); + claims = canonicalJsonBytes(delegation); + encodedHeader = Base64.getUrlEncoder().withoutPadding().encode(header); + encodedClaims = Base64.getUrlEncoder().withoutPadding().encode(claims); + signingInput = joinCompactParts(encodedHeader, encodedClaims, null); + + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(mounted.privateKey()); + signer.update(signingInput); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(mounted.publicKey()); + verifier.update(signingInput); + if (!verifier.verify(signatureBytes)) { + throw invalid(); + } + encodedSignature = Base64.getUrlEncoder().withoutPadding().encode(signatureBytes); + compactBytes = joinCompactParts(encodedHeader, encodedClaims, encodedSignature); + if (compactBytes.length > MAX_DELEGATION_COMPACT_JWT_BYTES) { + throw invalid(); + } + tokenDigest = MessageDigest.getInstance("SHA-256").digest(compactBytes); + SignedDelegationDigest digest = + new SignedDelegationDigest( + identity.operationId(), + identity.requestId(), + identity.tokenJti(), + expectedIdentity.operationId(), + expectedIdentity.generation(), + expectedIdentity.kid(), + expectedIdentity.publicKeyFingerprint(), + identity.issuedAtEpochSecond(), + identity.notBeforeEpochSecond(), + identity.expiresAtEpochSecond(), + java.util.HexFormat.of().formatHex(tokenDigest)); + callbackBytes = compactBytes.clone(); + try { + candidateConsumer.bindExactCandidate(digest, callbackBytes); + } catch (RuntimeException failure) { + // Callback exception chains must never retain the transient compact credential. + throw invalid(); + } + if (!sha256(callbackBytes).equals(digest.compactTokenSha256())) { + throw invalid(); + } + return digest; + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + throw invalid(); + } finally { + wipe(header); + wipe(claims); + wipe(encodedHeader); + wipe(encodedClaims); + wipe(signingInput); + wipe(signatureBytes); + wipe(encodedSignature); + wipe(compactBytes); + wipe(tokenDigest); + wipe(callbackBytes); + } + } + + /** + * Distinct control-ui entry, available only to the Account owner. The owner must have retained + * genuine primary authentication and exact committed signer evidence before calling outside SQL + * locks. Mounted correspondence alone supplies neither authority nor permission to deliver. + */ + static String signCommittedControlUiDigest( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity, + AccountControlUiSigningSpec spec, + java.util.function.BiConsumer exactCandidateConsumer) { + Objects.requireNonNull(spec); + Objects.requireNonNull(exactCandidateConsumer); + if (org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) { + throw new IllegalStateException("Control-ui signing must occur outside owner SQL locks"); + } + VerifiedMountedSigner mounted = + readAndVerifyMounted( + privateMountRoot, privateBundlePath, publicMountRoot, publicJwksPath, expectedIdentity); + byte[] header = null; + byte[] claims = null; + byte[] input = null; + byte[] signature = null; + byte[] compact = null; + byte[] callback = null; + try { + ControlUiJwtProfileValidator.validateClaims(spec.claims(), 1); + header = + canonicalJsonBytes(Map.of("alg", ALGORITHM, "kid", expectedIdentity.kid(), "typ", "JWT")); + claims = canonicalJsonBytes(spec.claims()); + input = + joinCompactParts( + Base64.getUrlEncoder().withoutPadding().encode(header), + Base64.getUrlEncoder().withoutPadding().encode(claims), + null); + int signatureLength = (mounted.publicKey().getModulus().bitLength() + 7) / 8; + int encodedSignatureLength = (signatureLength * 8 + 5) / 6; + if (input.length + 1 + encodedSignatureLength > MAX_READINESS_COMPACT_JWT_BYTES) { + throw invalid(); + } + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(mounted.privateKey()); + signer.update(input); + signature = signer.sign(); + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(mounted.publicKey()); + verifier.update(input); + if (!verifier.verify(signature)) { + throw invalid(); + } + compact = + joinCompactParts( + Base64.getUrlEncoder().withoutPadding().encode(header), + Base64.getUrlEncoder().withoutPadding().encode(claims), + Base64.getUrlEncoder().withoutPadding().encode(signature)); + if (compact.length > MAX_READINESS_COMPACT_JWT_BYTES) { + throw invalid(); + } + String digest = sha256(compact); + callback = compact.clone(); + exactCandidateConsumer.accept(digest, callback); + if (!digest.equals(sha256(callback))) { + throw invalid(); + } + return digest; + } catch (Exception failure) { + // Never retain a credential in a callback exception chain. + throw invalid(); + } finally { + wipe(header); + wipe(claims); + wipe(input); + wipe(signature); + wipe(compact); + wipe(callback); + } + } + + private static Map delegationClaims( + AccountGameplayDelegationPendingIdentity identity, AccountAuthoritySnapshot authority) { + if (!authority.accountId().equals(identity.accountId())) { + throw invalid(); + } + Map claims = new LinkedHashMap<>(); + claims.put("iss", ISSUER); + claims.put("sub", authority.accountId().toString()); + claims.put("jti", identity.tokenJti().toString()); + claims.put("accountId", authority.accountId().toString()); + claims.put("aud", GameSessionAccountDelegationProfile.AUDIENCE); + claims.put("iat", identity.issuedAtEpochSecond()); + claims.put("nbf", identity.notBeforeEpochSecond()); + claims.put("exp", identity.expiresAtEpochSecond()); + claims.put("tokenGeneration", "1"); + claims.put( + "authorityTuple", + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff())); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", Long.toString(authority.issuanceFence())); + return claims; + } + + private static Map mergeBoundAuthorityTuple( + AccountAuthoritySnapshot authority, BoundDelegationClaims bound) { + Map supplied = bound.authorityTuple(); + Map canonical = + GameSessionAccountDelegationProfile.authorityTuple( + authority.issuerGeneration(), + authority.accountGeneration(), + authority.accountSecurityCutoff()); + if (!Objects.equals(supplied.get("issuerAuthGeneration"), canonical.get("issuerAuthGeneration")) + || !Objects.equals( + supplied.get("accountAuthorityGeneration"), canonical.get("accountAuthorityGeneration")) + || supplied.containsKey("accountSecurityCutoff") + != canonical.containsKey("accountSecurityCutoff") + || !Objects.equals( + supplied.get("accountSecurityCutoff"), canonical.get("accountSecurityCutoff"))) { + throw invalid(); + } + + Map merged = new LinkedHashMap<>(canonical); + merged.put("tenantAuthorityGeneration", supplied.get("tenantAuthorityGeneration")); + merged.put("membershipAuthorityGeneration", supplied.get("membershipAuthorityGeneration")); + if (supplied.containsKey("tenantBillingCutoff")) { + merged.put("tenantBillingCutoff", supplied.get("tenantBillingCutoff")); + } + return merged; + } + + private static Map immutableAuthorityTupleCopy(Map source) { + Object copied = immutableJsonValueCopy(source, new IdentityHashMap<>()); + if (!(copied instanceof Map copiedMap)) { + throw invalid(); + } + Map result = new LinkedHashMap<>(); + for (Map.Entry entry : copiedMap.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw invalid(); + } + result.put(key, entry.getValue()); + } + return Collections.unmodifiableMap(result); + } + + private static Object immutableJsonValueCopy( + Object value, IdentityHashMap active) { + if (value instanceof Map source) { + if (active.put(source, Boolean.TRUE) != null) { + throw invalid(); + } + try { + Map copy = new LinkedHashMap<>(); + for (Map.Entry entry : source.entrySet()) { + if (!(entry.getKey() instanceof String key)) { + throw invalid(); + } + copy.put(key, immutableJsonValueCopy(entry.getValue(), active)); + } + return Collections.unmodifiableMap(copy); + } finally { + active.remove(source); + } + } + if (value instanceof List source) { + if (active.put(source, Boolean.TRUE) != null) { + throw invalid(); + } + try { + List copy = new java.util.ArrayList<>(source.size()); + for (Object item : source) { + copy.add(immutableJsonValueCopy(item, active)); + } + return Collections.unmodifiableList(copy); + } finally { + active.remove(source); + } + } + return value; + } + + private static VerifiedMountedSigner readAndVerifyMounted( + Path privateMountRoot, + Path privateBundlePath, + Path publicMountRoot, + Path publicJwksPath, + ExpectedIdentity expectedIdentity) { + byte[] privateBytes = null; + try { + if (expectedIdentity == null) { + throw invalid(); + } + validateIdentity(expectedIdentity); + Path privateFile = resolveMountedFile(privateMountRoot, privateBundlePath); + Path publicFile = resolveMountedFile(publicMountRoot, publicJwksPath); + privateBytes = readBounded(privateFile, MAX_PRIVATE_BUNDLE_BYTES); + ParsedPrivateBundle privateBundle = parsePrivateBundle(privateBytes); + Arrays.fill(privateBytes, (byte) 0); + privateBytes = null; + requireExpectedIdentity(privateBundle.identity(), expectedIdentity); + + byte[] publicBytes = readBounded(publicFile, MAX_PUBLIC_JWKS_BYTES); + Map publicKeys; + try { + publicKeys = parsePublicJwks(publicBytes); + } finally { + Arrays.fill(publicBytes, (byte) 0); + } + RSAPublicKey publicKey = publicKeys.get(expectedIdentity.kid()); + if (publicKey == null + || !publicKey.getModulus().equals(privateBundle.publicModulus()) + || !publicKey.getPublicExponent().equals(privateBundle.publicExponent())) { + throw invalid(); + } + String fingerprint = fingerprint(publicKey.getModulus(), publicKey.getPublicExponent()); + if (!fingerprint.equals(expectedIdentity.publicKeyFingerprint()) + || !fingerprint.equals(privateBundle.identity().publicKeyFingerprint())) { + throw invalid(); + } + proveCorrespondence(privateBundle.privateKey(), publicKey); + return new VerifiedMountedSigner( + new LocalObservation(expectedIdentity, fingerprint), + privateBundle.privateKey(), + publicKey); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (Exception ex) { + // Do not retain path, parser, key, or mounted-file details in a caller-visible failure. + throw invalid(); + } finally { + if (privateBytes != null) { + Arrays.fill(privateBytes, (byte) 0); + } + } + } + + private static Map readinessClaims(ReadinessProbeSigningSpec spec) { + Map claims = new LinkedHashMap<>(); + claims.put("iss", ISSUER); + claims.put("sub", RESERVED_SUBJECT); + claims.put("jti", spec.jti().toString()); + claims.put("aud", spec.audience()); + claims.put("iat", spec.issuedAtEpochSecond()); + claims.put("nbf", spec.issuedAtEpochSecond()); + claims.put("exp", spec.expiresAtEpochSecond()); + if (spec.probeKind() == ProbeKind.CANARY) { + claims.put("tokenProfile", READINESS_CANARY_PROFILE); + claims.put("tokenType", READINESS_CANARY_TYPE); + return claims; + } + if (ControlUiJwtProfileValidator.PROFILE.equals(spec.tokenProfile()) + || PlayerBootstrapJwtProfileValidator.PROFILE.equals(spec.tokenProfile())) { + claims.put("scopedRoles", Map.of()); + } + boolean decimalCounters = + GameSessionAccountDelegationProfile.PROFILE.equals(spec.tokenProfile()); + Object initialCounter = decimalCounters ? "1" : 1L; + claims.put("accountId", RESERVED_SUBJECT); + claims.put("tokenGeneration", initialCounter); + Map authorityTuple = new LinkedHashMap<>(); + authorityTuple.put("issuerAuthGeneration", initialCounter); + authorityTuple.put("accountAuthorityGeneration", initialCounter); + authorityTuple.put("tenantAuthorityGeneration", Map.of()); + authorityTuple.put("membershipAuthorityGeneration", Map.of()); + authorityTuple.put("privateRealmGrantVersions", List.of()); + claims.put("authorityTuple", authorityTuple); + claims.put("membershipVersion", Map.of()); + claims.put("issuanceFence", initialCounter); + if (ControlUiJwtProfileValidator.PROFILE.equals(spec.tokenProfile())) { + ControlUiJwtProfileValidator.validateClaims(claims, 1); + } else if (PlayerBootstrapJwtProfileValidator.PROFILE.equals(spec.tokenProfile())) { + PlayerBootstrapJwtProfileValidator.validateClaims(claims); + } else if (REPRESENTATIVE_PROFILE.equals(spec.tokenProfile())) { + net.firedevops.firemud.common.security.GameSessionAccountDelegationJwtProfileValidator + .validateClaims(claims); + } else { + throw invalid(); + } + return claims; + } + + private static byte[] canonicalJsonBytes(Map fields) throws Exception { + String json = STRICT_JSON.writeValueAsString(fields); + return Rfc8785CanonicalJson.canonicalizeUtf8(json); + } + + private static byte[] joinCompactParts(byte[] header, byte[] claims, byte[] signature) { + int signatureLength = signature == null ? 0 : signature.length; + int separatorCount = signature == null ? 1 : 2; + byte[] compact = new byte[header.length + claims.length + signatureLength + separatorCount]; + int offset = 0; + System.arraycopy(header, 0, compact, offset, header.length); + offset += header.length; + compact[offset++] = (byte) '.'; + System.arraycopy(claims, 0, compact, offset, claims.length); + offset += claims.length; + if (signature != null) { + compact[offset++] = (byte) '.'; + System.arraycopy(signature, 0, compact, offset, signature.length); + } + return compact; + } + + private static void wipe(byte[] bytes) { + if (bytes != null) { + Arrays.fill(bytes, (byte) 0); + } + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (GeneralSecurityException ex) { + throw invalid(); + } + } + + /** + * Builds the binary, domain-separated challenge used only by the local correspondence proof. Its + * leading NUL makes it structurally distinct from an ASCII compact JWT serialization. + */ + static byte[] correspondenceChallenge(byte[] nonce) { + if (nonce == null || nonce.length != CHALLENGE_NONCE_BYTES) { + throw invalid(); + } + byte[] challenge = Arrays.copyOf(CHALLENGE_DOMAIN, CHALLENGE_DOMAIN.length + nonce.length); + System.arraycopy(nonce, 0, challenge, CHALLENGE_DOMAIN.length, nonce.length); + return challenge; + } + + static void validateStrongRsaCrtPrivateKey(PrivateKey privateKey) { + if (!(privateKey instanceof RSAPrivateCrtKey rsaPrivateKey) + || !"RSA".equalsIgnoreCase(privateKey.getAlgorithm())) { + throw invalid(); + } + BigInteger modulus = rsaPrivateKey.getModulus(); + BigInteger publicExponent = rsaPrivateKey.getPublicExponent(); + BigInteger privateExponent = rsaPrivateKey.getPrivateExponent(); + BigInteger primeP = rsaPrivateKey.getPrimeP(); + BigInteger primeQ = rsaPrivateKey.getPrimeQ(); + BigInteger primeExponentP = rsaPrivateKey.getPrimeExponentP(); + BigInteger primeExponentQ = rsaPrivateKey.getPrimeExponentQ(); + BigInteger crtCoefficient = rsaPrivateKey.getCrtCoefficient(); + if (!positive(modulus) + || modulus.bitLength() < MIN_RSA_BITS + || modulus.bitLength() > MAX_RSA_BITS + || !BigInteger.valueOf(65_537).equals(publicExponent) + || !positive(privateExponent) + || !positive(primeP) + || !positive(primeQ) + || primeP.equals(primeQ) + || !positive(primeExponentP) + || !positive(primeExponentQ) + || !positive(crtCoefficient)) { + throw invalid(); + } + BigInteger pMinusOne = primeP.subtract(BigInteger.ONE); + BigInteger qMinusOne = primeQ.subtract(BigInteger.ONE); + BigInteger lambda = pMinusOne.divide(pMinusOne.gcd(qMinusOne)).multiply(qMinusOne); + if (!primeP.multiply(primeQ).equals(modulus) + || !privateExponent.multiply(publicExponent).mod(lambda).equals(BigInteger.ONE) + || !privateExponent.mod(pMinusOne).equals(primeExponentP) + || !privateExponent.mod(qMinusOne).equals(primeExponentQ) + || !primeQ.modInverse(primeP).equals(crtCoefficient)) { + throw invalid(); + } + } + + private static void validateIdentity(ExpectedIdentity identity) { + if (!validIdentityValue(identity.environmentId()) + || !validIdentityValue(identity.clusterId()) + || !validIdentityValue(identity.namespace()) + || !validUuidV4(identity.operationId()) + || identity.generation() == null + || !GENERATION.matcher(identity.generation()).matches() + || identity.kid() == null + || !KID.matcher(identity.kid()).matches() + || identity.publicKeyFingerprint() == null + || !FINGERPRINT.matcher(identity.publicKeyFingerprint()).matches()) { + throw invalid(); + } + } + + private static boolean validIdentityValue(String value) { + if (value == null || value.isBlank() || value.length() > 128) { + return false; + } + for (int index = 0; index < value.length(); index++) { + if (Character.isISOControl(value.charAt(index))) { + return false; + } + } + return true; + } + + private static boolean validUuidV4(String value) { + if (value == null) { + return false; + } + try { + UUID uuid = UUID.fromString(value); + return uuid.toString().equals(value) && uuid.version() == 4 && uuid.variant() == 2; + } catch (IllegalArgumentException ex) { + return false; + } + } + + private static void requireExpectedIdentity(ExpectedIdentity actual, ExpectedIdentity expected) { + if (!actual.equals(expected)) { + throw invalid(); + } + } + + private static ParsedPrivateBundle parsePrivateBundle(byte[] contents) { + if (contents == null || contents.length == 0 || contents.length > MAX_PRIVATE_BUNDLE_BYTES) { + throw invalid(); + } + try { + JsonNode root = strictJson(contents); + requireOnlyFields(root, PRIVATE_BUNDLE_FIELDS); + if (root.size() != PRIVATE_BUNDLE_FIELDS.size()) { + throw invalid(); + } + JsonNode version = root.get("version"); + if (version == null + || version.isNull() + || !version.isIntegralNumber() + || !version.canConvertToInt() + || version.intValue() != 1) { + throw invalid(); + } + ExpectedIdentity identity = + new ExpectedIdentity( + requiredText(root, "environmentId", 128), + requiredText(root, "clusterId", 128), + requiredText(root, "namespace", 128), + requiredText(root, "operationId", 36), + requiredText(root, "generation", 64), + requiredText(root, "kid", 64), + requiredText(root, "publicKeyFingerprint", 64)); + validateIdentity(identity); + if (!ALGORITHM.equals(requiredText(root, "algorithm", 8))) { + throw invalid(); + } + + String encodedPrivateKey = requiredText(root, "privateKeyPkcs8", 24 * 1024); + byte[] privateDer = decodeCanonicalBase64Url(encodedPrivateKey, MAX_PRIVATE_KEY_DER_BYTES); + try { + PrivateKey privateKey = + KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateDer)); + validateStrongRsaCrtPrivateKey(privateKey); + RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey; + byte[] canonicalEncoding = privateKey.getEncoded(); + try { + if (canonicalEncoding == null || !Arrays.equals(privateDer, canonicalEncoding)) { + throw invalid(); + } + } finally { + if (canonicalEncoding != null) { + Arrays.fill(canonicalEncoding, (byte) 0); + } + } + return new ParsedPrivateBundle( + privateKey, identity, rsaPrivateKey.getModulus(), rsaPrivateKey.getPublicExponent()); + } finally { + Arrays.fill(privateDer, (byte) 0); + } + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (CharacterCodingException | GeneralSecurityException | RuntimeException ex) { + throw invalid(); + } + } + + private static Map parsePublicJwks(byte[] contents) { + if (contents == null || contents.length == 0 || contents.length > MAX_PUBLIC_JWKS_BYTES) { + throw invalid(); + } + try { + JsonNode root = strictJson(contents); + requireOnlyFields(root, JWKS_FIELDS); + if (root.size() != 1) { + throw invalid(); + } + JsonNode keysNode = root.get("keys"); + if (keysNode == null + || !keysNode.isArray() + || keysNode.isEmpty() + || keysNode.size() > MAX_JWKS_KEYS) { + throw invalid(); + } + Map keys = new HashMap<>(); + Set seenKids = new HashSet<>(); + for (JsonNode jwk : keysNode) { + requireOnlyFields(jwk, JWK_FIELDS); + String keyType = requiredText(jwk, "kty", 8); + String use = requiredText(jwk, "use", 8); + String algorithm = requiredText(jwk, "alg", 8); + String kid = requiredText(jwk, "kid", 64); + String encodedModulus = requiredText(jwk, "n", 4_096); + String encodedExponent = requiredText(jwk, "e", 16); + if (!"RSA".equals(keyType) + || !"sig".equals(use) + || !ALGORITHM.equals(algorithm) + || !KID.matcher(kid).matches() + || !seenKids.add(kid)) { + throw invalid(); + } + JsonNode keyOps = jwk.get("key_ops"); + if (keyOps != null) { + if (!keyOps.isArray() + || keyOps.size() != 1 + || !keyOps.get(0).isTextual() + || !"verify".equals(keyOps.get(0).textValue())) { + throw invalid(); + } + } + byte[] modulusBytes = decodeCanonicalBase64Url(encodedModulus, 2_048); + byte[] exponentBytes = decodeCanonicalBase64Url(encodedExponent, 8); + try { + if (modulusBytes.length == 0 + || modulusBytes[0] == 0 + || exponentBytes.length == 0 + || exponentBytes[0] == 0) { + throw invalid(); + } + BigInteger modulus = new BigInteger(1, modulusBytes); + BigInteger exponent = new BigInteger(1, exponentBytes); + if (modulus.bitLength() < MIN_RSA_BITS + || modulus.bitLength() > MAX_RSA_BITS + || !modulus.testBit(0) + || !BigInteger.valueOf(65_537).equals(exponent)) { + throw invalid(); + } + RSAPublicKey publicKey = + (RSAPublicKey) + KeyFactory.getInstance("RSA") + .generatePublic(new RSAPublicKeySpec(modulus, exponent)); + keys.put(kid, publicKey); + } finally { + Arrays.fill(modulusBytes, (byte) 0); + Arrays.fill(exponentBytes, (byte) 0); + } + } + return Map.copyOf(keys); + } catch (InvalidMountedSignerBundleException ex) { + throw ex; + } catch (CharacterCodingException | GeneralSecurityException | RuntimeException ex) { + throw invalid(); + } + } + + private static JsonNode strictJson(byte[] contents) throws CharacterCodingException { + String text = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(contents)) + .toString(); + if (text.startsWith("\uFEFF")) { + throw invalid(); + } + JsonNode root = STRICT_JSON.readTree(text); + if (root == null || root.isNull()) { + throw invalid(); + } + return root; + } + + private static void requireOnlyFields(JsonNode node, Set allowedFields) { + if (node == null || !node.isObject()) { + throw invalid(); + } + for (Map.Entry field : node.properties()) { + if (!allowedFields.contains(field.getKey())) { + throw invalid(); + } + } + } + + private static String requiredText(JsonNode object, String name, int maxLength) { + JsonNode value = object.get(name); + if (value == null || value.isNull() || !value.isTextual()) { + throw invalid(); + } + String text = value.textValue(); + if (text == null || text.isEmpty() || text.length() > maxLength) { + throw invalid(); + } + return text; + } + + private static byte[] decodeCanonicalBase64Url(String encoded, int maxBytes) { + if (encoded == null || encoded.isEmpty()) { + throw invalid(); + } + byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(encoded); + } catch (IllegalArgumentException ex) { + throw invalid(); + } + byte[] canonical = Base64.getUrlEncoder().withoutPadding().encode(decoded); + boolean canonicalEncoding = canonical.length == encoded.length(); + for (int index = 0; canonicalEncoding && index < canonical.length; index++) { + canonicalEncoding = (char) Byte.toUnsignedInt(canonical[index]) == encoded.charAt(index); + } + Arrays.fill(canonical, (byte) 0); + if (decoded.length == 0 || decoded.length > maxBytes || !canonicalEncoding) { + Arrays.fill(decoded, (byte) 0); + throw invalid(); + } + return decoded; + } + + private static Path resolveMountedFile(Path configuredRoot, Path configuredRelativeFile) + throws IOException { + if (configuredRoot == null + || configuredRelativeFile == null + || !configuredRoot.isAbsolute() + || configuredRelativeFile.isAbsolute() + || configuredRelativeFile.toString().isBlank()) { + throw invalid(); + } + for (Path segment : configuredRelativeFile) { + if (".".equals(segment.toString()) || "..".equals(segment.toString())) { + throw invalid(); + } + } + Path mountRoot = configuredRoot.toRealPath(); + if (!Files.isDirectory(mountRoot, LinkOption.NOFOLLOW_LINKS)) { + throw invalid(); + } + Path resolvedFile = mountRoot.resolve(configuredRelativeFile).toRealPath(); + if (!resolvedFile.startsWith(mountRoot) + || !Files.isRegularFile(resolvedFile, LinkOption.NOFOLLOW_LINKS)) { + throw invalid(); + } + return resolvedFile; + } + + private static byte[] readBounded(Path path, int maxBytes) throws IOException { + byte[] scratch = new byte[maxBytes + 1]; + try { + try (SeekableByteChannel channel = + Files.newByteChannel(path, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS))) { + ByteBuffer buffer = ByteBuffer.wrap(scratch); + int total = 0; + while (true) { + int count = channel.read(buffer); + if (count < 0) { + break; + } + if (count == 0) { + continue; + } + total += count; + if (total > maxBytes) { + throw invalid(); + } + } + if (channel.position() != channel.size() || total != channel.size()) { + throw invalid(); + } + return Arrays.copyOf(scratch, total); + } + } finally { + Arrays.fill(scratch, (byte) 0); + } + } + + private static void proveCorrespondence(PrivateKey privateKey, RSAPublicKey publicKey) + throws GeneralSecurityException { + byte[] nonce = new byte[CHALLENGE_NONCE_BYTES]; + byte[] challenge = null; + byte[] signatureBytes = null; + try { + CHALLENGE_RANDOM.nextBytes(nonce); + challenge = correspondenceChallenge(nonce); + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(privateKey); + signer.update(challenge); + signatureBytes = signer.sign(); + + Signature verifier = Signature.getInstance("SHA256withRSA"); + verifier.initVerify(publicKey); + verifier.update(challenge); + if (!verifier.verify(signatureBytes)) { + throw invalid(); + } + } finally { + Arrays.fill(nonce, (byte) 0); + if (challenge != null) { + Arrays.fill(challenge, (byte) 0); + } + if (signatureBytes != null) { + Arrays.fill(signatureBytes, (byte) 0); + } + } + } + + private static String fingerprint(BigInteger modulus, BigInteger exponent) { + String canonicalJwk = + "{\"e\":\"" + + base64Url(unsignedBytes(exponent)) + + "\",\"kty\":\"RSA\",\"n\":\"" + + base64Url(unsignedBytes(modulus)) + + "\"}"; + try { + byte[] digest = + MessageDigest.getInstance("SHA-256") + .digest(canonicalJwk.getBytes(StandardCharsets.US_ASCII)); + return java.util.HexFormat.of().formatHex(digest); + } catch (GeneralSecurityException ex) { + throw invalid(); + } + } + + private static byte[] unsignedBytes(BigInteger value) { + byte[] encoded = value.toByteArray(); + if (encoded.length > 1 && encoded[0] == 0) { + return Arrays.copyOfRange(encoded, 1, encoded.length); + } + return encoded; + } + + private static String base64Url(byte[] bytes) { + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } finally { + Arrays.fill(bytes, (byte) 0); + } + } + + private static boolean positive(BigInteger value) { + return value != null && value.signum() > 0; + } + + private static InvalidMountedSignerBundleException invalid() { + return new InvalidMountedSignerBundleException(); + } + + /** Caller-supplied durable request identity; it is not authorization or proof of provisioning. */ + public record ExpectedIdentity( + String environmentId, + String clusterId, + String namespace, + String operationId, + String generation, + String kid, + String publicKeyFingerprint) {} + + /** Closed signing input built only from the issuance repository's locked owner readback. */ + record DelegationSigningSpec( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot, + Optional bound) { + DelegationSigningSpec( + AccountGameplayDelegationPendingIdentity identity, + AccountAuthoritySnapshot authoritySnapshot) { + this(identity, authoritySnapshot, Optional.empty()); + } + + DelegationSigningSpec { + Objects.requireNonNull(bound); + Objects.requireNonNull(identity, "Persisted pending identity is required"); + Objects.requireNonNull(authoritySnapshot, "Persisted Account authority is required"); + if (!authoritySnapshot.accountId().equals(identity.accountId()) + || identity.issuedAtEpochSecond() <= 0L + || identity.notBeforeEpochSecond() <= 0L + || identity.notBeforeEpochSecond() > identity.issuedAtEpochSecond() + || identity.expiresAtEpochSecond() <= identity.issuedAtEpochSecond() + || identity.expiresAtEpochSecond() - identity.issuedAtEpochSecond() + > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS) { + throw invalid(); + } + } + } + + record BoundDelegationClaims( + String tenantId, Map authorityTuple, Map membershipVersion) { + BoundDelegationClaims { + authorityTuple = immutableAuthorityTupleCopy(authorityTuple); + membershipVersion = Map.copyOf(membershipVersion); + net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile + .requirePublicTenantBoundAuthority(tenantId, authorityTuple, membershipVersion); + } + } + + @FunctionalInterface + interface DelegationCandidateConsumer { + /** The caller persists the exact candidate before any internal transient handoff. */ + void bindExactCandidate(SignedDelegationDigest digest, byte[] compactJwt); + } + + /** Non-secret operation, signer and token-hash identity; never includes compact JWT bytes. */ + static final class SignedDelegationDigest { + private final UUID issuanceOperationId; + private final UUID requestId; + private final UUID jti; + private final String signerOperationId; + private final String signerGeneration; + private final String kid; + private final String publicKeyFingerprint; + private final long issuedAtEpochSecond; + private final long notBeforeEpochSecond; + private final long expiresAtEpochSecond; + private final String compactTokenSha256; + + private SignedDelegationDigest( + UUID issuanceOperationId, + UUID requestId, + UUID jti, + String signerOperationId, + String signerGeneration, + String kid, + String publicKeyFingerprint, + long issuedAtEpochSecond, + long notBeforeEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256) { + this.issuanceOperationId = Objects.requireNonNull(issuanceOperationId); + this.requestId = Objects.requireNonNull(requestId); + this.jti = Objects.requireNonNull(jti); + this.signerOperationId = Objects.requireNonNull(signerOperationId); + this.signerGeneration = Objects.requireNonNull(signerGeneration); + this.kid = Objects.requireNonNull(kid); + this.publicKeyFingerprint = Objects.requireNonNull(publicKeyFingerprint); + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.notBeforeEpochSecond = notBeforeEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + if (compactTokenSha256 == null || !FINGERPRINT.matcher(compactTokenSha256).matches()) { + throw invalid(); + } + this.compactTokenSha256 = compactTokenSha256; + } + + UUID issuanceOperationId() { + return issuanceOperationId; + } + + UUID requestId() { + return requestId; + } + + UUID jti() { + return jti; + } + + String signerOperationId() { + return signerOperationId; + } + + String signerGeneration() { + return signerGeneration; + } + + String kid() { + return kid; + } + + String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + long notBeforeEpochSecond() { + return notBeforeEpochSecond; + } + + long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + String compactTokenSha256() { + return compactTokenSha256; + } + + @Override + public String toString() { + return "SignedDelegationDigest[redacted]"; + } + } + + public enum ProbeKind { + CANARY, + REPRESENTATIVE + } + + @FunctionalInterface + interface ProbeDeliveryConsumer { + /** The caller must durably pin {@code digest} before passing the transient bytes onward. */ + void persistAttemptAndDeliver(SignedProbeDigest digest, byte[] compactJwt); + } + + /** A closed claim-shape input; its constructor permits only the two declared readiness forms. */ + record ReadinessProbeSigningSpec( + String validatorId, + ProbeKind probeKind, + String tokenProfile, + String audience, + UUID jti, + String targetGeneration, + String targetKid, + long issuedAtEpochSecond, + long expiresAtEpochSecond) { + ReadinessProbeSigningSpec { + if (validatorId == null + || (!READINESS_VALIDATOR_ID.equals(validatorId) + && !GAME_SESSION_VALIDATOR_ID.equals(validatorId)) + || probeKind == null + || jti == null + || jti.version() != 4 + || jti.variant() != 2 + || targetGeneration == null + || !GENERATION.matcher(targetGeneration).matches() + || targetKid == null + || !KID.matcher(targetKid).matches() + || issuedAtEpochSecond <= 0L + || expiresAtEpochSecond <= issuedAtEpochSecond + || expiresAtEpochSecond - issuedAtEpochSecond > 300L) { + throw invalid(); + } + if (probeKind == ProbeKind.CANARY) { + if (!READINESS_CANARY_PROFILE.equals(tokenProfile) + || !READINESS_CANARY_AUDIENCE.equals(audience)) { + throw invalid(); + } + } else { + boolean exactProfileAudience = + (REPRESENTATIVE_PROFILE.equals(tokenProfile) + && REPRESENTATIVE_AUDIENCE.equals(audience)) + || (ControlUiJwtProfileValidator.PROFILE.equals(tokenProfile) + && ControlUiJwtProfileValidator.AUDIENCE.equals(audience)) + || (PlayerBootstrapJwtProfileValidator.PROFILE.equals(tokenProfile) + && PlayerBootstrapJwtProfileValidator.AUDIENCE.equals(audience)); + if (!exactProfileAudience) { + throw invalid(); + } + } + } + } + + /** Non-secret output from the one constrained signing operation; it never contains JWT bytes. */ + public static final class SignedProbeDigest { + private final String operationId; + private final String validatorId; + private final ProbeKind probeKind; + private final String tokenProfile; + private final String audience; + private final UUID jti; + private final String targetGeneration; + private final String targetKid; + private final String publicKeyFingerprint; + private final long issuedAtEpochSecond; + private final long expiresAtEpochSecond; + private final String compactTokenSha256; + + private SignedProbeDigest( + String operationId, + String validatorId, + ProbeKind probeKind, + String tokenProfile, + String audience, + UUID jti, + String targetGeneration, + String targetKid, + String publicKeyFingerprint, + long issuedAtEpochSecond, + long expiresAtEpochSecond, + String compactTokenSha256) { + this.operationId = operationId; + this.validatorId = validatorId; + this.probeKind = probeKind; + this.tokenProfile = tokenProfile; + this.audience = audience; + this.jti = jti; + this.targetGeneration = targetGeneration; + this.targetKid = targetKid; + this.publicKeyFingerprint = publicKeyFingerprint; + this.issuedAtEpochSecond = issuedAtEpochSecond; + this.expiresAtEpochSecond = expiresAtEpochSecond; + this.compactTokenSha256 = compactTokenSha256; + } + + public String operationId() { + return operationId; + } + + public String validatorId() { + return validatorId; + } + + public ProbeKind probeKind() { + return probeKind; + } + + public String tokenProfile() { + return tokenProfile; + } + + public String audience() { + return audience; + } + + public UUID jti() { + return jti; + } + + public String targetGeneration() { + return targetGeneration; + } + + public String targetKid() { + return targetKid; + } + + public String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + public long issuedAtEpochSecond() { + return issuedAtEpochSecond; + } + + public long expiresAtEpochSecond() { + return expiresAtEpochSecond; + } + + public String compactTokenSha256() { + return compactTokenSha256; + } + + @Override + public String toString() { + return "AccountMountedJwtSignerBundle.SignedProbeDigest[operation=" + + operationId + + ", probeKind=" + + probeKind + + ", tokenBytes=discarded, authorization=none, verification=unproved]"; + } + } + + /** Non-secret, process-local observation with no token-signing or private-key accessor. */ + public static final class LocalObservation { + private final ExpectedIdentity expectedIdentity; + private final String publicKeyFingerprint; + + private LocalObservation(ExpectedIdentity expectedIdentity, String publicKeyFingerprint) { + this.expectedIdentity = expectedIdentity; + this.publicKeyFingerprint = publicKeyFingerprint; + } + + public ExpectedIdentity expectedIdentity() { + return expectedIdentity; + } + + public String publicKeyFingerprint() { + return publicKeyFingerprint; + } + + public boolean localPrivatePublicCorrespondenceObserved() { + return true; + } + + @Override + public String toString() { + return "AccountMountedJwtSignerBundle.LocalObservation[local correspondence observed; " + + "authorization=none, provisioning=unproved, readiness=unproved]"; + } + } + + /** Safe generic failure for malformed, unavailable, or mismatched mounted projections. */ + public static final class InvalidMountedSignerBundleException extends IllegalArgumentException { + private InvalidMountedSignerBundleException() { + super("Mounted signer correspondence is unavailable or invalid"); + } + } + + private record ParsedPrivateBundle( + PrivateKey privateKey, + ExpectedIdentity identity, + BigInteger publicModulus, + BigInteger publicExponent) {} + + private record VerifiedMountedSigner( + LocalObservation observation, PrivateKey privateKey, RSAPublicKey publicKey) {} +} diff --git a/services/account-service/src/main/resources/db/migration/V100__account_jwt_signer_materialization_readback.sql b/services/account-service/src/main/resources/db/migration/V100__account_jwt_signer_materialization_readback.sql new file mode 100644 index 0000000000..acb940fa59 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V100__account_jwt_signer_materialization_readback.sql @@ -0,0 +1,326 @@ +-- Immutable Account-bound reports for the fixed private Secret. The first report observes only +-- the fixed-name pre-created Secret; the second records one pending-key generation/CAS result. +-- Neither report changes active state, PREPARED state, JWKS, token signing, or readiness. +CREATE TABLE account_jwt_signer_secret_observations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest_version SMALLINT NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL, + secret_uid UUID NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + observation_digest_version SMALLINT NOT NULL, + observation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_observation_exact_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_observation_exact_operation_fk + FOREIGN KEY (operation_id, environment_id, cluster_id, kubernetes_namespace, + custody_mode, operation_digest, expected_record_version, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + REFERENCES account_jwt_signer_generation_operations( + operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, expected_cluster_incarnation_uid, + expected_namespace_uid, trust_binding_digest, trust_config_revision) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_observation_readback_unique + UNIQUE (operation_id, operation_digest, generation_request_digest, + secret_uid, observed_resource_version), + CONSTRAINT account_jwt_signer_observation_name_check + CHECK (private_secret_name = 'jwt-signing-keys'), + CONSTRAINT account_jwt_signer_observation_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_signer_observation_trust_check + CHECK (trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_observation_version_check + CHECK (expected_record_version > 0 AND operation_digest_version = 1 + AND observation_digest_version = 1), + CONSTRAINT account_jwt_signer_observation_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND observation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_observation_resource_version_check + CHECK (observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256) +); + +CREATE TABLE account_jwt_signer_generation_results ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL, + secret_uid UUID NOT NULL, + expected_prior_resource_version VARCHAR(256) NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + public_jwk_json VARCHAR(8192) NOT NULL, + receipt_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_generation_result_exact_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_exact_operation_fk + FOREIGN KEY (operation_id, environment_id, cluster_id, kubernetes_namespace, + custody_mode, operation_digest, + target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + REFERENCES account_jwt_signer_generation_operations( + operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, target_generation, target_kid, + target_algorithm, expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_exact_observation_fk + FOREIGN KEY (operation_id, operation_digest, generation_request_digest, + secret_uid, expected_prior_resource_version) + REFERENCES account_jwt_signer_secret_observations( + operation_id, operation_digest, generation_request_digest, + secret_uid, observed_resource_version) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_result_name_check + CHECK (private_secret_name = 'jwt-signing-keys'), + CONSTRAINT account_jwt_signer_generation_result_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_signer_generation_result_trust_check + CHECK (trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_generation_result_version_check + CHECK (desired_state_version > 1), + CONSTRAINT account_jwt_signer_generation_result_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND receipt_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_generation_result_resource_versions_check + CHECK (expected_prior_resource_version ~ '^[!-~]+$' + AND char_length(expected_prior_resource_version) BETWEEN 1 AND 256 + AND observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256 + AND expected_prior_resource_version <> observed_resource_version), + CONSTRAINT account_jwt_signer_generation_result_key_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND target_algorithm = 'RS256' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +ALTER TABLE account_jwt_signer_generation_results + ADD CONSTRAINT account_jwt_signer_generation_result_public_jwk_check + CHECK (octet_length(public_jwk_json) <= 8192 + AND jsonb_typeof(public_jwk_json::jsonb) = 'object' + AND (public_jwk_json::jsonb ?& ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e']) + AND NOT (public_jwk_json::jsonb ?| ARRAY['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k']) + AND public_jwk_json::jsonb - ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e'] = '{}'::jsonb); +-- [jooq ignore stop] + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_signer_secret_observation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_record_version BIGINT; + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); +BEGIN + SELECT desired_state.generation_operation_id, desired_state.record_version + INTO state_operation_id, state_record_version + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = NEW.environment_id + AND desired_state.cluster_id = NEW.cluster_id + AND desired_state.kubernetes_namespace = NEW.kubernetes_namespace + AND desired_state.custody_mode = NEW.custody_mode + FOR UPDATE; + + SELECT generation_op.operation_digest, generation_op.expected_record_version, + generation_op.environment_id, generation_op.cluster_id, generation_op.kubernetes_namespace, + generation_op.custody_mode, generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision + INTO operation_digest, operation_expected_version, operation_environment, + operation_cluster, operation_namespace, operation_mode, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.operation_id + FOR UPDATE; + + IF state_operation_id IS DISTINCT FROM NEW.operation_id + OR state_record_version IS DISTINCT FROM operation_expected_version + 1 + OR operation_digest IS DISTINCT FROM NEW.operation_digest + OR operation_expected_version IS DISTINCT FROM NEW.expected_record_version + OR operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_cluster_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR operation_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR operation_trust_digest IS DISTINCT FROM NEW.trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM NEW.trust_config_revision + OR NEW.private_secret_name IS DISTINCT FROM 'jwt-signing-keys' THEN + RAISE EXCEPTION 'JWT signer Secret observation must bind the current Account operation and trust' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_secret_observation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_result_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_record_version BIGINT; + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_generation BIGINT; + operation_kid VARCHAR(64); + operation_algorithm VARCHAR(16); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); + observation_generation_request_digest VARCHAR(64); + observation_secret_uid UUID; + observation_resource_version VARCHAR(256); +BEGIN + -- Lock order matches every Account repository write: desired state, then operation. + SELECT desired_state.generation_operation_id, desired_state.record_version + INTO state_operation_id, state_record_version + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = NEW.environment_id + AND desired_state.cluster_id = NEW.cluster_id + AND desired_state.kubernetes_namespace = NEW.kubernetes_namespace + AND desired_state.custody_mode = NEW.custody_mode + FOR UPDATE; + + SELECT generation_op.operation_digest, generation_op.expected_record_version, + generation_op.environment_id, generation_op.cluster_id, generation_op.kubernetes_namespace, + generation_op.custody_mode, generation_op.target_generation, generation_op.target_kid, + generation_op.target_algorithm, generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision + INTO operation_digest, operation_expected_version, operation_environment, + operation_cluster, operation_namespace, operation_mode, operation_generation, + operation_kid, operation_algorithm, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.operation_id + FOR UPDATE; + + SELECT observation.generation_request_digest, observation.secret_uid, + observation.observed_resource_version + INTO observation_generation_request_digest, observation_secret_uid, + observation_resource_version + FROM account_jwt_signer_secret_observations AS observation + WHERE observation.operation_id = NEW.operation_id + FOR UPDATE; + + IF state_operation_id IS DISTINCT FROM NEW.operation_id + OR state_record_version IS DISTINCT FROM operation_expected_version + 1 + OR NEW.desired_state_version IS DISTINCT FROM state_record_version + OR operation_digest IS DISTINCT FROM NEW.operation_digest + OR operation_expected_version IS NULL + OR operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_generation IS DISTINCT FROM NEW.target_generation + OR operation_kid IS DISTINCT FROM NEW.target_kid + OR operation_algorithm IS DISTINCT FROM NEW.target_algorithm + OR operation_cluster_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR operation_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR operation_trust_digest IS DISTINCT FROM NEW.trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM NEW.trust_config_revision + OR observation_generation_request_digest IS DISTINCT FROM NEW.generation_request_digest + OR observation_secret_uid IS DISTINCT FROM NEW.secret_uid + OR observation_resource_version IS DISTINCT FROM NEW.expected_prior_resource_version + OR NEW.private_secret_name IS DISTINCT FROM 'jwt-signing-keys' THEN + RAISE EXCEPTION 'JWT signer generation result must bind the exact current request and observation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_result_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_evidence_immutable() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer generation evidence is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_evidence_immutable'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_jwt_signer_secret_observation_guard + BEFORE INSERT ON account_jwt_signer_secret_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_secret_observation_guard(); + +CREATE TRIGGER account_jwt_signer_secret_observation_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_secret_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_secret_observation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_secret_observations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_result_guard + BEFORE INSERT ON account_jwt_signer_generation_results + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_result_guard(); + +CREATE TRIGGER account_jwt_signer_generation_result_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_generation_results + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_result_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_generation_results + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_evidence_immutable(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V101__account_jwt_jwks_prepublication.sql b/services/account-service/src/main/resources/db/migration/V101__account_jwt_jwks_prepublication.sql new file mode 100644 index 0000000000..6da03d99d7 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V101__account_jwt_jwks_prepublication.sql @@ -0,0 +1,599 @@ +-- Account records its exact public-JWKS intent before the protected ConfigMap CAS, then binds +-- server readback and local mounted correspondence to the same current generation operation. +-- These observations are non-authorizing and never advance signer lifecycle state. +CREATE TABLE account_jwt_jwks_prepublication_intents ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + generation_receipt_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + api_config_revision VARCHAR(128) NOT NULL, + config_map_name VARCHAR(63) NOT NULL, + config_map_uid UUID NOT NULL, + expected_resource_version VARCHAR(256) NOT NULL, + expected_snapshot_digest VARCHAR(64) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + expected_durable_active_json VARCHAR(512) NOT NULL, + expected_published_active_json VARCHAR(512) NOT NULL, + jwks_json TEXT NOT NULL, + generation_marker_json TEXT NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + generation_marker_digest VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_intent_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_intent_generation_result_fk + FOREIGN KEY (operation_id) + REFERENCES account_jwt_signer_generation_results(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_intent_digest_unique + UNIQUE (operation_id, intent_digest), + CONSTRAINT account_jwt_jwks_intent_identity_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND config_map_name = 'jwt-jwks' + AND desired_state_version > 1 + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]+$' + AND char_length(target_kid) BETWEEN 1 AND 64), + CONSTRAINT account_jwt_jwks_intent_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_jwks_intent_resource_version_check + CHECK (expected_resource_version ~ '^[!-~]+$' + AND char_length(expected_resource_version) BETWEEN 1 AND 256), + CONSTRAINT account_jwt_jwks_intent_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND generation_receipt_digest ~ '^[0-9a-f]{64}$' + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND expected_snapshot_digest ~ '^[0-9a-f]{64}$' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND generation_marker_digest ~ '^[0-9a-f]{64}$' + AND intent_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_jwks_intent_revision_check + CHECK (trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' + AND char_length(trust_config_revision) BETWEEN 1 AND 128 + AND api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$' + AND char_length(api_config_revision) BETWEEN 1 AND 128), + CONSTRAINT account_jwt_jwks_intent_content_bounds_check + CHECK (octet_length(jwks_json) BETWEEN 1 AND 262144 + AND octet_length(generation_marker_json) BETWEEN 1 AND 16384 + AND octet_length(expected_durable_active_json) BETWEEN 1 AND 512 + AND octet_length(expected_published_active_json) BETWEEN 1 AND 512) +); + +CREATE TABLE account_jwt_jwks_publication_receipts ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + config_map_uid UUID NOT NULL, + expected_resource_version VARCHAR(256) NOT NULL, + observed_resource_version VARCHAR(256) NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + receipt_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_receipt_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_receipt_intent_fk + FOREIGN KEY (operation_id, intent_digest) + REFERENCES account_jwt_jwks_prepublication_intents(operation_id, intent_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_receipt_digest_unique + UNIQUE (operation_id, intent_digest, receipt_digest), + CONSTRAINT account_jwt_jwks_receipt_identity_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_resource_version ~ '^[!-~]+$' + AND char_length(expected_resource_version) BETWEEN 1 AND 256 + AND observed_resource_version ~ '^[!-~]+$' + AND char_length(observed_resource_version) BETWEEN 1 AND 256 + AND expected_resource_version <> observed_resource_version), + CONSTRAINT account_jwt_jwks_receipt_digest_check + CHECK (intent_digest ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND receipt_digest ~ '^[0-9a-f]{64}$') +); + +CREATE TABLE account_jwt_jwks_mount_observations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + intent_digest VARCHAR(64) NOT NULL, + publication_receipt_digest VARCHAR(64) NOT NULL, + generation_marker_digest VARCHAR(64) NOT NULL, + public_data_digest VARCHAR(64) NOT NULL, + public_key_fingerprint VARCHAR(64) NOT NULL, + observation_digest VARCHAR(64) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_jwks_mount_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_mount_receipt_fk + FOREIGN KEY (operation_id, intent_digest, publication_receipt_digest) + REFERENCES account_jwt_jwks_publication_receipts( + operation_id, intent_digest, receipt_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_jwks_mount_digest_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND intent_digest ~ '^[0-9a-f]{64}$' + AND publication_receipt_digest ~ '^[0-9a-f]{64}$' + AND generation_marker_digest ~ '^[0-9a-f]{64}$' + AND public_data_digest ~ '^[0-9a-f]{64}$' + AND public_key_fingerprint ~ '^[0-9a-f]{64}$' + AND observation_digest ~ '^[0-9a-f]{64}$') +); + +-- Keep the trigger bodies out of jOOQ DDL parsing; the database still enforces these invariants. +-- [jooq ignore start] +CREATE FUNCTION account_jwt_jwks_lock_current_generation( + p_operation_id UUID, + p_environment_id VARCHAR, + p_cluster_id VARCHAR, + p_namespace VARCHAR, + p_custody_mode VARCHAR, + p_operation_digest VARCHAR, + p_generation_request_digest VARCHAR, + p_generation_receipt_digest VARCHAR, + p_desired_state_version BIGINT, + p_cluster_uid UUID, + p_namespace_uid UUID, + p_trust_binding_digest VARCHAR, + p_trust_config_revision VARCHAR, + p_target_generation BIGINT, + p_target_kid VARCHAR, + p_public_key_fingerprint VARCHAR +) +RETURNS JSONB +LANGUAGE plpgsql +AS $$ +DECLARE + state_operation_id UUID; + state_version BIGINT; + state_prepared_operation_id UUID; + durable_active JSONB; + published_active JSONB; + operation_environment VARCHAR(63); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_digest VARCHAR(64); + operation_expected_version BIGINT; + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); + operation_target_generation BIGINT; + operation_target_kid VARCHAR(64); + operation_target_algorithm VARCHAR(16); + operation_previous_generation BIGINT; + operation_previous_kid VARCHAR(128); + operation_published_generation BIGINT; + operation_published_kid VARCHAR(128); + result_environment VARCHAR(63); + result_cluster VARCHAR(128); + result_namespace VARCHAR(63); + result_mode VARCHAR(64); + result_operation_digest VARCHAR(64); + result_generation_request_digest VARCHAR(64); + result_desired_state_version BIGINT; + result_cluster_uid UUID; + result_namespace_uid UUID; + result_trust_digest VARCHAR(64); + result_trust_revision VARCHAR(128); + result_generation BIGINT; + result_kid VARCHAR(64); + result_fingerprint VARCHAR(64); + result_receipt_digest VARCHAR(64); + result_jwk VARCHAR(8192); +BEGIN + SELECT desired_state.generation_operation_id, + desired_state.record_version, + desired_state.prepared_operation_id, + CASE WHEN desired_state.durable_active_generation IS NULL + THEN '{"present":false}'::jsonb + ELSE jsonb_build_object('present', true, + 'generation', desired_state.durable_active_generation::text, + 'kid', desired_state.durable_active_kid) + END, + CASE WHEN desired_state.published_active_generation IS NULL + THEN '{"present":false}'::jsonb + ELSE jsonb_build_object('present', true, + 'generation', desired_state.published_active_generation::text, + 'kid', desired_state.published_active_kid) + END + INTO state_operation_id, state_version, state_prepared_operation_id, + durable_active, published_active + FROM account_jwt_signer_desired_states AS desired_state + WHERE desired_state.environment_id = p_environment_id + AND desired_state.cluster_id = p_cluster_id + AND desired_state.kubernetes_namespace = p_namespace + AND desired_state.custody_mode = p_custody_mode + FOR UPDATE; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT JWKS current desired state is missing' USING ERRCODE = '23514'; + END IF; + + SELECT generation_op.environment_id, generation_op.cluster_id, + generation_op.kubernetes_namespace, generation_op.custody_mode, + generation_op.operation_digest, generation_op.expected_record_version, + generation_op.expected_cluster_incarnation_uid, + generation_op.expected_namespace_uid, generation_op.trust_binding_digest, + generation_op.trust_config_revision, generation_op.target_generation, + generation_op.target_kid, generation_op.target_algorithm, + generation_op.expected_previous_generation, generation_op.expected_previous_kid, + generation_op.expected_published_generation, generation_op.expected_published_kid + INTO operation_environment, operation_cluster, operation_namespace, operation_mode, + operation_digest, operation_expected_version, operation_cluster_uid, + operation_namespace_uid, operation_trust_digest, operation_trust_revision, + operation_target_generation, operation_target_kid, operation_target_algorithm, + operation_previous_generation, operation_previous_kid, + operation_published_generation, operation_published_kid + FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = p_operation_id + FOR UPDATE; + + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT JWKS generation operation is missing' USING ERRCODE = '23514'; + END IF; + + SELECT generation_result.environment_id, generation_result.cluster_id, + generation_result.kubernetes_namespace, generation_result.custody_mode, + generation_result.operation_digest, generation_result.generation_request_digest, + generation_result.desired_state_version, + generation_result.expected_cluster_incarnation_uid, + generation_result.expected_namespace_uid, generation_result.trust_binding_digest, + generation_result.trust_config_revision, generation_result.target_generation, + generation_result.target_kid, generation_result.public_key_fingerprint, + generation_result.receipt_digest, generation_result.public_jwk_json + INTO result_environment, result_cluster, result_namespace, result_mode, + result_operation_digest, result_generation_request_digest, result_desired_state_version, + result_cluster_uid, result_namespace_uid, result_trust_digest, result_trust_revision, + result_generation, result_kid, result_fingerprint, result_receipt_digest, result_jwk + FROM account_jwt_signer_generation_results AS generation_result + WHERE generation_result.operation_id = p_operation_id + FOR UPDATE; + + IF NOT FOUND + OR state_operation_id IS DISTINCT FROM p_operation_id + OR state_version IS DISTINCT FROM p_desired_state_version + OR state_prepared_operation_id IS NOT NULL + OR operation_environment IS DISTINCT FROM p_environment_id + OR operation_cluster IS DISTINCT FROM p_cluster_id + OR operation_namespace IS DISTINCT FROM p_namespace + OR operation_mode IS DISTINCT FROM p_custody_mode + OR operation_digest IS DISTINCT FROM p_operation_digest + OR operation_expected_version + 1 IS DISTINCT FROM p_desired_state_version + OR operation_cluster_uid IS DISTINCT FROM p_cluster_uid + OR operation_namespace_uid IS DISTINCT FROM p_namespace_uid + OR operation_trust_digest IS DISTINCT FROM p_trust_binding_digest + OR operation_trust_revision IS DISTINCT FROM p_trust_config_revision + OR operation_target_generation IS DISTINCT FROM p_target_generation + OR operation_target_kid IS DISTINCT FROM p_target_kid + OR operation_target_algorithm IS DISTINCT FROM 'RS256' + OR result_environment IS DISTINCT FROM p_environment_id + OR result_cluster IS DISTINCT FROM p_cluster_id + OR result_namespace IS DISTINCT FROM p_namespace + OR result_mode IS DISTINCT FROM p_custody_mode + OR result_operation_digest IS DISTINCT FROM p_operation_digest + OR result_generation_request_digest IS DISTINCT FROM p_generation_request_digest + OR result_receipt_digest IS DISTINCT FROM p_generation_receipt_digest + OR result_desired_state_version IS DISTINCT FROM p_desired_state_version + OR result_cluster_uid IS DISTINCT FROM p_cluster_uid + OR result_namespace_uid IS DISTINCT FROM p_namespace_uid + OR result_trust_digest IS DISTINCT FROM p_trust_binding_digest + OR result_trust_revision IS DISTINCT FROM p_trust_config_revision + OR result_generation IS DISTINCT FROM p_target_generation + OR result_kid IS DISTINCT FROM p_target_kid + OR result_fingerprint IS DISTINCT FROM p_public_key_fingerprint + OR operation_previous_generation IS DISTINCT FROM + NULLIF(durable_active->>'generation', '')::BIGINT + OR operation_previous_kid IS DISTINCT FROM NULLIF(durable_active->>'kid', '') + OR operation_published_generation IS DISTINCT FROM + NULLIF(published_active->>'generation', '')::BIGINT + OR operation_published_kid IS DISTINCT FROM NULLIF(published_active->>'kid', '') THEN + RAISE EXCEPTION 'Account JWT JWKS evidence is stale or mismatched' USING ERRCODE = '23514'; + END IF; + + RETURN jsonb_build_object( + 'durableActive', durable_active, + 'publishedActive', published_active, + 'publicJwk', result_jwk::jsonb); +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_public_intent() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + current_evidence JSONB; + jwks_document JSONB; + marker_document JSONB; + key_document JSONB; + key_kid TEXT; + seen_kids TEXT[] := ARRAY[]::TEXT[]; + target_key_count INTEGER := 0; + public_jwk JSONB; +BEGIN + current_evidence := account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, NEW.operation_digest, NEW.generation_request_digest, + NEW.generation_receipt_digest, NEW.desired_state_version, + NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.trust_binding_digest, NEW.trust_config_revision, + NEW.target_generation, NEW.target_kid, NEW.public_key_fingerprint); + + IF NEW.expected_durable_active_json::jsonb IS DISTINCT FROM current_evidence->'durableActive' + OR NEW.expected_published_active_json::jsonb IS DISTINCT FROM current_evidence->'publishedActive' THEN + RAISE EXCEPTION 'Account JWT JWKS active fence is stale' USING ERRCODE = '23514'; + END IF; + + jwks_document := NEW.jwks_json::jsonb; + IF jsonb_typeof(jwks_document) IS DISTINCT FROM 'object' + OR jwks_document - ARRAY['keys'] <> '{}'::jsonb + OR jsonb_typeof(jwks_document->'keys') IS DISTINCT FROM 'array' + OR jsonb_array_length(jwks_document->'keys') < 1 + OR jsonb_array_length(jwks_document->'keys') > 64 THEN + RAISE EXCEPTION 'Account public JWKS has an unsupported shape' USING ERRCODE = '23514'; + END IF; + public_jwk := current_evidence->'publicJwk'; + FOR key_document IN + SELECT jwks_key.value + FROM jsonb_array_elements(jwks_document->'keys') AS jwks_key(value) + LOOP + IF jsonb_typeof(key_document) IS DISTINCT FROM 'object' + OR key_document - ARRAY['kty', 'use', 'alg', 'kid', 'key_ops', 'n', 'e'] <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys(key_document)) NOT BETWEEN 6 AND 7 + OR key_document ?| ARRAY['d', 'p', 'q', 'dp', 'dq', 'qi', 'oth', 'k'] + OR key_document->>'kty' IS DISTINCT FROM 'RSA' + OR key_document->>'use' IS DISTINCT FROM 'sig' + OR key_document->>'alg' IS DISTINCT FROM 'RS256' + OR key_document->>'kid' IS NULL + OR key_document->>'kid' !~ '^[A-Za-z0-9_-]{1,64}$' + OR jsonb_typeof(key_document->'n') IS DISTINCT FROM 'string' + OR jsonb_typeof(key_document->'e') IS DISTINCT FROM 'string' + OR key_document->>'n' !~ '^[A-Za-z0-9_-]+$' + OR key_document->>'e' !~ '^[A-Za-z0-9_-]+$' + OR (key_document ? 'key_ops' + AND (jsonb_typeof(key_document->'key_ops') IS DISTINCT FROM 'array' + OR key_document->'key_ops' <> '["verify"]'::jsonb)) THEN + RAISE EXCEPTION 'Account public JWKS contains an invalid or private key' USING ERRCODE = '23514'; + END IF; + key_kid := key_document->>'kid'; + IF key_kid = ANY(seen_kids) THEN + RAISE EXCEPTION 'Account public JWKS has duplicate kids' USING ERRCODE = '23514'; + END IF; + seen_kids := array_append(seen_kids, key_kid); + IF key_kid = NEW.target_kid THEN + target_key_count := target_key_count + 1; + IF key_document IS DISTINCT FROM public_jwk THEN + RAISE EXCEPTION 'Account public JWKS pending key differs from receipt' USING ERRCODE = '23514'; + END IF; + END IF; + END LOOP; + IF target_key_count <> 1 THEN + RAISE EXCEPTION 'Account public JWKS does not contain exactly one pending key' USING ERRCODE = '23514'; + END IF; + + marker_document := NEW.generation_marker_json::jsonb; + IF jsonb_typeof(marker_document) IS DISTINCT FROM 'object' + OR (marker_document - ARRAY['schemaVersion', 'phase', 'operationId', 'operationDigest', + 'generationRequestDigest', 'generationReceiptDigest', 'binding', 'publicConfigMap', + 'expectedDurableActive', 'expectedPublishedActive', 'pending']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys(marker_document)) <> 11 + OR jsonb_typeof((marker_document -> 'binding')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'binding') - ARRAY['environmentId', 'clusterId', 'namespace', + 'expectedClusterIncarnationUid', 'expectedNamespaceUid', 'trustBindingDigest', + 'trustConfigRevision', 'apiBindingDigest', 'apiConfigRevision']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'binding'))) <> 9 + OR jsonb_typeof((marker_document -> 'publicConfigMap')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'publicConfigMap') - ARRAY['name']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'publicConfigMap'))) <> 1 + OR jsonb_typeof((marker_document -> 'pending')) IS DISTINCT FROM 'object' + OR ((marker_document -> 'pending') - ARRAY['generation', 'kid', 'algorithm', + 'publicKeyFingerprint']) <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys((marker_document -> 'pending'))) <> 4 + OR (marker_document ->> 'schemaVersion') IS DISTINCT FROM '1' + OR (marker_document ->> 'phase') IS DISTINCT FROM 'PREPUBLISHED' + OR (marker_document ->> 'operationId') IS DISTINCT FROM NEW.operation_id::TEXT + OR (marker_document ->> 'operationDigest') IS DISTINCT FROM NEW.operation_digest + OR (marker_document ->> 'generationRequestDigest') IS DISTINCT FROM NEW.generation_request_digest + OR (marker_document ->> 'generationReceiptDigest') IS DISTINCT FROM NEW.generation_receipt_digest + OR ((marker_document -> 'binding') ->> 'environmentId') IS DISTINCT FROM NEW.environment_id + OR ((marker_document -> 'binding') ->> 'clusterId') IS DISTINCT FROM NEW.cluster_id + OR ((marker_document -> 'binding') ->> 'namespace') IS DISTINCT FROM NEW.kubernetes_namespace + OR ((marker_document -> 'binding') ->> 'expectedClusterIncarnationUid') IS DISTINCT FROM NEW.expected_cluster_incarnation_uid::TEXT + OR ((marker_document -> 'binding') ->> 'expectedNamespaceUid') IS DISTINCT FROM NEW.expected_namespace_uid::TEXT + OR ((marker_document -> 'binding') ->> 'trustBindingDigest') IS DISTINCT FROM NEW.trust_binding_digest + OR ((marker_document -> 'binding') ->> 'trustConfigRevision') IS DISTINCT FROM NEW.trust_config_revision + OR ((marker_document -> 'binding') ->> 'apiBindingDigest') IS DISTINCT FROM NEW.api_binding_digest + OR ((marker_document -> 'binding') ->> 'apiConfigRevision') IS DISTINCT FROM NEW.api_config_revision + OR ((marker_document -> 'publicConfigMap') ->> 'name') IS DISTINCT FROM 'jwt-jwks' + OR (marker_document -> 'expectedDurableActive') IS DISTINCT FROM (NEW.expected_durable_active_json::jsonb) + OR (marker_document -> 'expectedPublishedActive') IS DISTINCT FROM (NEW.expected_published_active_json::jsonb) + OR ((marker_document -> 'pending') ->> 'generation') IS DISTINCT FROM NEW.target_generation::TEXT + OR ((marker_document -> 'pending') ->> 'kid') IS DISTINCT FROM NEW.target_kid + OR ((marker_document -> 'pending') ->> 'algorithm') IS DISTINCT FROM 'RS256' + OR ((marker_document -> 'pending') ->> 'publicKeyFingerprint') IS DISTINCT FROM NEW.public_key_fingerprint THEN + RAISE EXCEPTION 'Account public generation marker is stale or mismatched' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_publication_receipt() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + intent_row account_jwt_jwks_prepublication_intents%ROWTYPE; +BEGIN + PERFORM account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, (SELECT intent.operation_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_request_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_receipt_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.desired_state_version FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_cluster_incarnation_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_namespace_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_binding_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_config_revision FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_generation FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_kid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.public_key_fingerprint FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id)); + SELECT intent.* INTO intent_row + FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id + FOR UPDATE; + IF NOT FOUND + OR intent_row.environment_id IS DISTINCT FROM NEW.environment_id + OR intent_row.cluster_id IS DISTINCT FROM NEW.cluster_id + OR intent_row.kubernetes_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR intent_row.custody_mode IS DISTINCT FROM NEW.custody_mode + OR intent_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR intent_row.config_map_uid IS DISTINCT FROM NEW.config_map_uid + OR intent_row.expected_resource_version IS DISTINCT FROM NEW.expected_resource_version + OR intent_row.public_data_digest IS DISTINCT FROM NEW.public_data_digest + OR NEW.expected_resource_version = NEW.observed_resource_version THEN + RAISE EXCEPTION 'Account JWT publication receipt does not match current intent' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_validate_mount_observation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + intent_row account_jwt_jwks_prepublication_intents%ROWTYPE; + receipt_row account_jwt_jwks_publication_receipts%ROWTYPE; +BEGIN + PERFORM account_jwt_jwks_lock_current_generation( + NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, (SELECT intent.operation_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_request_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.generation_receipt_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.desired_state_version FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_cluster_incarnation_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.expected_namespace_uid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_binding_digest FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.trust_config_revision FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_generation FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.target_kid FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id), + (SELECT intent.public_key_fingerprint FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id)); + SELECT intent.* INTO intent_row + FROM account_jwt_jwks_prepublication_intents AS intent + WHERE intent.operation_id = NEW.operation_id + FOR UPDATE; + SELECT receipt.* INTO receipt_row + FROM account_jwt_jwks_publication_receipts AS receipt + WHERE receipt.operation_id = NEW.operation_id + FOR UPDATE; + IF NOT FOUND + OR intent_row.environment_id IS DISTINCT FROM NEW.environment_id + OR intent_row.cluster_id IS DISTINCT FROM NEW.cluster_id + OR intent_row.kubernetes_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR intent_row.custody_mode IS DISTINCT FROM NEW.custody_mode + OR intent_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR receipt_row.intent_digest IS DISTINCT FROM NEW.intent_digest + OR receipt_row.receipt_digest IS DISTINCT FROM NEW.publication_receipt_digest + OR intent_row.generation_marker_digest IS DISTINCT FROM NEW.generation_marker_digest + OR intent_row.public_data_digest IS DISTINCT FROM NEW.public_data_digest + OR intent_row.public_key_fingerprint IS DISTINCT FROM NEW.public_key_fingerprint THEN + RAISE EXCEPTION 'Mounted Account JWT correspondence is stale or mismatched' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_jwks_reject_mutation() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT JWKS publication evidence is immutable' USING ERRCODE = '55000'; +END; +$$; + +CREATE TRIGGER account_jwt_jwks_intent_current_guard + BEFORE INSERT ON account_jwt_jwks_prepublication_intents + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_public_intent(); +CREATE TRIGGER account_jwt_jwks_receipt_current_guard + BEFORE INSERT ON account_jwt_jwks_publication_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_publication_receipt(); +CREATE TRIGGER account_jwt_jwks_mount_current_guard + BEFORE INSERT ON account_jwt_jwks_mount_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_validate_mount_observation(); + +CREATE TRIGGER account_jwt_jwks_intent_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_prepublication_intents + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_receipt_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_publication_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_mount_immutable + BEFORE UPDATE OR DELETE ON account_jwt_jwks_mount_observations + FOR EACH ROW EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); + +CREATE TRIGGER account_jwt_jwks_intent_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_prepublication_intents + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_receipt_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_publication_receipts + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +CREATE TRIGGER account_jwt_jwks_mount_no_truncate + BEFORE TRUNCATE ON account_jwt_jwks_mount_observations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_jwks_reject_mutation(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V103__account_jwt_readiness_probes.sql b/services/account-service/src/main/resources/db/migration/V103__account_jwt_readiness_probes.sql new file mode 100644 index 0000000000..611ce071cf --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V103__account_jwt_readiness_probes.sql @@ -0,0 +1,466 @@ +-- Durable, operation-scoped probe plans for the interim Account-mounted JWT signer. +-- Plans bind existing desired-state, generation-result, JWKS publication, and mount evidence; +-- this migration creates no second key authority, validator endpoint, or promotion transition. +CREATE TABLE account_jwt_readiness_probe_plans ( + rotation_operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + generation_receipt_digest VARCHAR(64) NOT NULL, + desired_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_public_key_fingerprint VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + expected_published_generation BIGINT, + expected_published_kid VARCHAR(64), + publication_intent_digest VARCHAR(64) NOT NULL, + publication_receipt_digest VARCHAR(64) NOT NULL, + mounted_observation_digest VARCHAR(64) NOT NULL, + applicability_matrix_json TEXT NOT NULL, + applicability_matrix_digest VARCHAR(64) NOT NULL, + validator_inventory_complete BOOLEAN NOT NULL DEFAULT FALSE, + maximum_cache_age_seconds SMALLINT NOT NULL, + planned_at_epoch_seconds BIGINT NOT NULL, + not_before_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + plan_version SMALLINT NOT NULL DEFAULT 1, + plan_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_readiness_plan_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_operation_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_result_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_signer_generation_results(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_publication_intent_fk + FOREIGN KEY (rotation_operation_id, publication_intent_digest) + REFERENCES account_jwt_jwks_prepublication_intents(operation_id, intent_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_publication_receipt_fk + FOREIGN KEY (rotation_operation_id, publication_intent_digest, publication_receipt_digest) + REFERENCES account_jwt_jwks_publication_receipts( + operation_id, intent_digest, receipt_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_mount_observation_fk + FOREIGN KEY (rotation_operation_id) + REFERENCES account_jwt_jwks_mount_observations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_plan_identity_check + CHECK (rotation_operation_id::text ~ + '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK' + AND desired_state_version > 1 + AND target_generation > COALESCE(expected_active_generation, 0) + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL + AND expected_published_generation IS NULL AND expected_published_kid IS NULL) + OR (expected_active_generation IS NOT NULL AND expected_active_kid IS NOT NULL + AND expected_published_generation IS NOT NULL AND expected_published_kid IS NOT NULL + AND expected_active_generation > 0 + AND expected_active_generation = expected_published_generation + AND expected_active_kid = expected_published_kid)) + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_active_kid IS NULL OR expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$') + AND target_kid <> expected_active_kid + AND target_public_key_fingerprint ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_readiness_plan_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND generation_receipt_digest ~ '^[0-9a-f]{64}$' + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND publication_intent_digest ~ '^[0-9a-f]{64}$' + AND publication_receipt_digest ~ '^[0-9a-f]{64}$' + AND mounted_observation_digest ~ '^[0-9a-f]{64}$' + AND applicability_matrix_digest ~ '^[0-9a-f]{64}$' + AND plan_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_readiness_plan_revision_check + CHECK (trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_readiness_plan_trust_uid_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID), + CONSTRAINT account_jwt_readiness_plan_inventory_check + CHECK (octet_length(applicability_matrix_json) BETWEEN 2 AND 8192), + CONSTRAINT account_jwt_readiness_plan_window_check + CHECK (maximum_cache_age_seconds BETWEEN 1 AND 300 + AND planned_at_epoch_seconds > 0 + AND not_before_epoch_seconds >= planned_at_epoch_seconds + maximum_cache_age_seconds + AND expires_at_epoch_seconds > not_before_epoch_seconds + AND expires_at_epoch_seconds - not_before_epoch_seconds <= 300 + AND plan_version = 1), + CONSTRAINT account_jwt_readiness_plan_digest_unique + UNIQUE (rotation_operation_id, plan_digest) +); + +CREATE TABLE account_jwt_readiness_probe_entries ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + jti UUID NOT NULL UNIQUE, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + registry_version SMALLINT NOT NULL DEFAULT 1, + entry_version BIGINT NOT NULL DEFAULT 1, + planned_issued_at_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + state VARCHAR(16) NOT NULL DEFAULT 'PLANNED', + terminal_outcome VARCHAR(16), + signing_attempted_at_epoch_seconds BIGINT, + compact_token_sha256 VARCHAR(64), + verification_receipt_version SMALLINT, + verification_source_entry_version BIGINT, + verified_at_epoch_seconds BIGINT, + verified_kid VARCHAR(64), + validator_instance_id VARCHAR(128), + validator_binding_digest VARCHAR(64), + validator_config_revision VARCHAR(128), + validator_peer_uri VARCHAR(256), + validator_peer_spki_sha256 VARCHAR(64), + verification_receipt_sha256 VARCHAR(64), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind), + CONSTRAINT account_jwt_readiness_probe_plan_fk + FOREIGN KEY (rotation_operation_id, plan_digest) + REFERENCES account_jwt_readiness_probe_plans(rotation_operation_id, plan_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_probe_jti_v4_check + CHECK (jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_jwt_readiness_probe_identity_check + CHECK (validator_id ~ '^[a-z0-9][a-z0-9-]{0,62}$' + AND token_profile ~ '^[a-z0-9][a-z0-9-]{0,127}$' + AND audience ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND probe_kind IN ('CANARY', 'REPRESENTATIVE') + AND target_generation > COALESCE(expected_active_generation, 0) + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation IS NOT NULL AND expected_active_kid IS NOT NULL + AND expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid), + CONSTRAINT account_jwt_readiness_probe_state_check + CHECK (state IN ('PLANNED', 'ISSUED', 'VERIFIED', 'RETIRED', 'CLEANED', 'EXPIRED', 'ABORTED') + AND (terminal_outcome IS NULL OR terminal_outcome IN ('EXPIRED', 'ABORTED')) + AND ((state IN ('EXPIRED', 'ABORTED', 'CLEANED') AND terminal_outcome IS NOT NULL) + OR (state NOT IN ('EXPIRED', 'ABORTED', 'CLEANED') AND terminal_outcome IS NULL))), + CONSTRAINT account_jwt_readiness_probe_evidence_check + CHECK (plan_digest ~ '^[0-9a-f]{64}$' + AND registry_version = 1 + AND entry_version > 0 + AND planned_issued_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > planned_issued_at_epoch_seconds + AND (compact_token_sha256 IS NULL OR compact_token_sha256 ~ '^[0-9a-f]{64}$') + AND (signing_attempted_at_epoch_seconds IS NULL + OR (signing_attempted_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND signing_attempted_at_epoch_seconds < expires_at_epoch_seconds)) + AND ((compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL) + OR (compact_token_sha256 IS NOT NULL AND signing_attempted_at_epoch_seconds IS NOT NULL)) + AND (state NOT IN ('ISSUED', 'VERIFIED', 'RETIRED') + OR compact_token_sha256 IS NOT NULL) + AND (verification_receipt_version IS NULL OR verification_receipt_version = 1) + AND (verification_source_entry_version IS NULL OR verification_source_entry_version > 0) + AND (verified_at_epoch_seconds IS NULL + OR (verified_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND verified_at_epoch_seconds < expires_at_epoch_seconds)) + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND (validator_instance_id IS NULL + OR validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_binding_digest IS NULL OR validator_binding_digest ~ '^[0-9a-f]{64}$') + AND (validator_config_revision IS NULL + OR validator_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_peer_uri IS NULL + OR validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness$') + AND (validator_peer_spki_sha256 IS NULL + OR validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$') + AND (verification_receipt_sha256 IS NULL + OR verification_receipt_sha256 ~ '^[0-9a-f]{64}$') + AND ((verification_receipt_sha256 IS NULL + AND verification_receipt_version IS NULL + AND verification_source_entry_version IS NULL + AND verified_at_epoch_seconds IS NULL + AND verified_kid IS NULL + AND validator_instance_id IS NULL + AND validator_binding_digest IS NULL + AND validator_config_revision IS NULL + AND validator_peer_uri IS NULL + AND validator_peer_spki_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 1 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid IS NOT NULL + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL)) + AND (state NOT IN ('VERIFIED', 'RETIRED') OR verification_receipt_sha256 IS NOT NULL) + AND (state NOT IN ('PLANNED', 'ISSUED') OR verification_receipt_sha256 IS NULL)) +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_readiness_plan_inventory_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + matrix jsonb; +BEGIN + IF NEW.validator_inventory_complete THEN + RAISE EXCEPTION 'Readiness inventory is incomplete without authenticated validator evidence' + USING ERRCODE = '23514'; + END IF; + matrix := NEW.applicability_matrix_json::jsonb; + IF matrix ->> 'inventoryStatus' <> 'PARTIAL_UNCONFIRMED' + OR matrix ->> 'schemaVersion' <> '1' + OR jsonb_array_length(matrix -> 'validators') <> 1 + OR matrix #>> '{validators,0,validatorId}' <> 'account-service' + OR jsonb_array_length(matrix #> '{validators,0,applicableProfiles}') <> 3 + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Readiness applicability must bind the exact partial Account profile set' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_plan_inventory + BEFORE INSERT ON account_jwt_readiness_probe_plans + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_plan_inventory_guard(); + +CREATE FUNCTION account_jwt_readiness_plan_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT readiness probe plans are immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_plan_immutable + BEFORE UPDATE OR DELETE ON account_jwt_readiness_probe_plans + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_plan_immutable_guard(); + +CREATE FUNCTION account_jwt_readiness_entry_lifecycle_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; +BEGIN + IF TG_OP = 'INSERT' THEN + IF NEW.state <> 'PLANNED' + OR NEW.entry_version <> 1 + OR NEW.terminal_outcome IS NOT NULL + OR NEW.compact_token_sha256 IS NOT NULL + OR NEW.signing_attempted_at_epoch_seconds IS NOT NULL + OR NEW.verification_receipt_sha256 IS NOT NULL THEN + RAISE EXCEPTION 'Account JWT readiness entries must begin PLANNED' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM plan_row.not_before_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Account JWT readiness entry differs from its immutable plan' + USING ERRCODE = '23514'; + END IF; + IF NEW.probe_kind = 'CANARY' THEN + IF NEW.validator_id <> 'account-service' + OR NEW.token_profile <> 'account-jwt-readiness-canary' + OR NEW.audience <> 'firemud-account-jwt-readiness' THEN + RAISE EXCEPTION 'Account JWT readiness canary shape is not fixed' + USING ERRCODE = '23514'; + END IF; + ELSIF NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') + AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'applicableProfiles') + AS applicable(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND applicable.value ->> 'tokenProfile' = NEW.token_profile + AND applicable.value ->> 'audience' = NEW.audience + ) THEN + RAISE EXCEPTION 'Account JWT readiness profile is outside its applicability matrix' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT readiness evidence is retained' USING ERRCODE = '23514'; + END IF; + + IF NEW.rotation_operation_id IS DISTINCT FROM OLD.rotation_operation_id + OR NEW.plan_digest IS DISTINCT FROM OLD.plan_digest + OR NEW.validator_id IS DISTINCT FROM OLD.validator_id + OR NEW.token_profile IS DISTINCT FROM OLD.token_profile + OR NEW.audience IS DISTINCT FROM OLD.audience + OR NEW.probe_kind IS DISTINCT FROM OLD.probe_kind + OR NEW.jti IS DISTINCT FROM OLD.jti + OR NEW.target_generation IS DISTINCT FROM OLD.target_generation + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM OLD.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM OLD.expected_active_kid + OR NEW.registry_version IS DISTINCT FROM OLD.registry_version + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM OLD.planned_issued_at_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM OLD.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Account JWT readiness probe identity is immutable' USING ERRCODE = '23514'; + END IF; + + IF NEW.entry_version <> OLD.entry_version + 1 THEN + RAISE EXCEPTION 'Account JWT readiness entry version must advance once' USING ERRCODE = '23514'; + END IF; + + IF OLD.state = 'PLANNED' + AND NEW.state = 'PLANNED' + AND OLD.compact_token_sha256 IS NULL + AND NEW.compact_token_sha256 IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds >= OLD.planned_issued_at_epoch_seconds + AND NEW.signing_attempted_at_epoch_seconds < OLD.expires_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + + IF OLD.state = 'PLANNED' + AND NEW.state = 'ISSUED' + AND OLD.compact_token_sha256 IS NOT NULL + AND NEW.compact_token_sha256 = OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds = OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + + IF OLD.state = 'ISSUED' AND NEW.state = 'VERIFIED' THEN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.compact_token_sha256 IS DISTINCT FROM OLD.compact_token_sha256 + OR NEW.signing_attempted_at_epoch_seconds + IS DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + OR NEW.verification_receipt_version IS DISTINCT FROM 1 + OR NEW.verification_source_entry_version IS DISTINCT FROM OLD.entry_version + OR NEW.entry_version IS DISTINCT FROM OLD.entry_version + 1 + OR NEW.verified_kid IS DISTINCT FROM OLD.target_kid + OR NEW.verified_at_epoch_seconds IS NULL + OR NEW.verified_at_epoch_seconds < OLD.planned_issued_at_epoch_seconds + OR NEW.verified_at_epoch_seconds >= OLD.expires_at_epoch_seconds + OR to_timestamp(NEW.verified_at_epoch_seconds) > CURRENT_TIMESTAMP + OR NEW.validator_id IS DISTINCT FROM 'account-service' + OR NEW.validator_peer_uri IS DISTINCT FROM + 'spiffe://firemud/ns/' || plan_row.kubernetes_namespace || '/sa/account-jwt-readiness-harness' + OR CURRENT_TIMESTAMP < to_timestamp(OLD.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + OR NEW.terminal_outcome IS NOT NULL THEN + RAISE EXCEPTION 'Verified readiness probe differs from its current immutable plan' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'ABORTED' + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.terminal_outcome = 'ABORTED' THEN + RETURN NEW; + END IF; + + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'EXPIRED' + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.terminal_outcome = 'EXPIRED' THEN + RETURN NEW; + END IF; + + IF OLD.state IN ('ABORTED', 'EXPIRED') + AND NEW.state = 'CLEANED' + AND NEW.terminal_outcome = OLD.terminal_outcome + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 THEN + RETURN NEW; + END IF; + + -- This table records bounded non-authorizing observations only. RETIRED and every promotion + -- transition remain unavailable until their separate Account owner contracts are implemented. + RAISE EXCEPTION 'Account JWT readiness probe lifecycle transition is unavailable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_lifecycle + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V106__account_jwt_signer_promotion_lifecycle.sql b/services/account-service/src/main/resources/db/migration/V106__account_jwt_signer_promotion_lifecycle.sql new file mode 100644 index 0000000000..d867d0d0b8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V106__account_jwt_signer_promotion_lifecycle.sql @@ -0,0 +1,798 @@ +-- Forward-only lifecycle extension for the existing Account-owned signer authority. The +-- generation operation remains immutable; one separate promotion operation binds it to the +-- authenticated Secret/JWKS/probe evidence and owns the PREPARED -> COMMITTED|ABORTED CAS. + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_action_check; + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_slots_check; + +ALTER TABLE account_jwt_signer_promotion_operations + DROP CONSTRAINT account_jwt_signer_promotion_status_check; + +ALTER TABLE account_jwt_signer_promotion_operations + ADD COLUMN generation_operation_id UUID, + ADD COLUMN expected_cluster_incarnation_uid UUID, + ADD COLUMN expected_namespace_uid UUID, + ADD COLUMN materializer_trust_binding_digest VARCHAR(64), + ADD COLUMN materializer_trust_config_revision VARCHAR(128), + ADD COLUMN api_binding_digest VARCHAR(64), + ADD COLUMN api_config_revision VARCHAR(128), + ADD COLUMN expected_private_secret_uid UUID, + ADD COLUMN expected_public_config_map_uid UUID, + ADD COLUMN prepublication_intent_digest VARCHAR(64), + ADD COLUMN prepublication_receipt_digest VARCHAR(64), + ADD COLUMN mounted_observation_digest VARCHAR(64), + ADD COLUMN readiness_plan_digest VARCHAR(64), + ADD COLUMN readiness_evidence_digest VARCHAR(64), + ADD COLUMN expected_public_jwks_json TEXT, + ADD COLUMN expected_active_generation_marker_json TEXT, + ADD COLUMN private_promotion_observed_resource_version VARCHAR(256), + ADD COLUMN private_promotion_receipt_digest VARCHAR(64), + ADD COLUMN private_promotion_dispatched_at TIMESTAMPTZ, + ADD COLUMN active_jwks_observed_resource_version VARCHAR(256), + ADD COLUMN active_jwks_public_data_digest VARCHAR(64), + ADD COLUMN active_jwks_receipt_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_signer_promotion_generation_fk + FOREIGN KEY (generation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT, + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_action_check + CHECK ((operation_action = 'MATERIALIZE_PENDING' + AND allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea) + OR (operation_action = 'PROMOTE_PENDING' + AND allowed_private_slots_canonical_bytes = + '\x5b2263757272656e74222c2270656e64696e67222c2270726576696f7573225d'::bytea)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_status_check + CHECK (status IN ('PREPARED', 'COMMITTED', 'ABORTED')), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_identity_check + CHECK (operation_action <> 'PROMOTE_PENDING' + OR (generation_operation_id IS NOT NULL + AND expected_cluster_incarnation_uid IS NOT NULL + AND expected_namespace_uid IS NOT NULL + AND materializer_trust_binding_digest IS NOT NULL + AND materializer_trust_binding_digest ~ '^[0-9a-f]{64}$' + AND materializer_trust_config_revision IS NOT NULL + AND materializer_trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest IS NOT NULL + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND api_config_revision IS NOT NULL + AND api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND expected_private_secret_uid IS NOT NULL + AND expected_public_config_map_uid IS NOT NULL + AND prepublication_intent_digest IS NOT NULL + AND prepublication_intent_digest ~ '^[0-9a-f]{64}$' + AND prepublication_receipt_digest IS NOT NULL + AND prepublication_receipt_digest ~ '^[0-9a-f]{64}$' + AND mounted_observation_digest IS NOT NULL + AND mounted_observation_digest ~ '^[0-9a-f]{64}$' + AND readiness_plan_digest IS NOT NULL + AND readiness_plan_digest ~ '^[0-9a-f]{64}$' + AND readiness_evidence_digest IS NOT NULL + AND readiness_evidence_digest ~ '^[0-9a-f]{64}$' + AND expected_public_jwks_json IS NOT NULL + AND expected_active_generation_marker_json IS NOT NULL)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_uid_check + CHECK ((expected_cluster_incarnation_uid IS NULL + OR expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_namespace_uid IS NULL + OR expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_private_secret_uid IS NULL + OR expected_private_secret_uid <> '00000000-0000-0000-0000-000000000000'::UUID) + AND (expected_public_config_map_uid IS NULL + OR expected_public_config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID)), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_digest_check + CHECK ((materializer_trust_binding_digest IS NULL + OR materializer_trust_binding_digest ~ '^[0-9a-f]{64}$') + AND (api_binding_digest IS NULL OR api_binding_digest ~ '^[0-9a-f]{64}$') + AND (prepublication_intent_digest IS NULL + OR prepublication_intent_digest ~ '^[0-9a-f]{64}$') + AND (prepublication_receipt_digest IS NULL + OR prepublication_receipt_digest ~ '^[0-9a-f]{64}$') + AND (mounted_observation_digest IS NULL + OR mounted_observation_digest ~ '^[0-9a-f]{64}$') + AND (readiness_plan_digest IS NULL + OR readiness_plan_digest ~ '^[0-9a-f]{64}$') + AND (readiness_evidence_digest IS NULL + OR readiness_evidence_digest ~ '^[0-9a-f]{64}$') + AND (private_promotion_receipt_digest IS NULL + OR private_promotion_receipt_digest ~ '^[0-9a-f]{64}$') + AND (active_jwks_public_data_digest IS NULL + OR active_jwks_public_data_digest ~ '^[0-9a-f]{64}$') + AND (active_jwks_receipt_digest IS NULL + OR active_jwks_receipt_digest ~ '^[0-9a-f]{64}$')), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_rv_check + CHECK ((private_promotion_observed_resource_version IS NULL + OR (private_promotion_observed_resource_version ~ '^[!-~]+$' + AND char_length(private_promotion_observed_resource_version) BETWEEN 1 AND 256)) + AND (active_jwks_observed_resource_version IS NULL + OR (active_jwks_observed_resource_version ~ '^[!-~]+$' + AND char_length(active_jwks_observed_resource_version) BETWEEN 1 AND 256))), + ADD CONSTRAINT account_jwt_signer_promotion_lifecycle_content_check + CHECK ((expected_public_jwks_json IS NULL OR octet_length(expected_public_jwks_json) BETWEEN 1 AND 262144) + AND (expected_active_generation_marker_json IS NULL + OR octet_length(expected_active_generation_marker_json) BETWEEN 1 AND 16384)), + ADD CONSTRAINT account_jwt_signer_promotion_dispatch_check + CHECK ((private_promotion_receipt_digest IS NULL + OR private_promotion_dispatched_at IS NOT NULL) + AND (status <> 'COMMITTED' + OR (private_promotion_dispatched_at IS NOT NULL + AND private_promotion_receipt_digest IS NOT NULL + AND active_jwks_receipt_digest IS NOT NULL)) + AND (status <> 'ABORTED' + OR (private_promotion_dispatched_at IS NULL + AND private_promotion_receipt_digest IS NULL + AND active_jwks_receipt_digest IS NULL))); + +-- Enrollment is admitted only after both independently protected bindings and a live read of the +-- fixed pre-created public ConfigMap agree on the environment/cluster/namespace incarnation. +-- Existing rows with NULL pins are intentionally not backfilled or promoted. +ALTER TABLE account_jwt_signer_desired_states + ADD COLUMN enrollment_cluster_incarnation_uid UUID, + ADD COLUMN enrollment_namespace_uid UUID, + ADD COLUMN enrollment_materializer_binding_digest VARCHAR(64), + ADD COLUMN enrollment_materializer_config_revision VARCHAR(128), + ADD COLUMN enrollment_api_binding_digest VARCHAR(64), + ADD COLUMN enrollment_api_config_revision VARCHAR(128), + ADD COLUMN enrollment_public_config_map_uid UUID, + ADD COLUMN enrollment_public_config_map_resource_version VARCHAR(256), + ADD COLUMN enrollment_public_config_map_snapshot_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_signer_enrollment_shape_check + CHECK ((enrollment_cluster_incarnation_uid IS NULL + AND enrollment_namespace_uid IS NULL + AND enrollment_materializer_binding_digest IS NULL + AND enrollment_materializer_config_revision IS NULL + AND enrollment_api_binding_digest IS NULL + AND enrollment_api_config_revision IS NULL + AND enrollment_public_config_map_uid IS NULL + AND enrollment_public_config_map_resource_version IS NULL + AND enrollment_public_config_map_snapshot_digest IS NULL) + OR (enrollment_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_cluster_incarnation_uid IS NOT NULL + AND enrollment_namespace_uid IS NOT NULL + AND enrollment_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_materializer_binding_digest IS NOT NULL + AND enrollment_materializer_binding_digest ~ '^[0-9a-f]{64}$' + AND enrollment_materializer_config_revision IS NOT NULL + AND enrollment_materializer_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND enrollment_api_binding_digest IS NOT NULL + AND enrollment_api_binding_digest ~ '^[0-9a-f]{64}$' + AND enrollment_api_config_revision IS NOT NULL + AND enrollment_api_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND enrollment_public_config_map_uid IS NOT NULL + AND enrollment_public_config_map_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND enrollment_public_config_map_resource_version IS NOT NULL + AND enrollment_public_config_map_resource_version ~ '^[!-~]+$' + AND char_length(enrollment_public_config_map_resource_version) BETWEEN 1 AND 256 + AND enrollment_public_config_map_snapshot_digest IS NOT NULL + AND enrollment_public_config_map_snapshot_digest ~ '^[0-9a-f]{64}$')); + +-- A generation whose readiness proof cannot enter PREPARED may be terminally abandoned by +-- Account. This receipt only releases that exact current pointer; it never changes either active +-- fence or records authority to materialize, promote, or replace a key. +CREATE TABLE account_jwt_signer_generation_abort_receipts ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + generation_request_digest VARCHAR(64) NOT NULL, + generation_receipt_digest VARCHAR(64) NOT NULL, + expected_state_version BIGINT NOT NULL, + resulting_state_version BIGINT NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + durable_active_generation BIGINT, + durable_active_kid VARCHAR(128), + published_active_generation BIGINT, + published_active_kid VARCHAR(128), + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_generation_abort_state_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_generation_abort_operation_fk + FOREIGN KEY (operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_generation_abort_result_fk + FOREIGN KEY (operation_id) + REFERENCES account_jwt_signer_generation_results(operation_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_generation_abort_version_check + CHECK (expected_state_version > 1 + AND expected_state_version < 9223372036854775807 + AND resulting_state_version = expected_state_version + 1), + CONSTRAINT account_jwt_generation_abort_digest_check + CHECK (operation_digest ~ '^[0-9a-f]{64}$' + AND generation_request_digest ~ '^[0-9a-f]{64}$' + AND generation_receipt_digest ~ '^[0-9a-f]{64}$' + AND trust_binding_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_generation_abort_trust_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_generation_abort_active_shape_check + CHECK (((durable_active_generation IS NULL AND durable_active_kid IS NULL) + OR (durable_active_generation > 0 + AND durable_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND ((published_active_generation IS NULL AND published_active_kid IS NULL) + OR (published_active_generation > 0 + AND published_active_kid ~ '^[A-Za-z0-9_-]{1,64}$'))) +); + +-- PREPARED proof is immutable. Account first durably records its one-way peer dispatch before +-- returning mutation authority. Only the two exact public-only CAS receipts may then be filled +-- once, followed by one terminal state transition. No receipt includes, hashes, or returns +-- private Secret bytes. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_signer_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + private_receipt_changed BOOLEAN; + private_dispatch_changed BOOLEAN; + jwks_receipt_changed BOOLEAN; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer promotion history cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF (NEW.operation_id, NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.custody_mode, NEW.request_digest_version, NEW.request_digest, + NEW.expected_record_version, NEW.expected_previous_generation, NEW.expected_previous_kid, + NEW.target_generation, NEW.target_kid, NEW.target_algorithm, + NEW.target_public_key_fingerprint, NEW.expected_private_secret_resource_version, + NEW.expected_public_jwks_resource_version, NEW.expected_public_active_generation, + NEW.expected_public_active_kid, NEW.operation_action, + NEW.allowed_private_slots_canonical_bytes, NEW.generation_operation_id, + NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.materializer_trust_binding_digest, NEW.materializer_trust_config_revision, + NEW.api_binding_digest, NEW.api_config_revision, NEW.expected_private_secret_uid, + NEW.expected_public_config_map_uid, NEW.prepublication_intent_digest, + NEW.prepublication_receipt_digest, NEW.mounted_observation_digest, + NEW.readiness_plan_digest, NEW.readiness_evidence_digest, + NEW.expected_public_jwks_json, NEW.expected_active_generation_marker_json, + NEW.created_at) + IS DISTINCT FROM + (OLD.operation_id, OLD.environment_id, OLD.cluster_id, OLD.kubernetes_namespace, + OLD.custody_mode, OLD.request_digest_version, OLD.request_digest, + OLD.expected_record_version, OLD.expected_previous_generation, OLD.expected_previous_kid, + OLD.target_generation, OLD.target_kid, OLD.target_algorithm, + OLD.target_public_key_fingerprint, OLD.expected_private_secret_resource_version, + OLD.expected_public_jwks_resource_version, OLD.expected_public_active_generation, + OLD.expected_public_active_kid, OLD.operation_action, + OLD.allowed_private_slots_canonical_bytes, OLD.generation_operation_id, + OLD.expected_cluster_incarnation_uid, OLD.expected_namespace_uid, + OLD.materializer_trust_binding_digest, OLD.materializer_trust_config_revision, + OLD.api_binding_digest, OLD.api_config_revision, OLD.expected_private_secret_uid, + OLD.expected_public_config_map_uid, OLD.prepublication_intent_digest, + OLD.prepublication_receipt_digest, OLD.mounted_observation_digest, + OLD.readiness_plan_digest, OLD.readiness_evidence_digest, + OLD.expected_public_jwks_json, OLD.expected_active_generation_marker_json, + OLD.created_at) THEN + RAISE EXCEPTION 'Account JWT signer promotion request is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF OLD.status <> 'PREPARED' OR NEW.status NOT IN ('PREPARED', 'COMMITTED', 'ABORTED') THEN + RAISE EXCEPTION 'Account JWT signer promotion is already terminal' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + + private_receipt_changed := + (NEW.private_promotion_observed_resource_version, + NEW.private_promotion_receipt_digest) + IS DISTINCT FROM + (OLD.private_promotion_observed_resource_version, + OLD.private_promotion_receipt_digest); + private_dispatch_changed := + NEW.private_promotion_dispatched_at IS DISTINCT FROM OLD.private_promotion_dispatched_at; + jwks_receipt_changed := + (NEW.active_jwks_observed_resource_version, NEW.active_jwks_public_data_digest, + NEW.active_jwks_receipt_digest) + IS DISTINCT FROM + (OLD.active_jwks_observed_resource_version, OLD.active_jwks_public_data_digest, + OLD.active_jwks_receipt_digest); + + IF private_receipt_changed THEN + IF OLD.private_promotion_receipt_digest IS NOT NULL + OR NEW.private_promotion_receipt_digest IS NULL + OR NEW.private_promotion_observed_resource_version IS NULL + OR jwks_receipt_changed OR NEW.status <> 'PREPARED' THEN + RAISE EXCEPTION 'JWT private promotion receipt is not a first exact readback' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF private_dispatch_changed THEN + IF OLD.private_promotion_dispatched_at IS NOT NULL + OR NEW.private_promotion_dispatched_at IS NULL + OR NEW.status <> 'PREPARED' + OR private_receipt_changed OR jwks_receipt_changed THEN + RAISE EXCEPTION 'JWT private promotion dispatch is not a first durable authorization' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF jwks_receipt_changed THEN + IF OLD.active_jwks_receipt_digest IS NOT NULL + OR NEW.active_jwks_receipt_digest IS NULL + OR NEW.active_jwks_observed_resource_version IS NULL + OR NEW.active_jwks_public_data_digest IS NULL + OR OLD.private_promotion_receipt_digest IS NULL + OR NEW.status <> 'PREPARED' THEN + RAISE EXCEPTION 'JWT active JWKS receipt is not a first exact readback' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + END IF; + IF NEW.status = OLD.status AND NOT private_dispatch_changed + AND NOT private_receipt_changed AND NOT jwks_receipt_changed THEN + RAISE EXCEPTION 'JWT promotion update has no exact receipt transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF NEW.status = 'COMMITTED' + AND (NEW.private_promotion_dispatched_at IS NULL + OR NEW.private_promotion_receipt_digest IS NULL + OR NEW.active_jwks_receipt_digest IS NULL) THEN + RAISE EXCEPTION 'JWT promotion cannot commit without both exact resource receipts' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + IF NEW.status = 'ABORTED' + AND (OLD.private_promotion_dispatched_at IS NOT NULL + OR OLD.private_promotion_receipt_digest IS NOT NULL + OR OLD.active_jwks_receipt_digest IS NOT NULL) THEN + RAISE EXCEPTION 'Dispatched JWT promotion must remain PREPARED for reconciliation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_jwt_signer_desired_state_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_row RECORD; +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer desired state cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + IF (NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode, + NEW.private_secret_name, NEW.public_jwks_config_map_name, NEW.created_at, + NEW.enrollment_cluster_incarnation_uid, NEW.enrollment_namespace_uid, + NEW.enrollment_materializer_binding_digest, NEW.enrollment_materializer_config_revision, + NEW.enrollment_api_binding_digest, NEW.enrollment_api_config_revision, + NEW.enrollment_public_config_map_uid, NEW.enrollment_public_config_map_resource_version, + NEW.enrollment_public_config_map_snapshot_digest) + IS DISTINCT FROM + (OLD.environment_id, OLD.cluster_id, OLD.kubernetes_namespace, OLD.custody_mode, + OLD.private_secret_name, OLD.public_jwks_config_map_name, OLD.created_at, + OLD.enrollment_cluster_incarnation_uid, OLD.enrollment_namespace_uid, + OLD.enrollment_materializer_binding_digest, OLD.enrollment_materializer_config_revision, + OLD.enrollment_api_binding_digest, OLD.enrollment_api_config_revision, + OLD.enrollment_public_config_map_uid, OLD.enrollment_public_config_map_resource_version, + OLD.enrollment_public_config_map_snapshot_digest) + OR NEW.record_version <> OLD.record_version + 1 THEN + RAISE EXCEPTION 'Account JWT signer desired state permits only a versioned owner transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + -- Creating a generation operation is the only transition from an idle state to a new key + -- request. Active identities and publication fences remain unchanged. + IF OLD.generation_operation_id IS NULL AND OLD.prepared_operation_id IS NULL + AND NEW.generation_operation_id IS NOT NULL AND NEW.prepared_operation_id IS NULL + AND NEW.durable_active_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND NEW.durable_active_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND NEW.published_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND NEW.published_active_kid IS NOT DISTINCT FROM OLD.published_active_kid THEN + IF OLD.enrollment_cluster_incarnation_uid IS NULL + OR OLD.enrollment_namespace_uid IS NULL + OR OLD.enrollment_materializer_binding_digest IS NULL + OR OLD.enrollment_api_binding_digest IS NULL + OR OLD.enrollment_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'JWT signer state has no independently protected enrollment pins' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + PERFORM 1 FROM account_jwt_signer_generation_operations AS generation_op + WHERE generation_op.operation_id = NEW.generation_operation_id + AND generation_op.environment_id = NEW.environment_id + AND generation_op.cluster_id = NEW.cluster_id + AND generation_op.kubernetes_namespace = NEW.kubernetes_namespace + AND generation_op.custody_mode = NEW.custody_mode + AND generation_op.expected_record_version = OLD.record_version + AND generation_op.expected_previous_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND generation_op.expected_previous_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND generation_op.expected_published_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND generation_op.expected_published_kid IS NOT DISTINCT FROM OLD.published_active_kid; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT generation pointer is not the exact current Account operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + RETURN NEW; + END IF; + + -- Abandon only one complete, exact UNPREPARED generation. Both active fences stay untouched; + -- the immutable Account receipt is the only authority to release the generation pointer. + IF OLD.generation_operation_id IS NOT NULL AND OLD.prepared_operation_id IS NULL + AND NEW.generation_operation_id IS NULL AND NEW.prepared_operation_id IS NULL + AND NEW.durable_active_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND NEW.durable_active_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND NEW.published_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND NEW.published_active_kid IS NOT DISTINCT FROM OLD.published_active_kid THEN + SELECT receipt.* INTO operation_row + FROM account_jwt_signer_generation_abort_receipts AS receipt + WHERE receipt.operation_id = OLD.generation_operation_id + AND receipt.environment_id = OLD.environment_id + AND receipt.cluster_id = OLD.cluster_id + AND receipt.kubernetes_namespace = OLD.kubernetes_namespace + AND receipt.custody_mode = OLD.custody_mode + AND receipt.expected_state_version = OLD.record_version + AND receipt.resulting_state_version = NEW.record_version + AND receipt.durable_active_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND receipt.durable_active_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND receipt.published_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND receipt.published_active_kid IS NOT DISTINCT FROM OLD.published_active_kid; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT generation pointer release lacks its exact Account abort receipt' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_abort_binding'; + END IF; + RETURN NEW; + END IF; + + -- Enter PREPARED only after insertion of the exact durable promotion request. + IF OLD.generation_operation_id IS NOT NULL AND OLD.prepared_operation_id IS NULL + AND NEW.generation_operation_id IS NULL AND NEW.prepared_operation_id IS NOT NULL + AND NEW.durable_active_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND NEW.durable_active_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND NEW.published_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND NEW.published_active_kid IS NOT DISTINCT FROM OLD.published_active_kid THEN + SELECT promotion.* INTO operation_row + FROM account_jwt_signer_promotion_operations AS promotion + WHERE promotion.operation_id = NEW.prepared_operation_id + AND promotion.generation_operation_id = OLD.generation_operation_id + AND promotion.environment_id = OLD.environment_id + AND promotion.cluster_id = OLD.cluster_id + AND promotion.kubernetes_namespace = OLD.kubernetes_namespace + AND promotion.custody_mode = OLD.custody_mode + AND promotion.expected_record_version = OLD.record_version + AND promotion.expected_previous_generation IS NOT DISTINCT FROM OLD.durable_active_generation + AND promotion.expected_previous_kid IS NOT DISTINCT FROM OLD.durable_active_kid + AND promotion.expected_public_active_generation IS NOT DISTINCT FROM OLD.published_active_generation + AND promotion.expected_public_active_kid IS NOT DISTINCT FROM OLD.published_active_kid + AND promotion.status = 'PREPARED' + AND promotion.operation_action = 'PROMOTE_PENDING'; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT PREPARED pointer is not the exact Account promotion operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + RETURN NEW; + END IF; + + -- Close only the exact PREPARED operation. COMMITTED changes both active fences to target; + -- ABORTED preserves both previous fences. No resource observation can perform either CAS. + IF OLD.generation_operation_id IS NULL AND OLD.prepared_operation_id IS NOT NULL + AND NEW.generation_operation_id IS NULL AND NEW.prepared_operation_id IS NULL THEN + SELECT promotion.* INTO operation_row + FROM account_jwt_signer_promotion_operations AS promotion + WHERE promotion.operation_id = OLD.prepared_operation_id + AND promotion.environment_id = OLD.environment_id + AND promotion.cluster_id = OLD.cluster_id + AND promotion.kubernetes_namespace = OLD.kubernetes_namespace + AND promotion.custody_mode = OLD.custody_mode + AND promotion.expected_record_version + 1 = OLD.record_version + AND promotion.status IN ('COMMITTED', 'ABORTED'); + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT promotion terminal transition has no exact durable result' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + IF operation_row.status = 'COMMITTED' THEN + IF NEW.durable_active_generation IS DISTINCT FROM operation_row.target_generation + OR NEW.durable_active_kid IS DISTINCT FROM operation_row.target_kid + OR NEW.published_active_generation IS DISTINCT FROM operation_row.target_generation + OR NEW.published_active_kid IS DISTINCT FROM operation_row.target_kid THEN + RAISE EXCEPTION 'Committed JWT signer and published active fences must equal target' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + ELSIF NEW.durable_active_generation IS DISTINCT FROM OLD.durable_active_generation + OR NEW.durable_active_kid IS DISTINCT FROM OLD.durable_active_kid + OR NEW.published_active_generation IS DISTINCT FROM OLD.published_active_generation + OR NEW.published_active_kid IS DISTINCT FROM OLD.published_active_kid THEN + RAISE EXCEPTION 'Aborted JWT signer operation must preserve previous active fences' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + RETURN NEW; + END IF; + + RAISE EXCEPTION 'Account JWT signer state transition is not in the lifecycle CAS' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; +END; +$$; + +CREATE FUNCTION account_jwt_signer_promotion_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_row RECORD; + generation_row RECORD; + result_row RECORD; + plan_inventory_complete BOOLEAN; + plan_expires_at BIGINT; + entry_count BIGINT; + verified_count BIGINT; +BEGIN + IF NEW.operation_action <> 'PROMOTE_PENDING' + OR NEW.generation_operation_id IS NULL + OR NEW.expected_cluster_incarnation_uid IS NULL + OR NEW.expected_namespace_uid IS NULL + OR NEW.expected_private_secret_uid IS NULL + OR NEW.expected_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'Promotion request lacks its exact lifecycle binding' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + -- Lock order is desired state, then source generation, then immutable evidence. + SELECT * INTO state_row FROM account_jwt_signer_desired_states + WHERE environment_id = NEW.environment_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT signer desired state is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO generation_row FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation operation is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO result_row FROM account_jwt_signer_generation_results + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation result is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + IF state_row.generation_operation_id IS DISTINCT FROM NEW.generation_operation_id + OR state_row.prepared_operation_id IS NOT NULL + OR state_row.record_version IS DISTINCT FROM NEW.expected_record_version + OR (state_row.cluster_id, state_row.kubernetes_namespace, state_row.custody_mode) + IS DISTINCT FROM (NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode) + OR (state_row.durable_active_generation, state_row.durable_active_kid) + IS DISTINCT FROM (NEW.expected_previous_generation, NEW.expected_previous_kid) + OR (state_row.published_active_generation, state_row.published_active_kid) + IS DISTINCT FROM (NEW.expected_public_active_generation, NEW.expected_public_active_kid) + OR state_row.enrollment_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR state_row.enrollment_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR state_row.enrollment_materializer_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR state_row.enrollment_materializer_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR state_row.enrollment_api_binding_digest IS DISTINCT FROM NEW.api_binding_digest + OR state_row.enrollment_api_config_revision IS DISTINCT FROM NEW.api_config_revision + OR state_row.enrollment_public_config_map_uid IS DISTINCT FROM NEW.expected_public_config_map_uid + OR generation_row.operation_id IS NULL + OR generation_row.environment_id IS DISTINCT FROM NEW.environment_id + OR generation_row.expected_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR generation_row.expected_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR generation_row.trust_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR generation_row.trust_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR generation_row.target_generation IS DISTINCT FROM NEW.target_generation + OR generation_row.target_kid IS DISTINCT FROM NEW.target_kid + OR generation_row.expected_record_version + 1 IS DISTINCT FROM result_row.desired_state_version + OR result_row.secret_uid IS DISTINCT FROM NEW.expected_private_secret_uid + OR result_row.observed_resource_version IS DISTINCT FROM NEW.expected_private_secret_resource_version + OR result_row.receipt_digest IS DISTINCT FROM NEW.generation_receipt_digest + OR result_row.public_key_fingerprint IS DISTINCT FROM NEW.target_public_key_fingerprint + OR EXISTS ( + SELECT 1 FROM account_jwt_signer_generation_abort_receipts AS abort_receipt + WHERE abort_receipt.operation_id = NEW.generation_operation_id) THEN + RAISE EXCEPTION 'JWT promotion request does not match current Account generation evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + SELECT validator_inventory_complete, expires_at_epoch_seconds + INTO plan_inventory_complete, plan_expires_at + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest FOR SHARE; + IF plan_inventory_complete IS DISTINCT FROM TRUE + OR plan_expires_at IS NULL + OR plan_expires_at <= floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT THEN + RAISE EXCEPTION 'JWT promotion requires current complete validator inventory proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + SELECT count(*), count(*) FILTER (WHERE state = 'VERIFIED' + AND verified_at_epoch_seconds < expires_at_epoch_seconds) + INTO entry_count, verified_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest; + IF entry_count = 0 OR verified_count <> entry_count THEN + RAISE EXCEPTION 'JWT promotion requires every exact readiness probe to be VERIFIED' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM account_jwt_jwks_prepublication_intents AS intent + JOIN account_jwt_jwks_publication_receipts AS receipt + ON receipt.operation_id = intent.operation_id + AND receipt.intent_digest = intent.intent_digest + JOIN account_jwt_jwks_mount_observations AS mount + ON mount.operation_id = intent.operation_id + WHERE intent.operation_id = NEW.generation_operation_id + AND intent.intent_digest = NEW.prepublication_intent_digest + AND receipt.receipt_digest = NEW.prepublication_receipt_digest + AND mount.observation_digest = NEW.mounted_observation_digest + AND intent.config_map_uid = NEW.expected_public_config_map_uid + AND intent.api_binding_digest = NEW.api_binding_digest + AND intent.api_config_revision = NEW.api_config_revision + AND receipt.observed_resource_version = NEW.expected_public_jwks_resource_version + AND intent.public_key_fingerprint = NEW.target_public_key_fingerprint + AND intent.jwks_json = NEW.expected_public_jwks_json) THEN + RAISE EXCEPTION 'JWT promotion request does not match exact current prepublication evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_signer_promotion_insert_guard + BEFORE INSERT ON account_jwt_signer_promotion_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_promotion_insert_guard(); + +CREATE FUNCTION account_jwt_signer_promotion_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer promotion history cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; +CREATE TRIGGER account_jwt_signer_promotion_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_promotion_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_promotion_no_truncate(); + +CREATE FUNCTION account_jwt_generation_abort_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_row RECORD; + generation_row RECORD; + result_row RECORD; +BEGIN + SELECT * INTO state_row + FROM account_jwt_signer_desired_states + WHERE environment_id = NEW.environment_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT generation abort desired state is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_abort_binding'; + END IF; + SELECT * INTO generation_row + FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT generation abort operation is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_abort_binding'; + END IF; + SELECT * INTO result_row + FROM account_jwt_signer_generation_results + WHERE operation_id = NEW.operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'JWT generation abort result is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_abort_binding'; + END IF; + + IF (state_row.cluster_id, state_row.kubernetes_namespace, state_row.custody_mode, + state_row.record_version, state_row.generation_operation_id, state_row.prepared_operation_id, + state_row.durable_active_generation, state_row.durable_active_kid, + state_row.published_active_generation, state_row.published_active_kid) + IS DISTINCT FROM + (NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode, + NEW.expected_state_version, NEW.operation_id, NULL, + NEW.durable_active_generation, NEW.durable_active_kid, + NEW.published_active_generation, NEW.published_active_kid) + OR (state_row.enrollment_cluster_incarnation_uid, + state_row.enrollment_namespace_uid, + state_row.enrollment_materializer_binding_digest, + state_row.enrollment_materializer_config_revision) + IS DISTINCT FROM + (NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.trust_binding_digest, NEW.trust_config_revision) + OR (generation_row.environment_id, generation_row.cluster_id, + generation_row.kubernetes_namespace, generation_row.custody_mode, + generation_row.operation_digest, generation_row.expected_record_version, + generation_row.expected_previous_generation, generation_row.expected_previous_kid, + generation_row.expected_published_generation, generation_row.expected_published_kid, + generation_row.expected_cluster_incarnation_uid, generation_row.expected_namespace_uid, + generation_row.trust_binding_digest, generation_row.trust_config_revision) + IS DISTINCT FROM + (NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode, + NEW.operation_digest, NEW.expected_state_version - 1, + NEW.durable_active_generation, NEW.durable_active_kid, + NEW.published_active_generation, NEW.published_active_kid, + NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.trust_binding_digest, NEW.trust_config_revision) + OR (result_row.environment_id, result_row.cluster_id, + result_row.kubernetes_namespace, result_row.custody_mode, + result_row.operation_digest, result_row.generation_request_digest, + result_row.receipt_digest, result_row.desired_state_version, + result_row.expected_cluster_incarnation_uid, result_row.expected_namespace_uid, + result_row.trust_binding_digest, result_row.trust_config_revision, + result_row.target_generation, result_row.target_kid, + result_row.public_key_fingerprint) + IS DISTINCT FROM + (NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode, + NEW.operation_digest, NEW.generation_request_digest, + NEW.generation_receipt_digest, NEW.expected_state_version, + NEW.expected_cluster_incarnation_uid, NEW.expected_namespace_uid, + NEW.trust_binding_digest, NEW.trust_config_revision, + generation_row.target_generation, generation_row.target_kid, + result_row.public_key_fingerprint) + OR EXISTS ( + SELECT 1 FROM account_jwt_signer_promotion_operations promotion + WHERE promotion.generation_operation_id = NEW.operation_id) THEN + RAISE EXCEPTION 'JWT generation abort receipt does not bind the exact current UNPREPARED operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_abort_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_generation_abort_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer generation abort receipts are immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_abort_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_generation_abort_terminal_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_row RECORD; +BEGIN + SELECT * INTO state_row + FROM account_jwt_signer_desired_states + WHERE environment_id = NEW.environment_id; + IF NOT FOUND + OR state_row.cluster_id IS DISTINCT FROM NEW.cluster_id + OR state_row.kubernetes_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR state_row.custody_mode IS DISTINCT FROM NEW.custody_mode + OR state_row.record_version IS DISTINCT FROM NEW.resulting_state_version + OR state_row.generation_operation_id IS NOT NULL + OR state_row.prepared_operation_id IS NOT NULL + OR state_row.durable_active_generation IS DISTINCT FROM NEW.durable_active_generation + OR state_row.durable_active_kid IS DISTINCT FROM NEW.durable_active_kid + OR state_row.published_active_generation IS DISTINCT FROM NEW.published_active_generation + OR state_row.published_active_kid IS DISTINCT FROM NEW.published_active_kid THEN + RAISE EXCEPTION 'Account generation abort receipt is not paired with its exact terminal state CAS' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_abort_binding'; + END IF; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_jwt_generation_abort_insert_guard + BEFORE INSERT ON account_jwt_signer_generation_abort_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_generation_abort_insert_guard(); +CREATE TRIGGER account_jwt_generation_abort_immutable_guard + BEFORE UPDATE OR DELETE ON account_jwt_signer_generation_abort_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_generation_abort_immutable_guard(); +CREATE TRIGGER account_jwt_generation_abort_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_generation_abort_receipts + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_generation_abort_immutable_guard(); +CREATE CONSTRAINT TRIGGER account_jwt_generation_abort_terminal_guard + AFTER INSERT ON account_jwt_signer_generation_abort_receipts + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION account_jwt_generation_abort_terminal_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V107__account_jwt_readiness_single_delivery_claims.sql b/services/account-service/src/main/resources/db/migration/V107__account_jwt_readiness_single_delivery_claims.sql new file mode 100644 index 0000000000..65c13414a5 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V107__account_jwt_readiness_single_delivery_claims.sql @@ -0,0 +1,125 @@ +-- One durable winner may emit the exact current operation's readiness probes to its authenticated +-- harness. A claim is a one-shot concurrency fence, not delivery proof, validator evidence, or +-- signer authority; it is never cleared after an ambiguous response. +CREATE TABLE account_jwt_readiness_delivery_claims ( + rotation_operation_id UUID PRIMARY KEY, + plan_digest VARCHAR(64) NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + materializer_trust_binding_digest VARCHAR(64) NOT NULL, + materializer_trust_config_revision VARCHAR(128) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + readiness_binding_digest VARCHAR(64) NOT NULL, + readiness_config_revision VARCHAR(128) NOT NULL, + readiness_binding_valid_until_epoch_seconds BIGINT NOT NULL, + validator_id VARCHAR(63) NOT NULL, + validator_instance_id VARCHAR(128) NOT NULL, + validator_peer_uri VARCHAR(256) NOT NULL, + validator_peer_spki_sha256 VARCHAR(64) NOT NULL, + claimed_at_epoch_seconds BIGINT NOT NULL, + expires_at_epoch_seconds BIGINT NOT NULL, + claim_digest VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_readiness_delivery_claim_plan_fk + FOREIGN KEY (rotation_operation_id, plan_digest) + REFERENCES account_jwt_readiness_probe_plans(rotation_operation_id, plan_digest) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_delivery_claim_shape_check + CHECK (rotation_operation_id::text ~ + '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND materializer_trust_binding_digest ~ '^[0-9a-f]{64}$' + AND materializer_trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid + AND readiness_binding_digest ~ '^[0-9a-f]{64}$' + AND readiness_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND readiness_binding_valid_until_epoch_seconds > claimed_at_epoch_seconds + AND validator_id = 'account-service' + AND validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/account-jwt-readiness-harness$' + AND validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$' + AND claimed_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > claimed_at_epoch_seconds + AND claim_digest ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_readiness_delivery_claim_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + expected_entry_count integer; + actual_entry_count integer; +BEGIN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.expected_cluster_incarnation_uid IS DISTINCT FROM plan_row.expected_cluster_incarnation_uid + OR NEW.expected_namespace_uid IS DISTINCT FROM plan_row.expected_namespace_uid + OR NEW.materializer_trust_binding_digest IS DISTINCT FROM plan_row.trust_binding_digest + OR NEW.materializer_trust_config_revision IS DISTINCT FROM plan_row.trust_config_revision + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds + OR NEW.validator_id <> 'account-service' + OR NEW.readiness_binding_valid_until_epoch_seconds <= NEW.claimed_at_epoch_seconds + OR NEW.validator_peer_uri IS DISTINCT FROM + 'spiffe://firemud/ns/' || plan_row.kubernetes_namespace || '/sa/account-jwt-readiness-harness' + OR NEW.claimed_at_epoch_seconds < plan_row.not_before_epoch_seconds + OR NEW.claimed_at_epoch_seconds >= plan_row.expires_at_epoch_seconds + OR CURRENT_TIMESTAMP < to_timestamp(plan_row.not_before_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(plan_row.expires_at_epoch_seconds) THEN + RAISE EXCEPTION 'Account readiness delivery claim differs from its current exact plan' + USING ERRCODE = '23514'; + END IF; + expected_entry_count := + 1 + jsonb_array_length(plan_row.applicability_matrix_json::jsonb #> + '{validators,0,applicableProfiles}'); + SELECT COUNT(*) INTO actual_entry_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest + AND state = 'PLANNED' + AND compact_token_sha256 IS NULL + AND signing_attempted_at_epoch_seconds IS NULL + AND verification_receipt_sha256 IS NULL; + IF actual_entry_count <> expected_entry_count THEN + RAISE EXCEPTION 'Account readiness delivery claim requires untouched planned entries' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_delivery_claim_insert_guard + BEFORE INSERT ON account_jwt_readiness_delivery_claims + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_delivery_claim_guard(); + +CREATE FUNCTION account_jwt_readiness_delivery_claim_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT readiness delivery claims are immutable' USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_delivery_claim_immutable + BEFORE UPDATE OR DELETE ON account_jwt_readiness_delivery_claims + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_delivery_claim_immutable_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V109__account_jwt_validator_inventory_snapshots.sql b/services/account-service/src/main/resources/db/migration/V109__account_jwt_validator_inventory_snapshots.sql new file mode 100644 index 0000000000..1fd619b3c6 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V109__account_jwt_validator_inventory_snapshots.sql @@ -0,0 +1,67 @@ +-- Durable immutable owner observations are bound to a readiness plan, but remain partial +-- non-authorizing evidence. A stored Deployment/ReplicaSet/Pod inventory is not probe acceptance. +CREATE TABLE account_jwt_validator_inventory_snapshots ( + snapshot_digest VARCHAR(64) PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + cluster_incarnation_uid UUID NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + namespace_uid UUID NOT NULL, + api_binding_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + inventory_binding_revision VARCHAR(128) NOT NULL, + inventory_binding_digest VARCHAR(64) NOT NULL, + observed_at VARCHAR(40) NOT NULL, + canonical_snapshot BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_validator_inventory_snapshot_identity_check + CHECK (snapshot_digest ~ '^[0-9a-f]{64}$' + AND environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND api_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND inventory_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND inventory_binding_digest ~ '^[0-9a-f]{64}$' + AND length(observed_at) BETWEEN 20 AND 40 + AND observed_at ~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}T.*Z$' + AND octet_length(canonical_snapshot) BETWEEN 2 AND 4194304), + CONSTRAINT account_jwt_validator_inventory_snapshot_plan_identity_unique + UNIQUE (snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) +); + +ALTER TABLE account_jwt_readiness_probe_plans + ADD COLUMN inventory_snapshot_digest VARCHAR(64), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_digest_check + CHECK (inventory_snapshot_digest IS NULL + OR inventory_snapshot_digest ~ '^[0-9a-f]{64}$'), + ADD CONSTRAINT account_jwt_readiness_plan_inventory_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, + kubernetes_namespace, expected_cluster_incarnation_uid, expected_namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT; + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT validator inventory snapshots are immutable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_validator_inventory_snapshot_immutable + BEFORE UPDATE OR DELETE ON account_jwt_validator_inventory_snapshots + FOR EACH ROW EXECUTE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard(); + +CREATE TRIGGER account_jwt_validator_inventory_snapshot_no_truncate + BEFORE TRUNCATE ON account_jwt_validator_inventory_snapshots + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_validator_inventory_snapshot_immutable_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql b/services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql new file mode 100644 index 0000000000..bf62bc372e --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql @@ -0,0 +1,880 @@ +-- V2 readiness plans bind every protected live validator Pod and retain one immutable production +-- verification receipt per Pod and logical probe. Existing V1 plans and receipts remain retained +-- and partial; they are never rewritten into V2 closure evidence. + +ALTER TABLE account_jwt_readiness_probe_plans + DROP CONSTRAINT account_jwt_readiness_plan_window_check; + +ALTER TABLE account_jwt_readiness_probe_plans + ADD CONSTRAINT account_jwt_readiness_plan_window_check + CHECK (maximum_cache_age_seconds BETWEEN 1 AND 300 + AND planned_at_epoch_seconds > 0 + AND not_before_epoch_seconds >= planned_at_epoch_seconds + maximum_cache_age_seconds + AND expires_at_epoch_seconds > not_before_epoch_seconds + AND expires_at_epoch_seconds - not_before_epoch_seconds <= 300 + AND plan_version IN (1, 2) + AND (plan_version <> 2 OR inventory_snapshot_digest IS NOT NULL)); + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN entry_plan_version SMALLINT NOT NULL DEFAULT 1; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN pod_receipt_count SMALLINT; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD COLUMN pod_receipt_closure_sha256 VARCHAR(64); + +ALTER TABLE account_jwt_readiness_probe_entries + DROP CONSTRAINT account_jwt_readiness_probe_evidence_check; + +ALTER TABLE account_jwt_readiness_probe_entries + ADD CONSTRAINT account_jwt_readiness_probe_evidence_check + CHECK (plan_digest ~ '^[0-9a-f]{64}$' + AND registry_version = 1 + AND entry_plan_version IN (1, 2) + AND entry_version > 0 + AND planned_issued_at_epoch_seconds > 0 + AND expires_at_epoch_seconds > planned_issued_at_epoch_seconds + AND (compact_token_sha256 IS NULL OR compact_token_sha256 ~ '^[0-9a-f]{64}$') + AND (signing_attempted_at_epoch_seconds IS NULL + OR (signing_attempted_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND signing_attempted_at_epoch_seconds < expires_at_epoch_seconds)) + AND ((compact_token_sha256 IS NULL AND signing_attempted_at_epoch_seconds IS NULL) + OR (compact_token_sha256 IS NOT NULL AND signing_attempted_at_epoch_seconds IS NOT NULL)) + AND (state NOT IN ('ISSUED', 'VERIFIED', 'RETIRED') OR compact_token_sha256 IS NOT NULL) + AND (verification_receipt_version IS NULL + OR (entry_plan_version = 1 AND verification_receipt_version = 1) + OR (entry_plan_version = 2 AND verification_receipt_version = 2)) + AND (verification_source_entry_version IS NULL OR verification_source_entry_version > 0) + AND (verified_at_epoch_seconds IS NULL + OR (verified_at_epoch_seconds >= planned_issued_at_epoch_seconds + AND verified_at_epoch_seconds < expires_at_epoch_seconds)) + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND (validator_instance_id IS NULL + OR validator_instance_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_binding_digest IS NULL OR validator_binding_digest ~ '^[0-9a-f]{64}$') + AND (validator_config_revision IS NULL + OR validator_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$') + AND (validator_peer_uri IS NULL + OR validator_peer_uri ~ '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$') + AND (validator_peer_spki_sha256 IS NULL + OR validator_peer_spki_sha256 ~ '^[0-9a-f]{64}$') + AND (verification_receipt_sha256 IS NULL + OR verification_receipt_sha256 ~ '^[0-9a-f]{64}$') + AND (pod_receipt_count IS NULL OR pod_receipt_count BETWEEN 1 AND 256) + AND (pod_receipt_closure_sha256 IS NULL + OR pod_receipt_closure_sha256 ~ '^[0-9a-f]{64}$') + AND ((verification_receipt_sha256 IS NULL + AND verification_receipt_version IS NULL + AND verification_source_entry_version IS NULL + AND verified_at_epoch_seconds IS NULL + AND verified_kid IS NULL + AND validator_instance_id IS NULL + AND validator_binding_digest IS NULL + AND validator_config_revision IS NULL + AND validator_peer_uri IS NULL + AND validator_peer_spki_sha256 IS NULL + AND pod_receipt_count IS NULL + AND pod_receipt_closure_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 1 + AND entry_plan_version = 1 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid IS NOT NULL + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL + AND pod_receipt_count IS NULL + AND pod_receipt_closure_sha256 IS NULL) + OR (verification_receipt_sha256 IS NOT NULL + AND verification_receipt_version = 2 + AND entry_plan_version = 2 + AND verification_source_entry_version IS NOT NULL + AND verified_at_epoch_seconds IS NOT NULL + AND verified_kid = target_kid + AND validator_instance_id IS NOT NULL + AND validator_binding_digest IS NOT NULL + AND validator_config_revision IS NOT NULL + AND validator_peer_uri IS NOT NULL + AND validator_peer_spki_sha256 IS NOT NULL + AND pod_receipt_count IS NOT NULL + AND pod_receipt_closure_sha256 = verification_receipt_sha256)) + AND (state NOT IN ('VERIFIED', 'RETIRED') OR verification_receipt_sha256 IS NOT NULL) + AND (state NOT IN ('PLANNED', 'ISSUED') OR verification_receipt_sha256 IS NULL)); + +CREATE TABLE account_jwt_readiness_validator_pods ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + jti UUID NOT NULL, + inventory_snapshot_digest VARCHAR(64) NOT NULL, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + cluster_incarnation_uid UUID NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + namespace_uid UUID NOT NULL, + api_binding_revision VARCHAR(128) NOT NULL, + api_binding_digest VARCHAR(64) NOT NULL, + inventory_binding_revision VARCHAR(128) NOT NULL, + inventory_binding_digest VARCHAR(64) NOT NULL, + deployment_uid UUID NOT NULL, + pod_uid UUID NOT NULL, + pod_ip VARCHAR(45) NOT NULL, + image VARCHAR(512) NOT NULL, + verifier_config_sha256 VARCHAR(64) NOT NULL, + applicability_matrix_digest VARCHAR(64) NOT NULL, + expected_outcome VARCHAR(32) NOT NULL, + exact_pod_endpoint VARCHAR(512) NOT NULL, + canonical_service_uri VARCHAR(256) NOT NULL, + expected_pod_leaf_spki_sha256 VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid), + CONSTRAINT account_jwt_readiness_validator_pod_entry_fk + FOREIGN KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind) + REFERENCES account_jwt_readiness_probe_entries( + rotation_operation_id, validator_id, token_profile, audience, probe_kind) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_validator_pod_snapshot_fk + FOREIGN KEY (inventory_snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + REFERENCES account_jwt_validator_inventory_snapshots( + snapshot_digest, environment_id, cluster_id, kubernetes_namespace, + cluster_incarnation_uid, namespace_uid) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_validator_pod_shape_check + CHECK (rotation_operation_id::text ~ + '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND jti::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND plan_digest ~ '^[0-9a-f]{64}$' + AND inventory_snapshot_digest ~ '^[0-9a-f]{64}$' + AND validator_id ~ '^[a-z0-9][a-z0-9-]{0,62}$' + AND token_profile ~ '^[a-z0-9][a-z0-9-]{0,127}$' + AND audience ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND probe_kind IN ('CANARY', 'REPRESENTATIVE') + AND environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND api_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND api_binding_digest ~ '^[0-9a-f]{64}$' + AND inventory_binding_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND inventory_binding_digest ~ '^[0-9a-f]{64}$' + AND deployment_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND pod_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND (pod_ip ~ '^(?:[0-9]{1,3}[.]){3}[0-9]{1,3}$' OR pod_ip ~ '^[0-9a-f:]+$') + AND image ~ '^[^[:space:]@]+@sha256:[0-9a-f]{64}$' + AND verifier_config_sha256 ~ '^[0-9a-f]{64}$' + AND applicability_matrix_digest ~ '^[0-9a-f]{64}$' + AND expected_outcome IN ('ACCEPT', 'INAPPLICABLE_REJECT') + AND exact_pod_endpoint ~ '^grpcs://[^/?#]+:[0-9]{1,5}$' + AND canonical_service_uri ~ + '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$' + AND expected_pod_leaf_spki_sha256 ~ '^[0-9a-f]{64}$') +); + +CREATE TABLE account_jwt_readiness_pod_receipts ( + rotation_operation_id UUID NOT NULL, + plan_digest VARCHAR(64) NOT NULL, + validator_id VARCHAR(63) NOT NULL, + token_profile VARCHAR(128) NOT NULL, + audience VARCHAR(128) NOT NULL, + probe_kind VARCHAR(16) NOT NULL, + pod_uid UUID NOT NULL, + receipt_version SMALLINT NOT NULL, + jti UUID NOT NULL, + source_entry_version BIGINT NOT NULL, + compact_token_sha256 VARCHAR(64) NOT NULL, + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + expected_active_generation BIGINT, + expected_active_kid VARCHAR(64), + outcome VARCHAR(32) NOT NULL, + observed_pod_uid UUID NOT NULL, + observed_image VARCHAR(512) NOT NULL, + observed_verifier_config_sha256 VARCHAR(64) NOT NULL, + verified_kid VARCHAR(64), + receiver_endpoint VARCHAR(512) NOT NULL, + receiver_service_uri VARCHAR(256) NOT NULL, + receiver_peer_spki_sha256 VARCHAR(64) NOT NULL, + observed_at_epoch_seconds BIGINT NOT NULL, + receipt_sha256 VARCHAR(64) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid), + CONSTRAINT account_jwt_readiness_pod_receipt_target_fk + FOREIGN KEY (rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) + REFERENCES account_jwt_readiness_validator_pods( + rotation_operation_id, validator_id, token_profile, audience, probe_kind, pod_uid) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_readiness_pod_receipt_shape_check + CHECK (receipt_version = 1 + AND source_entry_version > 0 + AND compact_token_sha256 ~ '^[0-9a-f]{64}$' + AND target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND ((expected_active_generation IS NULL AND expected_active_kid IS NULL) + OR (expected_active_generation > 0 + AND expected_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) + AND target_kid <> expected_active_kid + AND outcome IN ('ACCEPT', 'INAPPLICABLE_REJECT') + AND observed_pod_uid = pod_uid + AND observed_image ~ '^[^[:space:]@]+@sha256:[0-9a-f]{64}$' + AND observed_verifier_config_sha256 ~ '^[0-9a-f]{64}$' + AND (verified_kid IS NULL OR verified_kid = target_kid) + AND receiver_endpoint ~ '^grpcs://[^/?#]+:[0-9]{1,5}$' + AND receiver_service_uri ~ + '^spiffe://firemud/ns/[a-z0-9-]{1,63}/sa/[a-z0-9][a-z0-9-]{0,62}$' + AND receiver_peer_spki_sha256 ~ '^[0-9a-f]{64}$' + AND observed_at_epoch_seconds > 0 + AND receipt_sha256 ~ '^[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_readiness_retained_evidence_truncate_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT readiness evidence in table % cannot be truncated', TG_TABLE_NAME + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_probe_plans_no_truncate + BEFORE TRUNCATE ON account_jwt_readiness_probe_plans + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_readiness_retained_evidence_truncate_guard(); + +CREATE TRIGGER account_jwt_readiness_probe_entries_no_truncate + BEFORE TRUNCATE ON account_jwt_readiness_probe_entries + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_readiness_retained_evidence_truncate_guard(); + +CREATE TRIGGER account_jwt_readiness_delivery_claims_no_truncate + BEFORE TRUNCATE ON account_jwt_readiness_delivery_claims + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_readiness_retained_evidence_truncate_guard(); + +CREATE TRIGGER account_jwt_readiness_validator_pods_no_truncate + BEFORE TRUNCATE ON account_jwt_readiness_validator_pods + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_readiness_retained_evidence_truncate_guard(); + +CREATE TRIGGER account_jwt_readiness_pod_receipts_no_truncate + BEFORE TRUNCATE ON account_jwt_readiness_pod_receipts + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_readiness_retained_evidence_truncate_guard(); + +CREATE OR REPLACE FUNCTION account_jwt_readiness_plan_inventory_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + matrix jsonb; + account_profiles jsonb; + game_session_profiles jsonb; +BEGIN + matrix := NEW.applicability_matrix_json::jsonb; + IF NEW.plan_version = 1 THEN + IF NEW.validator_inventory_complete + OR matrix ->> 'inventoryStatus' IS DISTINCT FROM 'PARTIAL_UNCONFIRMED' + OR matrix ->> 'schemaVersion' IS DISTINCT FROM '1' + OR (CASE WHEN jsonb_typeof(matrix -> 'validators') = 'array' + THEN jsonb_array_length(matrix -> 'validators') <> 1 + ELSE TRUE END) + OR matrix #>> '{validators,0,validatorId}' IS DISTINCT FROM 'account-service' + OR (CASE WHEN jsonb_typeof(matrix #> '{validators,0,applicableProfiles}') = 'array' + THEN jsonb_array_length(matrix #> '{validators,0,applicableProfiles}') <> 3 + ELSE TRUE END) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (matrix #> '{validators,0,applicableProfiles}' @> + '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Legacy readiness plans remain explicitly partial and Account-only' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF NEW.plan_version <> 2 + OR NEW.inventory_snapshot_digest IS NULL + OR matrix ->> 'schemaVersion' IS DISTINCT FROM '2' + OR matrix ->> 'inventorySnapshotDigest' IS DISTINCT FROM NEW.inventory_snapshot_digest + OR (CASE WHEN jsonb_typeof(matrix -> 'validators') = 'array' + THEN jsonb_array_length(matrix -> 'validators') NOT BETWEEN 1 AND 32 + ELSE TRUE END) + OR (CASE WHEN jsonb_typeof(matrix -> 'productionProfiles') = 'array' + THEN jsonb_array_length(matrix -> 'productionProfiles') <> 3 + ELSE TRUE END) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(matrix -> 'validators') = 'array' + THEN matrix -> 'validators' + ELSE '[]'::jsonb END) AS validator(value) + WHERE validator.value ->> 'validatorId' IS NULL + OR jsonb_typeof(validator.value -> 'applicableProfiles') IS DISTINCT FROM 'array') THEN + RAISE EXCEPTION 'Readiness V2 plan must bind its protected live snapshot and closed profile family' + USING ERRCODE = '23514'; + END IF; + IF NEW.validator_inventory_complete THEN + SELECT value -> 'applicableProfiles' INTO account_profiles + FROM jsonb_array_elements(matrix -> 'validators') AS validator(value) + WHERE value ->> 'validatorId' = 'account-service'; + SELECT value -> 'applicableProfiles' INTO game_session_profiles + FROM jsonb_array_elements(matrix -> 'validators') AS validator(value) + WHERE value ->> 'validatorId' = 'game-session-service'; + IF matrix ->> 'inventoryStatus' IS DISTINCT FROM 'PROTECTED_LIVE_COMPLETE' + OR (CASE WHEN jsonb_typeof(matrix -> 'validators') = 'array' + THEN jsonb_array_length(matrix -> 'validators') <> 2 + ELSE TRUE END) + OR account_profiles IS NULL + OR (CASE WHEN jsonb_typeof(account_profiles) = 'array' + THEN jsonb_array_length(account_profiles) <> 3 + ELSE TRUE END) + OR NOT (account_profiles @> '[{"tokenProfile":"control-ui","audience":"control-ui"}]'::jsonb) + OR NOT (account_profiles @> '[{"tokenProfile":"player-bootstrap","audience":"player-bootstrap"}]'::jsonb) + OR NOT (account_profiles @> '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) + OR game_session_profiles IS NULL + OR (CASE WHEN jsonb_typeof(game_session_profiles) = 'array' + THEN jsonb_array_length(game_session_profiles) <> 1 + ELSE TRUE END) + OR NOT (game_session_profiles @> '[{"tokenProfile":"game-session-account-delegation","audience":"account-service"}]'::jsonb) THEN + RAISE EXCEPTION 'Readiness V2 completion requires exact Account and Game Session profile inventory' + USING ERRCODE = '23514'; + END IF; + ELSIF matrix ->> 'inventoryStatus' IS DISTINCT FROM 'PARTIAL_UNCONFIRMED' THEN + RAISE EXCEPTION 'Incomplete Readiness V2 inventory must remain explicitly partial' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_readiness_entry_plan_version_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; +BEGIN + IF TG_OP = 'UPDATE' AND NEW.entry_plan_version IS DISTINCT FROM OLD.entry_plan_version THEN + RAISE EXCEPTION 'Readiness entry schema version is immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND OR NEW.entry_plan_version IS DISTINCT FROM plan_row.plan_version THEN + RAISE EXCEPTION 'Readiness entry schema differs from its immutable plan' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_plan_version_binding + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_plan_version_guard(); + +DROP TRIGGER account_jwt_readiness_entry_lifecycle ON account_jwt_readiness_probe_entries; +CREATE TRIGGER account_jwt_readiness_entry_lifecycle_v1 + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW WHEN (NEW.entry_plan_version = 1) + EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); +CREATE TRIGGER account_jwt_readiness_entry_delete_guard + BEFORE DELETE ON account_jwt_readiness_probe_entries + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_entry_lifecycle_guard(); + +CREATE FUNCTION account_jwt_readiness_expected_pod_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + entry_row account_jwt_readiness_probe_entries%ROWTYPE; + snapshot_json jsonb; + validator_json jsonb; + pod_json jsonb; + expected_outcome_value text; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Expected readiness Pod bindings are immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + SELECT * INTO entry_row + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + SELECT convert_from(canonical_snapshot, 'UTF8')::jsonb INTO snapshot_json + FROM account_jwt_validator_inventory_snapshots + WHERE snapshot_digest = NEW.inventory_snapshot_digest; + IF NOT FOUND OR plan_row.plan_version <> 2 OR entry_row.entry_plan_version <> 2 + OR entry_row.jti IS DISTINCT FROM NEW.jti + OR plan_row.inventory_snapshot_digest IS DISTINCT FROM NEW.inventory_snapshot_digest + OR plan_row.applicability_matrix_digest IS DISTINCT FROM NEW.applicability_matrix_digest + OR (plan_row.environment_id, plan_row.cluster_id, plan_row.kubernetes_namespace, + plan_row.expected_cluster_incarnation_uid, plan_row.expected_namespace_uid) + IS DISTINCT FROM (NEW.environment_id, NEW.cluster_id, NEW.kubernetes_namespace, + NEW.cluster_incarnation_uid, NEW.namespace_uid) + OR NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'pods') AS pod(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND validator.value ->> 'deploymentUid' = NEW.deployment_uid::text + AND pod.value ->> 'uid' = NEW.pod_uid::text + AND pod.value ->> 'podIp' = NEW.pod_ip + AND pod.value ->> 'exactPodEndpoint' = NEW.exact_pod_endpoint + AND pod.value ->> 'canonicalServiceUri' = NEW.canonical_service_uri + AND pod.value ->> 'leafSpkiSha256' = NEW.expected_pod_leaf_spki_sha256 + AND pod.value ->> 'image' = NEW.image + AND pod.value ->> 'verifierConfigSha256' = NEW.verifier_config_sha256 + AND validator.value ->> 'image' = NEW.image + AND validator.value ->> 'verifierConfigSha256' = NEW.verifier_config_sha256) + OR (NEW.probe_kind = 'CANARY' AND NEW.expected_outcome <> 'ACCEPT') + OR (NEW.probe_kind = 'REPRESENTATIVE' AND ( + (NEW.expected_outcome = 'ACCEPT') IS DISTINCT FROM EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'profiles') AS profile(value) + WHERE validator.value ->> 'validatorId' = NEW.validator_id + AND profile.value ->> 'tokenProfile' = NEW.token_profile + AND profile.value ->> 'audience' = NEW.audience))) THEN + RAISE EXCEPTION 'Expected readiness Pod differs from its exact protected inventory and entry' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_expected_pod_insert_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_validator_pods + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_expected_pod_guard(); + +CREATE FUNCTION account_jwt_readiness_pod_receipt_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + entry_row account_jwt_readiness_probe_entries%ROWTYPE; + pod_row account_jwt_readiness_validator_pods%ROWTYPE; +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Readiness Pod verification receipts are immutable' USING ERRCODE = '23514'; + END IF; + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + SELECT * INTO entry_row + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind + FOR UPDATE; + SELECT * INTO pod_row + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind + AND pod_uid = NEW.pod_uid + FOR KEY SHARE; + IF plan_row.plan_version <> 2 OR plan_row.validator_inventory_complete IS DISTINCT FROM TRUE + OR entry_row.entry_plan_version <> 2 OR entry_row.state <> 'ISSUED' + OR entry_row.jti IS DISTINCT FROM NEW.jti + OR entry_row.entry_version IS DISTINCT FROM NEW.source_entry_version + OR entry_row.compact_token_sha256 IS DISTINCT FROM NEW.compact_token_sha256 + OR entry_row.target_generation IS DISTINCT FROM NEW.target_generation + OR entry_row.target_kid IS DISTINCT FROM NEW.target_kid + OR entry_row.expected_active_generation IS DISTINCT FROM NEW.expected_active_generation + OR entry_row.expected_active_kid IS DISTINCT FROM NEW.expected_active_kid + OR pod_row.expected_outcome IS DISTINCT FROM NEW.outcome + OR pod_row.exact_pod_endpoint IS NULL + OR pod_row.exact_pod_endpoint IS DISTINCT FROM NEW.receiver_endpoint + OR pod_row.canonical_service_uri IS DISTINCT FROM NEW.receiver_service_uri + OR pod_row.expected_pod_leaf_spki_sha256 IS DISTINCT FROM NEW.receiver_peer_spki_sha256 + OR pod_row.pod_uid IS DISTINCT FROM NEW.observed_pod_uid + OR pod_row.image IS DISTINCT FROM NEW.observed_image + OR pod_row.verifier_config_sha256 IS DISTINCT FROM NEW.observed_verifier_config_sha256 + OR NEW.verified_kid IS DISTINCT FROM NEW.target_kid + OR NEW.observed_at_epoch_seconds < entry_row.planned_issued_at_epoch_seconds + OR NEW.observed_at_epoch_seconds >= entry_row.expires_at_epoch_seconds + OR NEW.observed_at_epoch_seconds > floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT + OR CURRENT_TIMESTAMP < to_timestamp(entry_row.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(entry_row.expires_at_epoch_seconds) THEN + RAISE EXCEPTION 'Readiness Pod receipt differs from exact current inventory, probe, or TLS identity' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_pod_receipt_insert_guard + BEFORE INSERT OR UPDATE OR DELETE ON account_jwt_readiness_pod_receipts + FOR EACH ROW EXECUTE FUNCTION account_jwt_readiness_pod_receipt_guard(); + +CREATE FUNCTION account_jwt_readiness_entry_v2_lifecycle_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + expected_pod_count integer; + receipt_count integer; +BEGIN + IF TG_OP = 'INSERT' THEN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND OR plan_row.plan_version <> 2 + OR NEW.state <> 'PLANNED' + OR NEW.entry_version <> 1 + OR NEW.registry_version <> 1 + OR NEW.terminal_outcome IS NOT NULL + OR NEW.compact_token_sha256 IS NOT NULL + OR NEW.signing_attempted_at_epoch_seconds IS NOT NULL + OR NEW.verification_receipt_sha256 IS NOT NULL + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM plan_row.not_before_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds THEN + RAISE EXCEPTION 'Readiness V2 entry differs from its immutable plan' + USING ERRCODE = '23514'; + END IF; + IF NEW.probe_kind = 'CANARY' THEN + IF NEW.token_profile <> 'account-jwt-readiness-canary' + OR NEW.audience <> 'firemud-account-jwt-readiness' + OR NOT EXISTS (SELECT 1 FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS v(value) + WHERE v.value ->> 'validatorId' = NEW.validator_id) THEN + RAISE EXCEPTION 'Readiness V2 canary entry is outside the closed validator set' + USING ERRCODE = '23514'; + END IF; + ELSIF NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS v(value) + CROSS JOIN LATERAL jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'productionProfiles') AS p(value) + WHERE v.value ->> 'validatorId' = NEW.validator_id + AND p.value ->> 'tokenProfile' = NEW.token_profile + AND p.value ->> 'audience' = NEW.audience) THEN + RAISE EXCEPTION 'Readiness V2 representative entry is outside its exact profile matrix' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT readiness evidence is retained' USING ERRCODE = '23514'; + END IF; + IF OLD.entry_plan_version <> 2 OR NEW.entry_plan_version <> 2 + OR NEW.rotation_operation_id IS DISTINCT FROM OLD.rotation_operation_id + OR NEW.plan_digest IS DISTINCT FROM OLD.plan_digest + OR NEW.validator_id IS DISTINCT FROM OLD.validator_id + OR NEW.token_profile IS DISTINCT FROM OLD.token_profile + OR NEW.audience IS DISTINCT FROM OLD.audience + OR NEW.probe_kind IS DISTINCT FROM OLD.probe_kind + OR NEW.jti IS DISTINCT FROM OLD.jti + OR NEW.target_generation IS DISTINCT FROM OLD.target_generation + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM OLD.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM OLD.expected_active_kid + OR NEW.registry_version IS DISTINCT FROM OLD.registry_version + OR NEW.planned_issued_at_epoch_seconds IS DISTINCT FROM OLD.planned_issued_at_epoch_seconds + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM OLD.expires_at_epoch_seconds + OR NEW.entry_version <> OLD.entry_version + 1 THEN + RAISE EXCEPTION 'Readiness V2 entry identity/version is immutable except for one exact transition' + USING ERRCODE = '23514'; + END IF; + IF OLD.state = 'PLANNED' AND NEW.state = 'PLANNED' + AND OLD.compact_token_sha256 IS NULL + AND NEW.compact_token_sha256 IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds IS NOT NULL + AND NEW.signing_attempted_at_epoch_seconds >= OLD.planned_issued_at_epoch_seconds + AND NEW.signing_attempted_at_epoch_seconds < OLD.expires_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + IF OLD.state = 'PLANNED' AND NEW.state = 'ISSUED' + AND OLD.compact_token_sha256 IS NOT NULL + AND NEW.compact_token_sha256 = OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds = OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NULL + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.planned_issued_at_epoch_seconds) + AND CURRENT_TIMESTAMP < to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.terminal_outcome IS NULL THEN + RETURN NEW; + END IF; + IF OLD.state = 'ISSUED' AND NEW.state = 'VERIFIED' THEN + SELECT count(*) INTO expected_pod_count + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + SELECT count(*) INTO receipt_count + FROM account_jwt_readiness_pod_receipts + WHERE rotation_operation_id = NEW.rotation_operation_id + AND validator_id = NEW.validator_id + AND token_profile = NEW.token_profile + AND audience = NEW.audience + AND probe_kind = NEW.probe_kind; + IF expected_pod_count <= 0 OR expected_pod_count <> receipt_count + OR NEW.verification_receipt_version IS DISTINCT FROM 2 + OR NEW.verification_source_entry_version IS DISTINCT FROM OLD.entry_version + OR NEW.verification_receipt_sha256 IS NULL + OR NEW.pod_receipt_count IS DISTINCT FROM expected_pod_count + OR NEW.pod_receipt_closure_sha256 IS DISTINCT FROM NEW.verification_receipt_sha256 + OR NEW.entry_version IS DISTINCT FROM OLD.entry_version + 1 + OR NEW.target_kid IS DISTINCT FROM OLD.target_kid + OR NEW.compact_token_sha256 IS DISTINCT FROM OLD.compact_token_sha256 + OR NEW.signing_attempted_at_epoch_seconds IS DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + OR NEW.verified_at_epoch_seconds IS NULL + OR NEW.verified_at_epoch_seconds < OLD.planned_issued_at_epoch_seconds + OR NEW.verified_at_epoch_seconds >= OLD.expires_at_epoch_seconds + OR to_timestamp(NEW.verified_at_epoch_seconds) > CURRENT_TIMESTAMP + OR NEW.validator_instance_id IS NULL + OR NEW.validator_binding_digest IS NULL + OR NEW.validator_config_revision IS NULL + OR NEW.validator_peer_uri IS NULL + OR NEW.validator_peer_spki_sha256 IS NULL + OR CURRENT_TIMESTAMP < to_timestamp(OLD.planned_issued_at_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + OR NEW.terminal_outcome IS NOT NULL THEN + RAISE EXCEPTION 'Readiness V2 VERIFIED transition lacks complete exact per-Pod receipts' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'ABORTED' + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 + AND NEW.terminal_outcome = 'ABORTED' THEN + RETURN NEW; + END IF; + IF OLD.state IN ('PLANNED', 'ISSUED', 'VERIFIED') + AND NEW.state = 'EXPIRED' + AND CURRENT_TIMESTAMP >= to_timestamp(OLD.expires_at_epoch_seconds) + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 + AND NEW.terminal_outcome = 'EXPIRED' THEN + RETURN NEW; + END IF; + IF OLD.state IN ('ABORTED', 'EXPIRED') AND NEW.state = 'CLEANED' + AND NEW.terminal_outcome = OLD.terminal_outcome + AND NEW.compact_token_sha256 IS NOT DISTINCT FROM OLD.compact_token_sha256 + AND NEW.signing_attempted_at_epoch_seconds IS NOT DISTINCT FROM OLD.signing_attempted_at_epoch_seconds + AND NEW.verification_receipt_sha256 IS NOT DISTINCT FROM OLD.verification_receipt_sha256 + AND NEW.verification_receipt_version IS NOT DISTINCT FROM OLD.verification_receipt_version + AND NEW.verification_source_entry_version IS NOT DISTINCT FROM OLD.verification_source_entry_version + AND NEW.verified_at_epoch_seconds IS NOT DISTINCT FROM OLD.verified_at_epoch_seconds + AND NEW.verified_kid IS NOT DISTINCT FROM OLD.verified_kid + AND NEW.validator_instance_id IS NOT DISTINCT FROM OLD.validator_instance_id + AND NEW.validator_binding_digest IS NOT DISTINCT FROM OLD.validator_binding_digest + AND NEW.validator_config_revision IS NOT DISTINCT FROM OLD.validator_config_revision + AND NEW.validator_peer_uri IS NOT DISTINCT FROM OLD.validator_peer_uri + AND NEW.validator_peer_spki_sha256 IS NOT DISTINCT FROM OLD.validator_peer_spki_sha256 + AND NEW.pod_receipt_count IS NOT DISTINCT FROM OLD.pod_receipt_count + AND NEW.pod_receipt_closure_sha256 IS NOT DISTINCT FROM OLD.pod_receipt_closure_sha256 THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Account JWT readiness V2 lifecycle transition is unavailable' + USING ERRCODE = '23514'; +END; +$$; + +CREATE TRIGGER account_jwt_readiness_entry_lifecycle_v2 + BEFORE INSERT OR UPDATE ON account_jwt_readiness_probe_entries + FOR EACH ROW WHEN (NEW.entry_plan_version = 2) + EXECUTE FUNCTION account_jwt_readiness_entry_v2_lifecycle_guard(); + +CREATE FUNCTION account_jwt_readiness_inventory_plan_closure_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + operation_id UUID; + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + snapshot_json jsonb; + expected_entry_count integer; + actual_entry_count integer; + expected_pod_count integer; + actual_pod_count integer; +BEGIN + operation_id := CASE WHEN TG_OP = 'DELETE' THEN OLD.rotation_operation_id ELSE NEW.rotation_operation_id END; + SELECT * INTO plan_row FROM account_jwt_readiness_probe_plans WHERE rotation_operation_id = operation_id; + IF NOT FOUND OR plan_row.plan_version <> 2 THEN + RETURN NULL; + END IF; + SELECT convert_from(canonical_snapshot, 'UTF8')::jsonb INTO snapshot_json + FROM account_jwt_validator_inventory_snapshots + WHERE snapshot_digest = plan_row.inventory_snapshot_digest; + IF snapshot_json IS NULL THEN + RAISE EXCEPTION 'Readiness V2 inventory snapshot is missing' USING ERRCODE = '23514'; + END IF; + IF jsonb_typeof(snapshot_json -> 'validators') IS DISTINCT FROM 'array' + OR jsonb_typeof(plan_row.applicability_matrix_json::jsonb -> 'validators') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'Readiness V2 inventory validator sets are malformed' USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + WHERE validator.value ->> 'validatorId' IS NULL + OR jsonb_typeof(validator.value -> 'profiles') IS DISTINCT FROM 'array') + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS validator(value) + WHERE validator.value ->> 'validatorId' IS NULL + OR jsonb_typeof(validator.value -> 'applicableProfiles') IS DISTINCT FROM 'array') THEN + RAISE EXCEPTION 'Readiness V2 inventory profile bindings are malformed' USING ERRCODE = '23514'; + END IF; + SELECT count(*) * 4 INTO expected_entry_count + FROM jsonb_array_elements(snapshot_json -> 'validators'); + SELECT count(*) INTO actual_entry_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = operation_id AND plan_digest = plan_row.plan_digest; + SELECT COALESCE(sum(jsonb_array_length(validator.value -> 'pods') * 4), 0) + INTO expected_pod_count + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value); + SELECT count(*) INTO actual_pod_count + FROM account_jwt_readiness_validator_pods + WHERE rotation_operation_id = operation_id AND plan_digest = plan_row.plan_digest; + IF actual_entry_count <> expected_entry_count + OR actual_pod_count <> expected_pod_count + OR actual_entry_count > 256 OR actual_pod_count > 256 + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS snapshot_validator(value) + WHERE NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS matrix_validator(value) + WHERE matrix_validator.value ->> 'validatorId' = snapshot_validator.value ->> 'validatorId')) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS matrix_validator(value) + WHERE NOT EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS snapshot_validator(value) + WHERE snapshot_validator.value ->> 'validatorId' = matrix_validator.value ->> 'validatorId')) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS snapshot_validator(value) + JOIN jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'validators') AS matrix_validator(value) + ON matrix_validator.value ->> 'validatorId' = snapshot_validator.value ->> 'validatorId' + WHERE COALESCE(( + SELECT jsonb_agg( + jsonb_build_object( + 'tokenProfile', profile.value ->> 'tokenProfile', + 'audience', profile.value ->> 'audience') + ORDER BY profile.value ->> 'tokenProfile', profile.value ->> 'audience') + FROM jsonb_array_elements(snapshot_validator.value -> 'profiles') AS profile(value)), + '[]'::jsonb) + IS DISTINCT FROM COALESCE(( + SELECT jsonb_agg( + jsonb_build_object( + 'tokenProfile', profile.value ->> 'tokenProfile', + 'audience', profile.value ->> 'audience') + ORDER BY profile.value ->> 'tokenProfile', profile.value ->> 'audience') + FROM jsonb_array_elements(matrix_validator.value -> 'applicableProfiles') AS profile(value)), + '[]'::jsonb)) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(plan_row.applicability_matrix_json::jsonb -> 'productionProfiles') AS profile(value) + WHERE NOT EXISTS ( + SELECT 1 FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND entry.validator_id = validator.value ->> 'validatorId' + AND entry.token_profile = profile.value ->> 'tokenProfile' + AND entry.audience = profile.value ->> 'audience' + AND entry.probe_kind = 'REPRESENTATIVE')) + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + WHERE NOT EXISTS ( + SELECT 1 FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND entry.validator_id = validator.value ->> 'validatorId' + AND entry.token_profile = 'account-jwt-readiness-canary' + AND entry.audience = 'firemud-account-jwt-readiness' + AND entry.probe_kind = 'CANARY')) + OR EXISTS ( + SELECT 1 + FROM account_jwt_readiness_probe_entries entry + WHERE entry.rotation_operation_id = operation_id + AND entry.plan_digest = plan_row.plan_digest + AND (SELECT count(*) FROM account_jwt_readiness_validator_pods target + WHERE target.rotation_operation_id = entry.rotation_operation_id + AND target.validator_id = entry.validator_id + AND target.token_profile = entry.token_profile + AND target.audience = entry.audience + AND target.probe_kind = entry.probe_kind) + <> (SELECT jsonb_array_length(validator.value -> 'pods') + FROM jsonb_array_elements(snapshot_json -> 'validators') AS validator(value) + WHERE validator.value ->> 'validatorId' = entry.validator_id)) THEN + RAISE EXCEPTION 'Readiness V2 plan is missing a validator entry or exact per-Pod inventory row' + USING ERRCODE = '23514'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER account_jwt_readiness_plan_v2_closure + AFTER INSERT ON account_jwt_readiness_probe_plans + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +CREATE CONSTRAINT TRIGGER account_jwt_readiness_entry_v2_closure + AFTER INSERT ON account_jwt_readiness_probe_entries + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +CREATE CONSTRAINT TRIGGER account_jwt_readiness_pod_v2_closure + AFTER INSERT ON account_jwt_readiness_validator_pods + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION account_jwt_readiness_inventory_plan_closure_guard(); +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V124__account_jwt_readiness_version_aware_delivery_claim_guard.sql b/services/account-service/src/main/resources/db/migration/V124__account_jwt_readiness_version_aware_delivery_claim_guard.sql new file mode 100644 index 0000000000..7fbc6992ab --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V124__account_jwt_readiness_version_aware_delivery_claim_guard.sql @@ -0,0 +1,84 @@ +-- Keep delivery claims compatible with retained V1 plans while requiring the complete V2 +-- validator/profile registry created from the exact immutable protected inventory snapshot. +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_readiness_delivery_claim_guard() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + plan_row account_jwt_readiness_probe_plans%ROWTYPE; + snapshot_json jsonb; + expected_entry_count integer; + actual_entry_count integer; +BEGIN + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest; + IF NOT FOUND + OR NEW.expected_cluster_incarnation_uid IS DISTINCT FROM plan_row.expected_cluster_incarnation_uid + OR NEW.expected_namespace_uid IS DISTINCT FROM plan_row.expected_namespace_uid + OR NEW.materializer_trust_binding_digest IS DISTINCT FROM plan_row.trust_binding_digest + OR NEW.materializer_trust_config_revision IS DISTINCT FROM plan_row.trust_config_revision + OR NEW.target_generation IS DISTINCT FROM plan_row.target_generation + OR NEW.target_kid IS DISTINCT FROM plan_row.target_kid + OR NEW.expected_active_generation IS DISTINCT FROM plan_row.expected_active_generation + OR NEW.expected_active_kid IS DISTINCT FROM plan_row.expected_active_kid + OR NEW.expires_at_epoch_seconds IS DISTINCT FROM plan_row.expires_at_epoch_seconds + OR NEW.validator_id <> 'account-service' + OR NEW.readiness_binding_valid_until_epoch_seconds <= NEW.claimed_at_epoch_seconds + OR NEW.validator_peer_uri IS DISTINCT FROM + 'spiffe://firemud/ns/' || plan_row.kubernetes_namespace || '/sa/account-jwt-readiness-harness' + OR NEW.claimed_at_epoch_seconds < plan_row.not_before_epoch_seconds + OR NEW.claimed_at_epoch_seconds >= plan_row.expires_at_epoch_seconds + OR CURRENT_TIMESTAMP < to_timestamp(plan_row.not_before_epoch_seconds) + OR CURRENT_TIMESTAMP >= to_timestamp(plan_row.expires_at_epoch_seconds) THEN + RAISE EXCEPTION 'Account readiness delivery claim differs from its current exact plan' + USING ERRCODE = '23514'; + END IF; + + IF plan_row.plan_version = 1 THEN + expected_entry_count := + 1 + jsonb_array_length(plan_row.applicability_matrix_json::jsonb #> + '{validators,0,applicableProfiles}'); + ELSIF plan_row.plan_version = 2 THEN + IF plan_row.validator_inventory_complete IS DISTINCT FROM TRUE + OR plan_row.inventory_snapshot_digest IS NULL + OR plan_row.applicability_matrix_json::jsonb ->> 'inventorySnapshotDigest' + IS DISTINCT FROM plan_row.inventory_snapshot_digest THEN + RAISE EXCEPTION 'Account readiness delivery claim requires a complete exact V2 inventory plan' + USING ERRCODE = '23514'; + END IF; + SELECT convert_from(canonical_snapshot, 'UTF8')::jsonb + INTO snapshot_json + FROM account_jwt_validator_inventory_snapshots + WHERE snapshot_digest = plan_row.inventory_snapshot_digest; + IF NOT FOUND + OR snapshot_json IS NULL + OR jsonb_typeof(snapshot_json -> 'validators') IS DISTINCT FROM 'array' + OR jsonb_array_length(snapshot_json -> 'validators') NOT BETWEEN 1 AND 32 THEN + RAISE EXCEPTION 'Account readiness delivery claim requires its exact V2 inventory snapshot' + USING ERRCODE = '23514'; + END IF; + expected_entry_count := jsonb_array_length(snapshot_json -> 'validators') * 4; + ELSE + RAISE EXCEPTION 'Account readiness delivery claim has an unknown plan version' + USING ERRCODE = '23514'; + END IF; + + SELECT COUNT(*) INTO actual_entry_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.rotation_operation_id + AND plan_digest = NEW.plan_digest + AND state = 'PLANNED' + AND compact_token_sha256 IS NULL + AND signing_attempted_at_epoch_seconds IS NULL + AND verification_receipt_sha256 IS NULL; + IF actual_entry_count <> expected_entry_count THEN + RAISE EXCEPTION 'Account readiness delivery claim requires untouched planned entries' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +-- [jooq ignore end] diff --git a/services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql b/services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql new file mode 100644 index 0000000000..748300ef3f --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql @@ -0,0 +1,481 @@ +-- Bind the exact Account-verified readiness proof bytes and the complete parsed proof projection +-- to the existing immutable signer, publication, inventory, and probe owner rows. +ALTER TABLE account_jwt_signer_promotion_operations + ADD COLUMN readiness_evidence_preimage BYTEA NOT NULL; + +-- [jooq ignore start] +CREATE OR REPLACE FUNCTION account_jwt_signer_promotion_insert_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + state_row RECORD; + generation_row RECORD; + result_row RECORD; + plan_generation_receipt_digest VARCHAR(64); + plan_inventory_complete BOOLEAN; + plan_expires_at BIGINT; + entry_count BIGINT; + verified_count BIGINT; + plan_row RECORD; + proof_document JSONB; + expected_plan JSONB; + expected_generation JSONB; + expected_publication JSONB; + expected_verified_probes JSONB; +BEGIN + IF NEW.operation_action <> 'PROMOTE_PENDING' + OR NEW.generation_operation_id IS NULL + OR NEW.expected_cluster_incarnation_uid IS NULL + OR NEW.expected_namespace_uid IS NULL + OR NEW.expected_private_secret_uid IS NULL + OR NEW.expected_public_config_map_uid IS NULL THEN + RAISE EXCEPTION 'Promotion request lacks its exact lifecycle binding' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + -- Lock order is desired state, then source generation, then immutable evidence. + SELECT * INTO state_row FROM account_jwt_signer_desired_states + WHERE environment_id = NEW.environment_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT signer desired state is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO generation_row FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation operation is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + SELECT * INTO result_row FROM account_jwt_signer_generation_results + WHERE operation_id = NEW.generation_operation_id FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'Account JWT generation result is missing' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + IF state_row.generation_operation_id IS DISTINCT FROM NEW.generation_operation_id + OR state_row.prepared_operation_id IS NOT NULL + OR state_row.record_version IS DISTINCT FROM NEW.expected_record_version + OR (state_row.cluster_id, state_row.kubernetes_namespace, state_row.custody_mode) + IS DISTINCT FROM (NEW.cluster_id, NEW.kubernetes_namespace, NEW.custody_mode) + OR (state_row.durable_active_generation, state_row.durable_active_kid) + IS DISTINCT FROM (NEW.expected_previous_generation, NEW.expected_previous_kid) + OR (state_row.published_active_generation, state_row.published_active_kid) + IS DISTINCT FROM (NEW.expected_public_active_generation, NEW.expected_public_active_kid) + OR state_row.enrollment_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR state_row.enrollment_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR state_row.enrollment_materializer_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR state_row.enrollment_materializer_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR state_row.enrollment_api_binding_digest IS DISTINCT FROM NEW.api_binding_digest + OR state_row.enrollment_api_config_revision IS DISTINCT FROM NEW.api_config_revision + OR state_row.enrollment_public_config_map_uid IS DISTINCT FROM NEW.expected_public_config_map_uid + OR generation_row.operation_id IS NULL + OR generation_row.environment_id IS DISTINCT FROM NEW.environment_id + OR generation_row.expected_cluster_incarnation_uid IS DISTINCT FROM NEW.expected_cluster_incarnation_uid + OR generation_row.expected_namespace_uid IS DISTINCT FROM NEW.expected_namespace_uid + OR generation_row.trust_binding_digest IS DISTINCT FROM NEW.materializer_trust_binding_digest + OR generation_row.trust_config_revision IS DISTINCT FROM NEW.materializer_trust_config_revision + OR generation_row.target_generation IS DISTINCT FROM NEW.target_generation + OR generation_row.target_kid IS DISTINCT FROM NEW.target_kid + OR generation_row.expected_record_version + 1 IS DISTINCT FROM result_row.desired_state_version + OR result_row.secret_uid IS DISTINCT FROM NEW.expected_private_secret_uid + OR result_row.observed_resource_version IS DISTINCT FROM NEW.expected_private_secret_resource_version + OR result_row.public_key_fingerprint IS DISTINCT FROM NEW.target_public_key_fingerprint THEN + RAISE EXCEPTION 'JWT promotion request does not match current Account generation evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + IF EXISTS ( + SELECT 1 FROM account_jwt_signer_generation_abort_receipts AS abort_receipt + WHERE abort_receipt.operation_id = NEW.generation_operation_id) THEN + RAISE EXCEPTION 'JWT promotion cannot reuse a terminally aborted generation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + + IF NEW.readiness_evidence_preimage IS NULL + OR octet_length(NEW.readiness_evidence_preimage) NOT BETWEEN 2 AND 1048576 + OR encode(sha256(NEW.readiness_evidence_preimage), 'hex') + IS DISTINCT FROM NEW.readiness_evidence_digest THEN + RAISE EXCEPTION 'JWT promotion readiness digest does not hash its exact proof preimage' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_digest'; + END IF; + proof_document := convert_from(NEW.readiness_evidence_preimage, 'UTF8')::jsonb; + IF jsonb_typeof(proof_document) IS DISTINCT FROM 'object' + OR proof_document - ARRAY['digestVersion', 'plan', 'planDigest', 'generation', + 'publication', 'inventoryEvidenceReference', 'inventoryEvidenceDigest', + 'verifiedProbes'] <> '{}'::jsonb + OR (SELECT count(*) FROM jsonb_object_keys(proof_document)) <> 8 + OR proof_document->>'digestVersion' IS DISTINCT FROM + 'account-jwt-readiness-promotion-proof/v1' THEN + RAISE EXCEPTION 'JWT promotion readiness proof has an unexpected shape or version' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_binding'; + END IF; + + SELECT * INTO plan_row + FROM account_jwt_readiness_probe_plans + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest FOR SHARE; + plan_generation_receipt_digest := plan_row.generation_receipt_digest; + plan_inventory_complete := plan_row.validator_inventory_complete; + plan_expires_at := plan_row.expires_at_epoch_seconds; + IF plan_generation_receipt_digest IS DISTINCT FROM result_row.receipt_digest + OR plan_inventory_complete IS DISTINCT FROM TRUE + OR plan_expires_at IS NULL + OR plan_expires_at <= floor(extract(epoch FROM CURRENT_TIMESTAMP))::BIGINT THEN + RAISE EXCEPTION 'JWT promotion requires current complete validator inventory proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + SELECT count(*), count(*) FILTER (WHERE state = 'VERIFIED' + AND verified_at_epoch_seconds < expires_at_epoch_seconds) + INTO entry_count, verified_count + FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest; + IF entry_count = 0 OR verified_count <> entry_count THEN + RAISE EXCEPTION 'JWT promotion requires every exact readiness probe to be VERIFIED' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + + -- V2 receipts are mutable only through their one-way Account transition. Lock the exact + -- ordered set before comparing the complete proof projection to those owner rows. + PERFORM 1 FROM account_jwt_readiness_probe_entries + WHERE rotation_operation_id = NEW.generation_operation_id + AND plan_digest = NEW.readiness_plan_digest + ORDER BY validator_id, + CASE token_profile WHEN 'account-jwt-readiness-canary' THEN 0 WHEN 'control-ui' THEN 1 + WHEN 'player-bootstrap' THEN 2 WHEN 'game-session-account-delegation' THEN 3 ELSE 4 END, + token_profile, audience, probe_kind + FOR SHARE; + + SELECT jsonb_build_object( + 'digestVersion', 'account-jwt-readiness-probe-plan/v2', + 'rotationOperationId', plan_row.rotation_operation_id::text, + 'environmentId', plan_row.environment_id, + 'clusterId', plan_row.cluster_id, + 'namespace', plan_row.kubernetes_namespace, + 'custodyMode', plan_row.custody_mode, + 'operationDigest', plan_row.operation_digest, + 'generationRequestDigest', plan_row.generation_request_digest, + 'generationReceiptDigest', plan_row.generation_receipt_digest, + 'desiredStateVersion', plan_row.desired_state_version, + 'trustFence', jsonb_build_object( + 'clusterIncarnationUid', plan_row.expected_cluster_incarnation_uid::text, + 'namespaceUid', plan_row.expected_namespace_uid::text, + 'bindingDigest', plan_row.trust_binding_digest, + 'configRevision', plan_row.trust_config_revision), + 'targetGeneration', plan_row.target_generation::text, + 'targetKid', plan_row.target_kid, + 'targetPublicKeyFingerprint', plan_row.target_public_key_fingerprint, + 'expectedActive', CASE WHEN plan_row.expected_active_generation IS NULL + THEN jsonb_build_object('present', false) + ELSE jsonb_build_object('present', true, + 'generation', plan_row.expected_active_generation::text, + 'kid', plan_row.expected_active_kid) END, + 'expectedPublishedActive', CASE WHEN plan_row.expected_published_generation IS NULL + THEN jsonb_build_object('present', false) + ELSE jsonb_build_object('present', true, + 'generation', plan_row.expected_published_generation::text, + 'kid', plan_row.expected_published_kid) END, + 'publicationIntentDigest', plan_row.publication_intent_digest, + 'publicationReceiptDigest', plan_row.publication_receipt_digest, + 'mountedObservationDigest', plan_row.mounted_observation_digest, + 'applicabilityMatrixJson', plan_row.applicability_matrix_json, + 'applicabilityMatrixDigest', plan_row.applicability_matrix_digest, + 'validatorInventoryComplete', plan_row.validator_inventory_complete, + 'planVersion', plan_row.plan_version, + 'inventorySnapshotDigest', plan_row.inventory_snapshot_digest, + 'maximumCacheAgeSeconds', plan_row.maximum_cache_age_seconds, + 'plannedAtEpochSecond', plan_row.planned_at_epoch_seconds, + 'notBeforeEpochSecond', plan_row.not_before_epoch_seconds, + 'expiresAtEpochSecond', plan_row.expires_at_epoch_seconds, + 'entries', COALESCE(( + SELECT jsonb_agg(jsonb_build_object( + 'validatorId', entry.validator_id, + 'tokenProfile', entry.token_profile, + 'audience', entry.audience, + 'probeKind', entry.probe_kind, + 'jti', entry.jti::text, + 'targetGeneration', entry.target_generation::text, + 'targetKid', entry.target_kid, + 'expectedActive', CASE WHEN entry.expected_active_generation IS NULL + THEN jsonb_build_object('present', false) + ELSE jsonb_build_object('present', true, + 'generation', entry.expected_active_generation::text, + 'kid', entry.expected_active_kid) END, + 'registryVersion', entry.registry_version, + 'entryVersion', 1, + 'plannedIssuedAtEpochSecond', entry.planned_issued_at_epoch_seconds, + 'expiresAtEpochSecond', entry.expires_at_epoch_seconds) + ORDER BY entry.validator_id, + CASE entry.token_profile WHEN 'account-jwt-readiness-canary' THEN 0 WHEN 'control-ui' THEN 1 + WHEN 'player-bootstrap' THEN 2 + WHEN 'game-session-account-delegation' THEN 3 ELSE 4 END, + entry.token_profile, entry.audience, entry.probe_kind) + FROM account_jwt_readiness_probe_entries AS entry + WHERE entry.rotation_operation_id = plan_row.rotation_operation_id + AND entry.plan_digest = plan_row.plan_digest), '[]'::jsonb)) + INTO expected_plan; + + expected_generation := jsonb_build_object( + 'operationId', result_row.operation_id::text, + 'environmentId', result_row.environment_id, + 'clusterId', result_row.cluster_id, + 'namespace', result_row.kubernetes_namespace, + 'custodyMode', result_row.custody_mode, + 'operationDigest', result_row.operation_digest, + 'generationRequestDigest', result_row.generation_request_digest, + 'desiredStateVersion', result_row.desired_state_version, + 'trustFence', jsonb_build_object( + 'clusterIncarnationUid', result_row.expected_cluster_incarnation_uid::text, + 'namespaceUid', result_row.expected_namespace_uid::text, + 'bindingDigest', result_row.trust_binding_digest, + 'configRevision', result_row.trust_config_revision), + 'privateSecretName', result_row.private_secret_name, + 'secretUid', result_row.secret_uid::text, + 'expectedPriorResourceVersion', result_row.expected_prior_resource_version, + 'observedResourceVersion', result_row.observed_resource_version, + 'targetGeneration', result_row.target_generation::text, + 'targetKid', result_row.target_kid, + 'targetAlgorithm', result_row.target_algorithm, + 'publicKeyFingerprint', result_row.public_key_fingerprint, + 'publicJwkJson', result_row.public_jwk_json, + 'receiptDigest', result_row.receipt_digest); + + SELECT jsonb_build_object( + 'intent', jsonb_build_object( + 'operationId', intent.operation_id::text, + 'environmentId', intent.environment_id, + 'clusterId', intent.cluster_id, + 'namespace', intent.kubernetes_namespace, + 'operationDigest', intent.operation_digest, + 'generationRequestDigest', intent.generation_request_digest, + 'generationReceiptDigest', intent.generation_receipt_digest, + 'desiredStateVersion', intent.desired_state_version, + 'trustFence', jsonb_build_object( + 'clusterIncarnationUid', intent.expected_cluster_incarnation_uid::text, + 'namespaceUid', intent.expected_namespace_uid::text, + 'bindingDigest', intent.trust_binding_digest, + 'configRevision', intent.trust_config_revision), + 'apiBindingDigest', intent.api_binding_digest, + 'apiConfigRevision', intent.api_config_revision, + 'configMapName', intent.config_map_name, + 'configMapUid', intent.config_map_uid::text, + 'expectedResourceVersion', intent.expected_resource_version, + 'expectedSnapshotDigest', intent.expected_snapshot_digest, + 'targetGeneration', intent.target_generation::text, + 'targetKid', intent.target_kid, + 'publicKeyFingerprint', intent.public_key_fingerprint, + 'expectedDurableActive', intent.expected_durable_active_json::jsonb, + 'expectedPublishedActive', intent.expected_published_active_json::jsonb, + 'publicDataDigest', intent.public_data_digest, + 'generationMarkerDigest', intent.generation_marker_digest, + 'intentDigest', intent.intent_digest), + 'receipt', jsonb_build_object( + 'operationId', receipt.operation_id::text, + 'intentDigest', receipt.intent_digest, + 'configMapUid', receipt.config_map_uid::text, + 'expectedResourceVersion', receipt.expected_resource_version, + 'observedResourceVersion', receipt.observed_resource_version, + 'publicDataDigest', receipt.public_data_digest, + 'receiptDigest', receipt.receipt_digest), + 'mount', jsonb_build_object( + 'operationId', mount.operation_id::text, + 'intentDigest', mount.intent_digest, + 'publicationReceiptDigest', mount.publication_receipt_digest, + 'generationMarkerDigest', mount.generation_marker_digest, + 'publicDataDigest', mount.public_data_digest, + 'publicKeyFingerprint', mount.public_key_fingerprint, + 'observationDigest', mount.observation_digest)) + INTO expected_publication + FROM account_jwt_jwks_prepublication_intents AS intent + JOIN account_jwt_jwks_publication_receipts AS receipt + ON receipt.operation_id = intent.operation_id + AND receipt.intent_digest = intent.intent_digest + JOIN account_jwt_jwks_mount_observations AS mount + ON mount.operation_id = intent.operation_id + WHERE intent.operation_id = NEW.generation_operation_id + AND intent.intent_digest = NEW.prepublication_intent_digest + AND receipt.receipt_digest = NEW.prepublication_receipt_digest + AND mount.observation_digest = NEW.mounted_observation_digest; + + SELECT jsonb_agg(jsonb_build_object( + 'rotationOperationId', entry.rotation_operation_id::text, + 'planDigest', entry.plan_digest, + 'validatorId', entry.validator_id, + 'tokenProfile', entry.token_profile, + 'audience', entry.audience, + 'probeKind', entry.probe_kind, + 'jti', entry.jti::text, + 'targetGeneration', entry.target_generation::text, + 'targetKid', entry.target_kid, + 'expectedActive', CASE WHEN entry.expected_active_generation IS NULL + THEN jsonb_build_object('present', false) + ELSE jsonb_build_object('present', true, + 'generation', entry.expected_active_generation::text, + 'kid', entry.expected_active_kid) END, + 'registryVersion', entry.registry_version, + 'entryVersion', entry.entry_version, + 'plannedIssuedAtEpochSecond', entry.planned_issued_at_epoch_seconds, + 'expiresAtEpochSecond', entry.expires_at_epoch_seconds, + 'compactTokenSha256', entry.compact_token_sha256, + 'verificationReceipt', jsonb_build_object( + 'receiptVersion', entry.verification_receipt_version, + 'sourceEntryVersion', entry.verification_source_entry_version, + 'resultEntryVersion', entry.entry_version, + 'observedAtEpochSecond', entry.verified_at_epoch_seconds, + 'receiptSha256', entry.verification_receipt_sha256, + 'verifiedKid', entry.verified_kid, + 'validatorInstanceId', entry.validator_instance_id, + 'validatorBindingDigest', entry.validator_binding_digest, + 'validatorConfigRevision', entry.validator_config_revision, + 'validatorPeerUri', entry.validator_peer_uri, + 'validatorPeerSpkiSha256', entry.validator_peer_spki_sha256, + 'podReceiptCount', entry.pod_receipt_count, + 'podReceiptClosureSha256', entry.pod_receipt_closure_sha256)) + ORDER BY entry.validator_id, + CASE entry.token_profile WHEN 'account-jwt-readiness-canary' THEN 0 WHEN 'control-ui' THEN 1 + WHEN 'player-bootstrap' THEN 2 + WHEN 'game-session-account-delegation' THEN 3 ELSE 4 END, + entry.token_profile, entry.audience, entry.probe_kind) + INTO expected_verified_probes + FROM account_jwt_readiness_probe_entries AS entry + WHERE entry.rotation_operation_id = NEW.generation_operation_id + AND entry.plan_digest = NEW.readiness_plan_digest + AND entry.state = 'VERIFIED'; + + IF expected_publication IS NULL + OR proof_document->'planDigest' IS DISTINCT FROM to_jsonb(plan_row.plan_digest) + OR proof_document->'plan' IS DISTINCT FROM expected_plan + OR proof_document->'generation' IS DISTINCT FROM expected_generation + OR proof_document->'publication' IS DISTINCT FROM expected_publication + OR proof_document->'inventoryEvidenceReference' IS DISTINCT FROM + to_jsonb('protected-validator-inventory:' || plan_row.inventory_snapshot_digest) + OR proof_document->'inventoryEvidenceDigest' IS DISTINCT FROM + to_jsonb(plan_row.inventory_snapshot_digest) + OR proof_document->'verifiedProbes' IS DISTINCT FROM expected_verified_probes THEN + RAISE EXCEPTION 'JWT promotion proof does not match complete immutable owner evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_binding'; + END IF; + + IF NOT EXISTS ( + SELECT 1 FROM account_jwt_jwks_prepublication_intents AS intent + JOIN account_jwt_jwks_publication_receipts AS receipt + ON receipt.operation_id = intent.operation_id + AND receipt.intent_digest = intent.intent_digest + JOIN account_jwt_jwks_mount_observations AS mount + ON mount.operation_id = intent.operation_id + WHERE intent.operation_id = NEW.generation_operation_id + AND intent.intent_digest = NEW.prepublication_intent_digest + AND receipt.receipt_digest = NEW.prepublication_receipt_digest + AND mount.observation_digest = NEW.mounted_observation_digest + AND intent.config_map_uid = NEW.expected_public_config_map_uid + AND intent.api_binding_digest = NEW.api_binding_digest + AND intent.api_config_revision = NEW.api_config_revision + AND receipt.observed_resource_version = NEW.expected_public_jwks_resource_version + AND intent.public_key_fingerprint = NEW.target_public_key_fingerprint + AND intent.jwks_json = NEW.expected_public_jwks_json) THEN + RAISE EXCEPTION 'JWT promotion request does not match exact current prepublication evidence' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_insert_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_readiness_preimage_immutable_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.readiness_evidence_preimage IS DISTINCT FROM OLD.readiness_evidence_preimage THEN + RAISE EXCEPTION 'Account JWT signer readiness proof preimage is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_immutable'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_signer_readiness_preimage_immutable + BEFORE UPDATE OF readiness_evidence_preimage ON account_jwt_signer_promotion_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_readiness_preimage_immutable_guard(); + +-- The dispatch marker is the last reversible boundary before the materializer may mutate the +-- fixed private Secret. Keep a database-level freshness fence for direct SQL callers as well as +-- the repository CAS; after this marker is durable, recovery uses the frozen proof and receipts. +CREATE FUNCTION account_jwt_signer_promotion_readiness_dispatch_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + proof_document JSONB; + checked_at TIMESTAMPTZ; + now_epoch BIGINT; + probe_count BIGINT; + plan_inventory_complete BOOLEAN; + plan_not_before BIGINT; + plan_expires_at BIGINT; + entry_count BIGINT; + verified_count BIGINT; +BEGIN + IF OLD.private_promotion_dispatched_at IS NULL + AND NEW.private_promotion_dispatched_at IS NOT NULL THEN + IF NEW.readiness_evidence_preimage IS NULL + OR encode(sha256(NEW.readiness_evidence_preimage), 'hex') + IS DISTINCT FROM NEW.readiness_evidence_digest THEN + RAISE EXCEPTION 'JWT promotion dispatch lacks its exact frozen readiness proof' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + proof_document := convert_from(NEW.readiness_evidence_preimage, 'UTF8')::JSONB; + IF jsonb_typeof(proof_document) IS DISTINCT FROM 'object' + OR jsonb_typeof(proof_document -> 'verifiedProbes') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'JWT promotion dispatch lacks its exact frozen readiness probe set' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + probe_count := jsonb_array_length(proof_document -> 'verifiedProbes'); + IF probe_count <= 0 OR probe_count > 32 THEN + RAISE EXCEPTION 'JWT promotion dispatch readiness probe set is outside its bound' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + + SELECT plan.validator_inventory_complete, + plan.not_before_epoch_seconds, + plan.expires_at_epoch_seconds + INTO plan_inventory_complete, plan_not_before, plan_expires_at + FROM account_jwt_readiness_probe_plans AS plan + WHERE plan.rotation_operation_id = NEW.generation_operation_id + AND plan.plan_digest = NEW.readiness_plan_digest + FOR SHARE; + PERFORM 1 + FROM account_jwt_readiness_probe_entries AS entry + WHERE entry.rotation_operation_id = NEW.generation_operation_id + AND entry.plan_digest = NEW.readiness_plan_digest + FOR SHARE; + checked_at := clock_timestamp(); + now_epoch := floor(extract(epoch FROM checked_at))::BIGINT; + SELECT count(*), count(*) FILTER ( + WHERE entry.state = 'VERIFIED' + AND entry.verification_receipt_sha256 IS NOT NULL + AND entry.verified_at_epoch_seconds < entry.expires_at_epoch_seconds + AND entry.expires_at_epoch_seconds > now_epoch) + INTO entry_count, verified_count + FROM account_jwt_readiness_probe_entries AS entry + WHERE entry.rotation_operation_id = NEW.generation_operation_id + AND entry.plan_digest = NEW.readiness_plan_digest; + IF plan_inventory_complete IS DISTINCT FROM TRUE + OR plan_not_before IS NULL + OR plan_expires_at IS NULL + OR now_epoch < plan_not_before + OR now_epoch >= plan_expires_at + OR entry_count IS DISTINCT FROM probe_count + OR verified_count IS DISTINCT FROM probe_count THEN + RAISE EXCEPTION 'JWT promotion readiness expired or changed before private dispatch' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_promotion_readiness_incomplete'; + END IF; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER account_jwt_signer_promotion_readiness_dispatch_guard + BEFORE UPDATE OF private_promotion_dispatched_at ON account_jwt_signer_promotion_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_promotion_readiness_dispatch_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql b/services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql new file mode 100644 index 0000000000..9048e940f8 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql @@ -0,0 +1,404 @@ +-- Account-owned signer desired state, Account-selected generation requests, and a dormant +-- PREPARED schema for the later lifecycle phase. Generation/materialization evidence is not a +-- PREPARED promotion record and never authorizes signing. +CREATE TABLE account_jwt_signer_desired_states ( + environment_id VARCHAR(63) PRIMARY KEY, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + private_secret_name VARCHAR(63) NOT NULL DEFAULT 'jwt-signing-keys', + public_jwks_config_map_name VARCHAR(63) NOT NULL DEFAULT 'jwt-jwks', + record_version BIGINT NOT NULL DEFAULT 1, + durable_active_generation BIGINT, + durable_active_kid VARCHAR(128), + published_active_generation BIGINT, + published_active_kid VARCHAR(128), + generation_operation_id UUID, + prepared_operation_id UUID, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_state_binding_unique + UNIQUE (environment_id, cluster_id, kubernetes_namespace, custody_mode), + CONSTRAINT account_jwt_signer_state_environment_check + CHECK (environment_id ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_state_cluster_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_state_namespace_check + CHECK (kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_state_mode_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_state_resource_names_check + CHECK (private_secret_name = 'jwt-signing-keys' + AND public_jwks_config_map_name = 'jwt-jwks'), + CONSTRAINT account_jwt_signer_state_version_check CHECK (record_version > 0), + CONSTRAINT account_jwt_signer_state_durable_active_shape_check + CHECK ((durable_active_generation IS NULL AND durable_active_kid IS NULL) + OR (durable_active_generation IS NOT NULL + AND durable_active_generation > 0 + AND durable_active_kid IS NOT NULL + AND durable_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_state_published_active_shape_check + CHECK ((published_active_generation IS NULL AND published_active_kid IS NULL) + OR (published_active_generation IS NOT NULL + AND published_active_generation > 0 + AND published_active_kid IS NOT NULL + AND published_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')) +); + +CREATE TABLE account_jwt_signer_promotion_operations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + request_digest_version SMALLINT NOT NULL, + request_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_previous_generation BIGINT, + expected_previous_kid VARCHAR(128), + target_generation BIGINT NOT NULL, + target_kid VARCHAR(128) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + target_public_key_fingerprint VARCHAR(64) NOT NULL, + expected_private_secret_resource_version VARCHAR(256) NOT NULL, + expected_public_jwks_resource_version VARCHAR(256) NOT NULL, + expected_public_active_generation BIGINT, + expected_public_active_kid VARCHAR(128), + operation_action VARCHAR(32) NOT NULL, + allowed_private_slots_canonical_bytes BYTEA NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'PREPARED', + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_promotion_operation_state_fk + FOREIGN KEY (environment_id) + REFERENCES account_jwt_signer_desired_states(environment_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_promotion_exact_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_promotion_cluster_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_promotion_namespace_check + CHECK (kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT account_jwt_signer_promotion_mode_check + CHECK (custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_promotion_id_v4_check + CHECK (operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_jwt_signer_promotion_digest_check + CHECK (request_digest_version = 1 AND request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_promotion_record_version_check + CHECK (expected_record_version > 0 + AND expected_record_version < 9223372036854775807), + CONSTRAINT account_jwt_signer_promotion_previous_shape_check + CHECK ((expected_previous_generation IS NULL AND expected_previous_kid IS NULL) + OR (expected_previous_generation IS NOT NULL + AND expected_previous_generation > 0 + AND expected_previous_kid IS NOT NULL + AND expected_previous_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_promotion_target_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_previous_generation IS NULL + OR (expected_previous_generation IS NOT NULL + AND target_generation > expected_previous_generation + AND target_kid <> expected_previous_kid))), + CONSTRAINT account_jwt_signer_promotion_algorithm_check + CHECK (target_algorithm = 'RS256'), + CONSTRAINT account_jwt_signer_promotion_fingerprint_check + CHECK (target_public_key_fingerprint ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_promotion_resource_versions_check + CHECK (expected_private_secret_resource_version ~ '^[!-~]+$' + AND char_length(expected_private_secret_resource_version) BETWEEN 1 AND 256 + AND expected_public_jwks_resource_version ~ '^[!-~]+$' + AND char_length(expected_public_jwks_resource_version) BETWEEN 1 AND 256), + CONSTRAINT account_jwt_signer_promotion_public_active_shape_check + CHECK ((expected_public_active_generation IS NULL AND expected_public_active_kid IS NULL) + OR (expected_public_active_generation IS NOT NULL + AND expected_public_active_generation > 0 + AND expected_public_active_kid IS NOT NULL + AND expected_public_active_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_promotion_published_generation_check + CHECK (expected_public_active_generation IS NULL + OR (target_generation > expected_public_active_generation + AND target_kid <> expected_public_active_kid)), + CONSTRAINT account_jwt_signer_promotion_action_check + CHECK (operation_action = 'MATERIALIZE_PENDING'), + CONSTRAINT account_jwt_signer_promotion_slots_check + CHECK (allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea), + CONSTRAINT account_jwt_signer_promotion_status_check CHECK (status = 'PREPARED') +); + +ALTER TABLE account_jwt_signer_desired_states + ADD CONSTRAINT account_jwt_signer_state_prepared_operation_fk + FOREIGN KEY (prepared_operation_id) + REFERENCES account_jwt_signer_promotion_operations(operation_id) + ON DELETE RESTRICT; + +CREATE TABLE account_jwt_signer_generation_operations ( + operation_id UUID PRIMARY KEY, + environment_id VARCHAR(63) NOT NULL, + cluster_id VARCHAR(128) NOT NULL, + kubernetes_namespace VARCHAR(63) NOT NULL, + custody_mode VARCHAR(64) NOT NULL, + operation_digest_version SMALLINT NOT NULL, + operation_digest VARCHAR(64) NOT NULL, + expected_record_version BIGINT NOT NULL, + expected_previous_generation BIGINT, + expected_previous_kid VARCHAR(128), + expected_published_generation BIGINT, + expected_published_kid VARCHAR(128), + target_generation BIGINT NOT NULL, + target_kid VARCHAR(64) NOT NULL, + target_algorithm VARCHAR(16) NOT NULL, + expected_cluster_incarnation_uid UUID NOT NULL, + expected_namespace_uid UUID NOT NULL, + trust_binding_digest VARCHAR(64) NOT NULL, + trust_config_revision VARCHAR(128) NOT NULL, + operation_action VARCHAR(32) NOT NULL, + allowed_private_slots_canonical_bytes BYTEA NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT account_jwt_signer_generation_state_fk + FOREIGN KEY (environment_id) + REFERENCES account_jwt_signer_desired_states(environment_id) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_exact_binding_fk + FOREIGN KEY (environment_id, cluster_id, kubernetes_namespace, custody_mode) + REFERENCES account_jwt_signer_desired_states( + environment_id, cluster_id, kubernetes_namespace, custody_mode) + ON DELETE RESTRICT, + CONSTRAINT account_jwt_signer_generation_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, target_generation, target_kid, + expected_published_generation, expected_published_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_observation_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, expected_record_version, expected_cluster_incarnation_uid, + expected_namespace_uid, trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_receipt_binding_unique + UNIQUE (operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision), + CONSTRAINT account_jwt_signer_generation_id_v4_check + CHECK (operation_id::text ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CONSTRAINT account_jwt_signer_generation_binding_check + CHECK (cluster_id ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$' + AND kubernetes_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$' + AND custody_mode = 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK'), + CONSTRAINT account_jwt_signer_generation_digest_check + CHECK (operation_digest_version = 1 AND operation_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT account_jwt_signer_generation_state_version_check + CHECK (expected_record_version > 0 AND expected_record_version < 9223372036854775807), + CONSTRAINT account_jwt_signer_generation_previous_shape_check + CHECK ((expected_previous_generation IS NULL AND expected_previous_kid IS NULL) + OR (expected_previous_generation IS NOT NULL AND expected_previous_generation > 0 + AND expected_previous_kid IS NOT NULL + AND expected_previous_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_generation_target_check + CHECK (target_generation > 0 + AND target_kid ~ '^[A-Za-z0-9_-]{1,64}$' + AND (expected_previous_generation IS NULL + OR (target_generation > expected_previous_generation + AND target_kid <> expected_previous_kid))), + CONSTRAINT account_jwt_signer_generation_algorithm_check + CHECK (target_algorithm = 'RS256'), + CONSTRAINT account_jwt_signer_generation_published_shape_check + CHECK ((expected_published_generation IS NULL AND expected_published_kid IS NULL) + OR (expected_published_generation IS NOT NULL AND expected_published_generation > 0 + AND expected_published_kid IS NOT NULL + AND expected_published_kid ~ '^[A-Za-z0-9_-]{1,64}$')), + CONSTRAINT account_jwt_signer_generation_trust_check + CHECK (expected_cluster_incarnation_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND expected_namespace_uid <> '00000000-0000-0000-0000-000000000000'::UUID + AND trust_binding_digest ~ '^[0-9a-f]{64}$' + AND trust_config_revision ~ '^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$'), + CONSTRAINT account_jwt_signer_generation_action_check + CHECK (operation_action = 'MATERIALIZE_PENDING'), + CONSTRAINT account_jwt_signer_generation_slots_check + CHECK (allowed_private_slots_canonical_bytes = '\x5b2270656e64696e67225d'::bytea) +); + +ALTER TABLE account_jwt_signer_desired_states + ADD CONSTRAINT account_jwt_signer_state_generation_operation_fk + FOREIGN KEY (generation_operation_id) + REFERENCES account_jwt_signer_generation_operations(operation_id) + ON DELETE RESTRICT; + +CREATE UNIQUE INDEX account_jwt_signer_generation_target_once + ON account_jwt_signer_generation_operations (environment_id, target_generation); + +CREATE UNIQUE INDEX account_jwt_signer_generation_kid_once + ON account_jwt_signer_generation_operations (environment_id, target_kid); + +CREATE UNIQUE INDEX account_jwt_signer_one_prepared_operation_per_environment + ON account_jwt_signer_promotion_operations (environment_id) + WHERE status = 'PREPARED'; + +CREATE UNIQUE INDEX account_jwt_signer_target_generation_once + ON account_jwt_signer_promotion_operations (environment_id, target_generation); + +CREATE UNIQUE INDEX account_jwt_signer_target_kid_once + ON account_jwt_signer_promotion_operations (environment_id, target_kid); + +-- [jooq ignore start] +CREATE FUNCTION account_jwt_signer_desired_state_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +DECLARE + operation_environment VARCHAR(63); + operation_expected_version BIGINT; + operation_previous_generation BIGINT; + operation_previous_kid VARCHAR(128); + operation_published_generation BIGINT; + operation_published_kid VARCHAR(128); + operation_status VARCHAR(16); + operation_cluster VARCHAR(128); + operation_namespace VARCHAR(63); + operation_mode VARCHAR(64); + operation_target_generation BIGINT; + operation_target_kid VARCHAR(64); + operation_algorithm VARCHAR(16); + operation_cluster_uid UUID; + operation_namespace_uid UUID; + operation_trust_digest VARCHAR(64); + operation_trust_revision VARCHAR(128); +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'Account JWT signer desired state cannot be deleted' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + IF NEW.environment_id IS DISTINCT FROM OLD.environment_id + OR NEW.cluster_id IS DISTINCT FROM OLD.cluster_id + OR NEW.kubernetes_namespace IS DISTINCT FROM OLD.kubernetes_namespace + OR NEW.custody_mode IS DISTINCT FROM OLD.custody_mode + OR NEW.private_secret_name IS DISTINCT FROM OLD.private_secret_name + OR NEW.public_jwks_config_map_name IS DISTINCT FROM OLD.public_jwks_config_map_name + OR NEW.durable_active_generation IS DISTINCT FROM OLD.durable_active_generation + OR NEW.durable_active_kid IS DISTINCT FROM OLD.durable_active_kid + OR NEW.published_active_generation IS DISTINCT FROM OLD.published_active_generation + OR NEW.published_active_kid IS DISTINCT FROM OLD.published_active_kid + OR NEW.created_at IS DISTINCT FROM OLD.created_at + OR NEW.record_version <> OLD.record_version + 1 THEN + RAISE EXCEPTION 'Account JWT signer desired state permits only a versioned owner transition' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + END IF; + + IF NEW.prepared_operation_id IS DISTINCT FROM OLD.prepared_operation_id THEN + RAISE EXCEPTION 'JWT signer promotion prerequisites are incomplete' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_prepared_operation_binding'; + END IF; + + IF OLD.generation_operation_id IS NOT NULL + OR NEW.generation_operation_id IS NULL + OR OLD.prepared_operation_id IS NOT NULL + OR NEW.prepared_operation_id IS NOT NULL THEN + RAISE EXCEPTION 'Account JWT signer generation operation is already fenced or not promotable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + + SELECT environment_id, cluster_id, kubernetes_namespace, custody_mode, + expected_record_version, expected_previous_generation, expected_previous_kid, + expected_published_generation, expected_published_kid, + target_generation, target_kid, target_algorithm, + expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision + INTO operation_environment, operation_cluster, operation_namespace, operation_mode, + operation_expected_version, operation_previous_generation, operation_previous_kid, + operation_published_generation, operation_published_kid, + operation_target_generation, operation_target_kid, operation_algorithm, + operation_cluster_uid, operation_namespace_uid, + operation_trust_digest, operation_trust_revision + FROM account_jwt_signer_generation_operations + WHERE operation_id = NEW.generation_operation_id; + IF operation_environment IS DISTINCT FROM NEW.environment_id + OR operation_cluster IS DISTINCT FROM NEW.cluster_id + OR operation_namespace IS DISTINCT FROM NEW.kubernetes_namespace + OR operation_mode IS DISTINCT FROM NEW.custody_mode + OR operation_expected_version IS DISTINCT FROM OLD.record_version + OR operation_previous_generation IS DISTINCT FROM OLD.durable_active_generation + OR operation_previous_kid IS DISTINCT FROM OLD.durable_active_kid + OR operation_published_generation IS DISTINCT FROM OLD.published_active_generation + OR operation_published_kid IS DISTINCT FROM OLD.published_active_kid + OR operation_algorithm IS DISTINCT FROM 'RS256' + OR operation_cluster_uid IS NULL OR operation_namespace_uid IS NULL + OR operation_trust_digest IS NULL OR operation_trust_revision IS NULL THEN + RAISE EXCEPTION 'Account JWT signer state must point to its exact owner-selected generation operation' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_binding'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_jwt_signer_desired_state_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer desired state cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_desired_state_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_operation_guard() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer operation history is immutable and PREPARED-only' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_operation_no_truncate() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer operation history cannot be truncated' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE FUNCTION account_jwt_signer_generation_operation_immutable() +RETURNS TRIGGER +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'Account JWT signer generation operation is immutable' + USING ERRCODE = '23514', CONSTRAINT = 'account_jwt_signer_generation_operation_immutable'; + RETURN NULL; +END; +$$; + +CREATE TRIGGER account_jwt_signer_desired_state_guard + BEFORE UPDATE OR DELETE ON account_jwt_signer_desired_states + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_desired_state_guard(); + +CREATE TRIGGER account_jwt_signer_desired_state_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_desired_states + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_desired_state_no_truncate(); + +CREATE TRIGGER account_jwt_signer_operation_guard + BEFORE UPDATE OR DELETE ON account_jwt_signer_promotion_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_operation_guard(); + +CREATE TRIGGER account_jwt_signer_operation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_promotion_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_operation_no_truncate(); + +CREATE TRIGGER account_jwt_signer_generation_operation_immutable + BEFORE UPDATE OR DELETE ON account_jwt_signer_generation_operations + FOR EACH ROW EXECUTE FUNCTION account_jwt_signer_generation_operation_immutable(); + +CREATE TRIGGER account_jwt_signer_generation_operation_no_truncate + BEFORE TRUNCATE ON account_jwt_signer_generation_operations + FOR EACH STATEMENT EXECUTE FUNCTION account_jwt_signer_generation_operation_immutable(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java new file mode 100644 index 0000000000..fbff0cf2be --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java @@ -0,0 +1,469 @@ +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.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +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.EnrollmentIdentity; +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.common.json.Rfc8785CanonicalJson; +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.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtJwksPublicationPersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "jwt_jwks_publication_proof"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private static final Binding PROD_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_DIGEST = "a".repeat(64); + private static final String TRUST_REVISION = "trust-r1"; + private static final String API_DIGEST = "b".repeat(64); + private static final String API_REVISION = "api-r1"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final Set schemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @AfterEach + void dropRunOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.startsWith(SCHEMA_PREFIX + "_") || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean an unowned PostgreSQL schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + schemas.clear(); + } + + @Test + void exactIntentReadbackAndMountedObservationPersistAndRejectEveryMutationPath() + throws Exception { + TestContext context = newTestContext(); + AccountJwtSignerDesiredStateRepository desiredRepository = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + AccountJwtJwksPublicationRepository publicationRepository = + new AccountJwtJwksPublicationRepository(context.dsl(), desiredRepository); + String expectedSnapshotDigest = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", "{\"keys\":[]}", "unrelated.txt", "preserve")); + EnrollmentIdentity enrollment = + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + TRUST_DIGEST, + TRUST_REVISION, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest); + inTransaction(context, () -> desiredRepository.initialize(PROD_BINDING, enrollment)); + + GenerationRequest operation = + inTransaction( + context, () -> desiredRepository.ensureCurrentGenerationRequest(PROD_BINDING, trust())); + GenerationRequest observed = + inTransaction( + context, + () -> + desiredRepository.recordSecretObservation( + PROD_BINDING, + trust(), + operation.operationId(), + operation.operationDigest(), + SECRET_UID, + "12")); + PublicJwk jwk = publicJwk(operation.targetKid()); + GenerationResult result = + inTransaction( + context, + () -> + desiredRepository.recordGenerationResult( + PROD_BINDING, + trust(), + operation.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + jwk.json())); + + String retainedJwk = publicJwk("retained-key").jsonWithoutKeyOps(); + String desiredJwks = jwks(retainedJwk, result.publicJwkJson()); + String marker = marker(result, operation); + String invalidBindingMarker = + marker.replaceFirst("\"binding\":\\{[^{}]*}", "\"binding\":\"binding\""); + GenerationRequest currentRequest = + inTransaction( + context, () -> desiredRepository.readCurrentGenerationRequest(PROD_BINDING, trust())); + String invalidMarker = marker.replace("\"pending\":{", "\"pending\":{\"unexpected\":true,"); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + desiredJwks, + invalidMarker))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + desiredJwks, + invalidBindingMarker))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + jwks( + mutateJwk(retainedJwk, "key_ops", List.of("sign")), + result.publicJwkJson()), + marker))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + jwks( + mutateJwk(retainedJwk, "unexpected", "field"), + result.publicJwkJson()), + marker))) + .isInstanceOf(DataAccessException.class); + var intent = + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + desiredJwks, + marker)); + assertThat(intent.operationId()).isEqualTo(result.operationId()); + assertThat(intent.generationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(intent.publicKeyFingerprint()).isEqualTo(result.publicKeyFingerprint()); + assertThat(intent.jwksJson()).doesNotContain("privateKey", "\"d\""); + + var receipt = + inTransaction( + context, + () -> + publicationRepository.recordPublicationReceipt( + PROD_BINDING, + trust(), + result.operationId(), + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "42", + desiredJwks, + marker)); + assertThat(receipt.intentDigest()).isEqualTo(intent.intentDigest()); + assertThat(receipt.expectedResourceVersion()).isEqualTo("41"); + assertThat(receipt.observedResourceVersion()).isEqualTo("42"); + + var mountObservation = + inTransaction( + context, + () -> + publicationRepository.recordMountedCorrespondence( + PROD_BINDING, + trust(), + result.operationId(), + sha256(marker.getBytes(StandardCharsets.UTF_8)), + AccountJwtJwksPublicationRepository.publicDataDigest(desiredJwks, marker), + result.publicKeyFingerprint())); + assertThat(mountObservation.publicationReceiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(mountObservation.publicKeyFingerprint()).isEqualTo(result.publicKeyFingerprint()); + + assertThat(count(context, "account_jwt_jwks_prepublication_intents")).isEqualTo(1L); + assertThat(count(context, "account_jwt_jwks_publication_receipts")).isEqualTo(1L); + assertThat(count(context, "account_jwt_jwks_mount_observations")).isEqualTo(1L); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_jwks_prepublication_intents " + + "SET public_data_digest = ? WHERE operation_id = ?", + "f".repeat(64), + result.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "DELETE FROM account_jwt_jwks_publication_receipts " + + "WHERE operation_id = ?", + result.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> context.dsl().execute("TRUNCATE account_jwt_jwks_mount_observations"))) + .isInstanceOf(DataAccessException.class); + + assertThat(count(context, "account_jwt_jwks_prepublication_intents")).isEqualTo(1L); + assertThat(count(context, "account_jwt_jwks_publication_receipts")).isEqualTo(1L); + assertThat(count(context, "account_jwt_jwks_mount_observations")).isEqualTo(1L); + assertThat( + inTransaction( + context, () -> publicationRepository.readCurrentPublication(PROD_BINDING, trust()))) + .isPresent() + .get() + .satisfies( + evidence -> { + assertThat(evidence.intent()).isEqualTo(intent); + assertThat(evidence.receipt()).contains(receipt); + assertThat(evidence.mountedCorrespondence()).contains(mountObservation); + }); + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + var dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + return new TestContext(new TransactionTemplate(transactionManager), dsl); + } + + private static T inTransaction( + TestContext context, java.util.function.Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static long count(TestContext context, String table) { + return java.util.Objects.requireNonNull( + context.dsl().resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class), + "COUNT query must return a scalar row"); + } + + private static TrustFence trust() { + return new TrustFence(CLUSTER_UID, NAMESPACE_UID, TRUST_DIGEST, TRUST_REVISION); + } + + private static String marker(GenerationResult result, GenerationRequest request) + throws Exception { + 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", API_DIGEST); + binding.put("apiConfigRevision", API_REVISION); + marker.put("binding", binding); + marker.put("publicConfigMap", Map.of("name", "jwt-jwks")); + marker.put("expectedDurableActive", Map.of("present", false)); + marker.put("expectedPublishedActive", Map.of("present", false)); + marker.put( + "pending", + Map.of( + "generation", + result.targetGeneration(), + "kid", + result.targetKid(), + "algorithm", + result.targetAlgorithm(), + "publicKeyFingerprint", + result.publicKeyFingerprint())); + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(marker)), + StandardCharsets.UTF_8); + } + + private static PublicJwk publicJwk(String kid) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey key = (RSAPublicKey) generator.generateKeyPair().getPublic(); + 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 = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(jwk)), + StandardCharsets.UTF_8); + Map withoutKeyOps = new LinkedHashMap<>(jwk); + withoutKeyOps.remove("key_ops"); + String jsonWithoutKeyOps = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(withoutKeyOps)), + StandardCharsets.UTF_8); + String fingerprint = + sha256( + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(Map.of("e", exponent, "kty", "RSA", "n", modulus)))); + return new PublicJwk(json, jsonWithoutKeyOps, fingerprint); + } + + private static String jwks(String retainedJwk, String targetJwk) { + return "{\"keys\":[" + retainedJwk + "," + targetJwk + "]}"; + } + + private static String mutateJwk(String jwkJson, String fieldName, Object value) { + try { + @SuppressWarnings("unchecked") + Map jwk = JSON.readValue(jwkJson, Map.class); + jwk.put(fieldName, value); + return new String( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(jwk)), + StandardCharsets.UTF_8); + } catch (Exception ex) { + throw new IllegalStateException("Test JWK could not be updated", ex); + } + } + + private static String encodeUnsigned(java.math.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 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); + } + } + + private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + + private record TestContext(TransactionTemplate transaction, DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java new file mode 100644 index 0000000000..cab856a65e --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java @@ -0,0 +1,500 @@ +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.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +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.EnrollmentIdentity; +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.common.json.Rfc8785CanonicalJson; +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.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Physical PostgreSQL proof for Account-owned signer desired-state and materialization receipts. + */ +class AccountJwtSignerStoragePostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "jwt_signer_owner_storage"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + 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 TRUST_DIGEST = "b".repeat(64); + private static final String TRUST_REVISION = "trust-revision-1"; + private static final String API_DIGEST = "d".repeat(64); + private static final String API_REVISION = "api-revision-1"; + private static final String CONFIG_MAP_UID = "44444444-4444-4444-8444-444444444444"; + private static final String INITIAL_CONFIG_MAP_SNAPSHOT_DIGEST = "e".repeat(64); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final Set schemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @AfterEach + void dropRunOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.startsWith(SCHEMA_PREFIX + "_") || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean an unowned PostgreSQL schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + schemas.clear(); + } + + @Test + void materializationReadbackIsDurableAndExactReplaysRejectChangedOrStaleEvidence() + throws Exception { + TestContext context = newTestContext(null); + AccountJwtSignerDesiredStateRepository desired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + TrustFence trust = trust(); + + var initialized = + inTransaction(context, () -> desired.initialize(BINDING, enrollmentIdentity())); + assertThat(initialized.recordVersion()).isEqualTo(1L); + assertThat(initialized.durableActive()).isEmpty(); + assertThat(initialized.publishedActive()).isEmpty(); + assertThat(initialized.generationOperationId()).isEmpty(); + assertThat(initialized.preparedOperationId()).isEmpty(); + + GenerationRequest request = + inTransaction(context, () -> desired.ensureCurrentGenerationRequest(BINDING, trust)); + assertThat(request.targetGeneration()).isEqualTo("1"); + assertThat(request.targetKid()).startsWith("jwt-1-"); + assertThat(request.publicJwkJson()).isEmpty(); + assertThat(request.publicKeyFingerprint()).isEmpty(); + + String observedResourceVersion = "r".repeat(256); + GenerationRequest observation = + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + trust, + request.operationId(), + request.operationDigest(), + SECRET_UID, + observedResourceVersion)); + GenerationRequest observationReplay = + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + trust, + request.operationId(), + request.operationDigest(), + SECRET_UID, + observedResourceVersion)); + assertThat(observationReplay).isEqualTo(observation); + assertThat(observation.phase()) + .isEqualTo(AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATE_PENDING); + assertThat(observation.generationRequestDigest()).hasSize(64); + assertThat(observation.expectedSecretResourceVersion()).isEqualTo(observedResourceVersion); + assertThat(observation.secretUid()).isEqualTo(SECRET_UID); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + trust, + request.operationId(), + request.operationDigest(), + SECRET_UID, + "13"))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); + + PublicJwk key = publicJwk(request.targetKid()); + GenerationResult result = + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + trust, + request.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + observedResourceVersion, + "13", + key.json())); + GenerationResult resultReplay = + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + trust, + request.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + observedResourceVersion, + "13", + key.json())); + assertThat(resultReplay).isEqualTo(result); + assertThat(result.publicKeyFingerprint()).isEqualTo(key.fingerprint()); + assertThat(result.publicJwkJson()).doesNotContain("\"d\""); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + trust, + request.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + observedResourceVersion, + "14", + key.json()))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); + + TrustFence staleTrust = + new TrustFence(CLUSTER_UID, NAMESPACE_UID, "a".repeat(64), TRUST_REVISION); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + staleTrust, + request.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + observedResourceVersion, + "13", + key.json()))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.BindingMismatchException.class); + + AccountJwtSignerDesiredStateRepository restartedRepository = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + var persistedState = inTransaction(context, () -> restartedRepository.read(BINDING)); + GenerationRequest persistedRequest = + inTransaction( + context, () -> restartedRepository.readCurrentGenerationRequest(BINDING, trust)); + GenerationResult persistedResult = + inTransaction( + context, () -> restartedRepository.readCurrentGenerationResult(BINDING, trust)); + + assertThat(persistedState.recordVersion()).isEqualTo(2L); + assertThat(persistedState.durableActive()).isEmpty(); + assertThat(persistedState.publishedActive()).isEmpty(); + assertThat(persistedState.preparedOperationId()).isEmpty(); + assertThat(persistedState.generationOperationId()).contains(request.operationId()); + assertThat(persistedRequest.phase()) + .isEqualTo(AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED); + assertThat(persistedRequest.generationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(persistedRequest.publicJwkJson()).isEqualTo(key.json()); + assertThat(persistedResult).isEqualTo(result); + + assertThat(count(context, "account_jwt_signer_desired_states")).isEqualTo(1L); + assertThat(count(context, "account_jwt_signer_generation_operations")).isEqualTo(1L); + assertThat(count(context, "account_jwt_signer_secret_observations")).isEqualTo(1L); + assertThat(count(context, "account_jwt_signer_generation_results")).isEqualTo(1L); + } + + @Test + void unpreparedGenerationAbortIsAnImmutableOwnerCasAndExactReplayAcrossRepositoryRestart() + throws Exception { + TestContext context = newTestContext(null); + AccountJwtSignerDesiredStateRepository desired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + TrustFence trust = trust(); + inTransaction(context, () -> desired.initialize(BINDING, enrollmentIdentity())); + GenerationRequest request = + inTransaction(context, () -> desired.ensureCurrentGenerationRequest(BINDING, trust)); + GenerationRequest observation = + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + trust, + request.operationId(), + request.operationDigest(), + SECRET_UID, + "12")); + PublicJwk key = publicJwk(request.targetKid()); + GenerationResult result = + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + trust, + request.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + "12", + "13", + key.json())); + + GenerationResult changedResult = + new GenerationResult( + result.operationId(), + result.binding(), + result.operationDigest(), + result.generationRequestDigest(), + result.desiredStateVersion(), + result.trustFence(), + result.privateSecretName(), + result.secretUid(), + result.expectedPriorResourceVersion(), + result.observedResourceVersion(), + result.targetGeneration(), + result.targetKid(), + result.targetAlgorithm(), + result.publicKeyFingerprint(), + result.publicJwkJson(), + "f".repeat(64)); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> desired.abortUnpreparedGeneration(BINDING, trust, changedResult))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_signer_desired_states " + + "SET record_version = record_version + 1, " + + "generation_operation_id = NULL " + + "WHERE environment_id = ?", + BINDING.environmentId()))) + .isInstanceOf(DataAccessException.class); + + var receipt = + inTransaction(context, () -> desired.abortUnpreparedGeneration(BINDING, trust, result)); + assertThat(receipt.operationId()).isEqualTo(request.operationId()); + assertThat(receipt.operationDigest()).isEqualTo(request.operationDigest()); + assertThat(receipt.generationRequestDigest()).isEqualTo(result.generationRequestDigest()); + assertThat(receipt.generationReceiptDigest()).isEqualTo(result.receiptDigest()); + assertThat(receipt.expectedStateVersion()).isEqualTo(2L); + assertThat(receipt.resultingStateVersion()).isEqualTo(3L); + assertThat(receipt.durableActive()).isEmpty(); + assertThat(receipt.publishedActive()).isEmpty(); + + AccountJwtSignerDesiredStateRepository restarted = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + assertThat( + inTransaction( + context, () -> restarted.abortUnpreparedGeneration(BINDING, trust, result))) + .isEqualTo(receipt); + var state = inTransaction(context, () -> restarted.read(BINDING)); + assertThat(state.recordVersion()).isEqualTo(3L); + assertThat(state.generationOperationId()).isEmpty(); + assertThat(state.preparedOperationId()).isEmpty(); + assertThat(state.durableActive()).isEmpty(); + assertThat(state.publishedActive()).isEmpty(); + assertThat(count(context, "account_jwt_signer_generation_abort_receipts")).isEqualTo(1L); + + GenerationRequest next = + inTransaction(context, () -> restarted.ensureCurrentGenerationRequest(BINDING, trust)); + assertThat(next.targetGeneration()).isEqualTo("2"); + assertThat(next.operationId()).isNotEqualTo(request.operationId()); + assertThat(next.expectedActive()).isEmpty(); + assertThat(next.expectedPublishedActive()).isEmpty(); + } + + @Test + void parentV98UpgradePreservesRetainedAccountWithoutInventingSignerEnrollment() { + TestContext context = newTestContext("98"); + String suffix = UUID.randomUUID().toString().replace("-", ""); + Long accountId = + new JdbcTemplate(context.dataSource()) + .queryForObject( + "INSERT INTO accounts (username, email, password_hash, role) " + + "VALUES (?, ?, ?, 'player') RETURNING id", + Long.class, + "signer-retained-" + suffix, + "signer-retained-" + suffix + "@example.test", + "retained-test-password"); + UUID accountUuid = + new JdbcTemplate(context.dataSource()) + .queryForObject( + "SELECT account_uuid FROM accounts WHERE id = ?", UUID.class, accountId); + + migrateLatest(context); + + assertThat( + new JdbcTemplate(context.dataSource()) + .queryForObject( + "SELECT account_uuid FROM accounts WHERE id = ?", UUID.class, accountId)) + .isEqualTo(accountUuid); + assertThat( + new JdbcTemplate(context.dataSource()) + .queryForObject( + "SELECT count(*) FROM account_jwt_signer_desired_states", Long.class)) + .isZero(); + AccountJwtSignerDesiredStateRepository desired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + assertThat(inTransaction(context, () -> desired.readEnrollmentState(BINDING))).isEmpty(); + } + + private TestContext newTestContext(String targetVersion) { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + var dataSource = POSTGRES.dataSource(schema); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + configuration.target(targetVersion); + } + configuration.load().migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext(schema, dataSource, transaction, dsl); + } + + private void migrateLatest(TestContext context) { + Flyway.configure() + .dataSource(context.dataSource()) + .schemas(context.schema()) + .defaultSchema(context.schema()) + .placeholders(Map.of("serviceSchema", context.schema())) + .locations("classpath:db/migration") + .load() + .migrate(); + } + + private static T inTransaction(TestContext context, Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static long count(TestContext context, String table) { + return java.util.Objects.requireNonNull( + context.dsl().resultQuery("SELECT count(*) FROM " + table).fetchOne(0, Long.class), + "Count query returned no row."); + } + + private static TrustFence trust() { + return new TrustFence(CLUSTER_UID, NAMESPACE_UID, TRUST_DIGEST, TRUST_REVISION); + } + + private static EnrollmentIdentity enrollmentIdentity() { + return new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + TRUST_DIGEST, + TRUST_REVISION, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "12", + INITIAL_CONFIG_MAP_SNAPSHOT_DIGEST); + } + + private static PublicJwk publicJwk(String kid) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey key = (RSAPublicKey) generator.generateKeyPair().getPublic(); + 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); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest( + Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString( + Map.of("e", exponent, "kty", "RSA", "n", modulus))))); + return new PublicJwk(json, 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 java.util.Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + private record PublicJwk(String json, String fingerprint) {} + + private record TestContext( + String schema, + javax.sql.DataSource dataSource, + TransactionTemplate transaction, + DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java new file mode 100644 index 0000000000..274fdc243c --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java @@ -0,0 +1,258 @@ +package integration.net.firedevops.firemud.accountservice.repository; + +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 java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +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.AccountJwtValidatorInventoryRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +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.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; + +/** Persistence-component proof only; fixture bytes are not evidence of a live Kubernetes read. */ +class AccountJwtValidatorInventoryPersistenceIntegrationTest { + private static final String SCHEMA_PREFIX = "jwt_inv_snapshot_"; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + 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 final Set schemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @AfterEach + void dropRunOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.startsWith(SCHEMA_PREFIX) || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean an unowned PostgreSQL schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + schemas.clear(); + } + + @Test + void exactDigestRetryReadsBackImmutableCanonicalBytesAndRejectsMutation() throws Exception { + TestContext context = newTestContext(); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(context.dsl()); + InventorySnapshot candidate = snapshot(); + + var first = + inTransaction(context, () -> repository.persistOrReadback(candidate, BINDING, trust())); + var retry = + inTransaction(context, () -> repository.persistOrReadback(candidate, BINDING, trust())); + + assertThat(retry).isEqualTo(first); + assertThat( + context + .dsl() + .resultQuery("SELECT COUNT(*) FROM account_jwt_validator_inventory_snapshots") + .fetchOne(0, Long.class)) + .isEqualTo(1L); + assertThat(retry.canonicalBytes()).isEqualTo(candidate.canonicalBytes()); + assertThat(new String(retry.canonicalBytes(), StandardCharsets.UTF_8)) + .doesNotContain("privateKey"); + assertThatThrownBy( + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_validator_inventory_snapshots " + + "SET canonical_snapshot = ? WHERE snapshot_digest = ?", + "{}".getBytes(StandardCharsets.UTF_8), + retry.digest())) + .isInstanceOf(DataAccessException.class); + + long plansBeforeTruncate = count(context, "account_jwt_readiness_probe_plans"); + assertThatThrownBy( + () -> + context + .dsl() + .execute("TRUNCATE TABLE account_jwt_validator_inventory_snapshots CASCADE")) + .isInstanceOf(DataAccessException.class); + assertThat(count(context, "account_jwt_validator_inventory_snapshots")).isEqualTo(1L); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(plansBeforeTruncate); + } + + @Test + void differentBytesCannotReuseAStoredDigestAndWrongOwnerIdentityIsDenied() throws Exception { + TestContext context = newTestContext(); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(context.dsl()); + InventorySnapshot candidate = snapshot(); + inTransaction(context, () -> repository.persistOrReadback(candidate, BINDING, trust())); + Instant observedAt = candidate.observedAt(); + String environmentId = candidate.environmentId(); + String namespace = candidate.namespace(); + String apiBindingRevision = candidate.apiBindingRevision(); + String apiBindingDigest = candidate.apiBindingDigest(); + String inventoryBindingRevision = candidate.inventoryBindingRevision(); + String inventoryBindingDigest = candidate.inventoryBindingDigest(); + String digest = candidate.digest(); + byte[] canonicalBytes = candidate.canonicalBytes(); + + InventorySnapshot wrongIdentity = mock(InventorySnapshot.class); + when(wrongIdentity.observedAt()).thenReturn(observedAt); + when(wrongIdentity.environmentId()).thenReturn(environmentId); + when(wrongIdentity.clusterId()).thenReturn("other-cluster"); + when(wrongIdentity.clusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(wrongIdentity.namespace()).thenReturn(namespace); + when(wrongIdentity.namespaceUid()).thenReturn(NAMESPACE_UID); + when(wrongIdentity.apiBindingRevision()).thenReturn(apiBindingRevision); + when(wrongIdentity.apiBindingDigest()).thenReturn(apiBindingDigest); + when(wrongIdentity.inventoryBindingRevision()).thenReturn(inventoryBindingRevision); + when(wrongIdentity.inventoryBindingDigest()).thenReturn(inventoryBindingDigest); + when(wrongIdentity.digest()).thenReturn(digest); + when(wrongIdentity.canonicalBytes()).thenReturn(canonicalBytes); + + assertThatThrownBy( + () -> + inTransaction( + context, () -> repository.persistOrReadback(wrongIdentity, BINDING, trust()))) + .isInstanceOf( + AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) + .hasNoCause(); + + InventorySnapshot conflictingApiBindingRevision = mock(InventorySnapshot.class); + when(conflictingApiBindingRevision.observedAt()).thenReturn(observedAt); + when(conflictingApiBindingRevision.environmentId()).thenReturn(environmentId); + when(conflictingApiBindingRevision.clusterId()).thenReturn(BINDING.clusterId()); + when(conflictingApiBindingRevision.clusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(conflictingApiBindingRevision.namespace()).thenReturn(namespace); + when(conflictingApiBindingRevision.namespaceUid()).thenReturn(NAMESPACE_UID); + when(conflictingApiBindingRevision.apiBindingRevision()).thenReturn("api-r2"); + when(conflictingApiBindingRevision.apiBindingDigest()).thenReturn(apiBindingDigest); + when(conflictingApiBindingRevision.inventoryBindingRevision()) + .thenReturn(inventoryBindingRevision); + when(conflictingApiBindingRevision.inventoryBindingDigest()).thenReturn(inventoryBindingDigest); + when(conflictingApiBindingRevision.digest()).thenReturn(digest); + when(conflictingApiBindingRevision.canonicalBytes()).thenReturn(canonicalBytes); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + repository.persistOrReadback( + conflictingApiBindingRevision, BINDING, trust()))) + .isInstanceOf( + AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) + .hasNoCause(); + + assertThat(count(context, "account_jwt_validator_inventory_snapshots")).isEqualTo(1L); + var unchanged = + context + .dsl() + .fetchOne( + "SELECT api_binding_revision, canonical_snapshot " + + "FROM account_jwt_validator_inventory_snapshots WHERE snapshot_digest = ?", + digest); + assertThat(unchanged).isNotNull(); + assertThat(unchanged.get("api_binding_revision", String.class)).isEqualTo(apiBindingRevision); + assertThat(unchanged.get("canonical_snapshot", byte[].class)).isEqualTo(canonicalBytes); + } + + private static InventorySnapshot snapshot() throws Exception { + byte[] bytes = + ("{\"domain\":\"firemud-account-validator-inventory/v1\"," + + "\"environmentId\":\"prod\",\"clusterId\":\"prod-cluster-1\"," + + "\"clusterIncarnationUid\":\"" + + CLUSTER_UID + + "\"," + + "\"namespace\":\"firemud-prod\",\"namespaceUid\":\"" + + NAMESPACE_UID + + "\"}") + .getBytes(StandardCharsets.UTF_8); + InventorySnapshot snapshot = mock(InventorySnapshot.class); + when(snapshot.observedAt()).thenReturn(Instant.parse("2026-10-05T00:00:00Z")); + when(snapshot.environmentId()).thenReturn("prod"); + when(snapshot.clusterId()).thenReturn("prod-cluster-1"); + when(snapshot.clusterIncarnationUid()).thenReturn(CLUSTER_UID); + when(snapshot.namespace()).thenReturn("firemud-prod"); + when(snapshot.namespaceUid()).thenReturn(NAMESPACE_UID); + when(snapshot.apiBindingRevision()).thenReturn("api-r1"); + when(snapshot.apiBindingDigest()).thenReturn("a".repeat(64)); + when(snapshot.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(snapshot.inventoryBindingDigest()).thenReturn("b".repeat(64)); + when(snapshot.canonicalBytes()).thenReturn(bytes); + when(snapshot.digest()).thenReturn(sha256(bytes)); + return snapshot; + } + + private TestContext newTestContext() { + String schema = SCHEMA_PREFIX + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + var dataSource = POSTGRES.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration") + .load() + .migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext( + new TransactionTemplate(new DataSourceTransactionManager(dataSource)), dsl); + } + + private static T inTransaction(TestContext context, java.util.function.Supplier action) { + return context.transaction().execute(status -> action.get()); + } + + private static long count(TestContext context, String table) { + return java.util.Objects.requireNonNull( + context.dsl().resultQuery("SELECT COUNT(*) FROM " + table).fetchOne(0, Long.class), + "COUNT query must return a scalar row"); + } + + private static TrustFence trust() { + return new TrustFence(CLUSTER_UID, NAMESPACE_UID, "c".repeat(64), "trust-r1"); + } + + private static String sha256(byte[] bytes) throws Exception { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } + + private record TestContext(TransactionTemplate transaction, DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java new file mode 100644 index 0000000000..0b4a788a10 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java @@ -0,0 +1,2727 @@ +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 integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +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.Duration; +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.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.PeerIdentity; +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.ExpectedPod; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +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.PrivatePromotionObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PublicKeyIdentity; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.repository.AccountJwtValidatorInventoryRepository; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessProbeOwnerSelector.LocalIdentity; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance; +import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.ProbeExpectation; +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 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.awaitility.Awaitility; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.postgresql.util.PSQLException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import tools.jackson.databind.json.JsonMapper; + +/** + * Physical PostgreSQL proof for Account-owned V2 readiness inventory, signing-state, per-Pod + * receipt storage, and dispatched promotion recovery after plan expiry. The inventory, + * authenticated-acceptance, and resource readback inputs are synthetic owner values, as in the + * retained donor proof; this does not establish live Kubernetes currentness, receiver + * authentication, readiness activation, or signer activation. The local ephemeral canary key is + * only a real signing precondition for the storage transition. + */ +class AccountJwtReadinessStoragePostgresIntegrationTest { + private static final String SCHEMA_PREFIX = "jwt_readiness_owner_storage"; + private static final int BULK_READINESS_PLAN_HEADROOM_SECONDS = 300; + private static final int DISPATCHED_RECOVERY_PLAN_HEADROOM_SECONDS = 70; + private static final int DISPATCHED_RECOVERY_EXPIRY_WAIT_SECONDS = + DISPATCHED_RECOVERY_PLAN_HEADROOM_SECONDS + 30; + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + 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 TRUST_REVISION = "trust-r1"; + private static final String TRUST_DIGEST = "b".repeat(64); + private static final String API_DIGEST = "c".repeat(64); + private static final String API_REVISION = "api-r1"; + private static final String CONFIG_MAP_UID = "44444444-4444-4444-8444-444444444444"; + private static final String INITIAL_CONFIG_MAP_RESOURCE_VERSION = "41"; + private static final Map INITIAL_CONFIG_MAP_DATA = + Map.of("jwks.json", "{\"keys\":[]}", "unrelated.txt", "preserve"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir Path tempDirectory; + + private final Set schemas = ConcurrentHashMap.newKeySet(); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @AfterEach + void dropRunOwnedSchemas() { + JdbcTemplate jdbc = new JdbcTemplate(POSTGRES.dataSource()); + for (String schema : schemas) { + if (!schema.startsWith(SCHEMA_PREFIX + "_") || !schema.matches("[a-z][a-z0-9_]{0,62}")) { + throw new IllegalStateException("Refusing to clean an unowned PostgreSQL schema"); + } + jdbc.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + schemas.clear(); + } + + @Test + void rejectsMissingAndNullReadinessInventoryFieldsWithIndependentRawSqlAttempts() + throws Exception { + TestContext context = newTestContext(null); + OwnerState owner = createOwnerState(context); + ObservationContext observationContext = + inTransaction( + context, + () -> owner.readiness().readCurrentInventoryObservationContext(BINDING, owner.trust())); + long databaseNow = databaseNow(context); + long plannedAtEpochSecond = + databaseNow + - AccountJwtReadinessProbeRepository.MAX_VALIDATOR_CACHE_AGE_SECONDS + - AccountJwtReadinessProbeRepository.PROBE_LIFETIME_SECONDS + + BULK_READINESS_PLAN_HEADROOM_SECONDS; + Instant plannedAt = Instant.ofEpochSecond(plannedAtEpochSecond); + InventorySnapshot inventory = completeInventorySnapshot(plannedAt, observationContext); + inTransaction( + context, () -> owner.inventory().persistOrReadback(inventory, BINDING, owner.trust())); + + ReadinessProbePlan planTemplate = + context + .transaction() + .execute( + status -> { + ReadinessProbePlan candidate = + owner.readiness().planCurrent(BINDING, owner.trust(), plannedAt, inventory); + status.setRollbackOnly(); + return candidate; + }); + assertThat(planTemplate).isNotNull(); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); + + assertReadinessInventoryClosureGuardRejectsMatrixMismatch( + context, + planTemplate, + readinessMatrixWithExtraValidator(planTemplate.applicabilityMatrixJson()), + "validator ID set differs from the canonical inventory snapshot"); + assertReadinessInventoryClosureGuardRejectsMatrixMismatch( + context, + planTemplate, + readinessMatrixWithDifferentApplicableProfiles(planTemplate.applicabilityMatrixJson()), + "matching validator IDs have different applicable profile membership"); + + ReadinessProbePlan legacyPlanTemplate = + context + .transaction() + .execute( + status -> { + ReadinessProbePlan candidate = + owner.readiness().planCurrent(BINDING, owner.trust(), plannedAt); + status.setRollbackOnly(); + return candidate; + }); + assertThat(legacyPlanTemplate).isNotNull(); + assertThat(legacyPlanTemplate.planVersion()).isEqualTo(1); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); + + assertReadinessPlanInventoryGuardRejects( + context, + legacyPlanTemplate, + List.of("inventoryStatus", "schemaVersion", "validatorId", "applicableProfiles")); + assertReadinessPlanInventoryGuardRejects( + context, + planTemplate, + List.of( + "inventoryStatus", + "schemaVersion", + "validatorId", + "productionProfiles", + "applicableProfiles")); + + ReadinessProbePlan canonicalPlan = + inTransaction( + context, + () -> owner.readiness().planCurrent(BINDING, owner.trust(), plannedAt, inventory)); + assertThat(canonicalPlan.validatorInventoryComplete()).isTrue(); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(1L); + assertThat(count(context, "account_jwt_readiness_probe_entries")).isEqualTo(8L); + assertThat(count(context, "account_jwt_readiness_validator_pods")).isEqualTo(12L); + } + + @Test + void recoversDispatchedReceiptBoundPromotionAfterReadinessPlanExpiry() throws Exception { + TestContext context = newTestContext(null); + OwnerState owner = createOwnerState(context); + ObservationContext observationContext = + inTransaction( + context, + () -> owner.readiness().readCurrentInventoryObservationContext(BINDING, owner.trust())); + long databaseNow = databaseNow(context); + long plannedAtEpochSecond = + databaseNow + - AccountJwtReadinessProbeRepository.MAX_VALIDATOR_CACHE_AGE_SECONDS + - AccountJwtReadinessProbeRepository.PROBE_LIFETIME_SECONDS + + DISPATCHED_RECOVERY_PLAN_HEADROOM_SECONDS; + Instant plannedAt = Instant.ofEpochSecond(plannedAtEpochSecond); + InventorySnapshot planningInventory = completeInventorySnapshot(plannedAt, observationContext); + ReadinessProbePlan plan = + inTransaction( + context, + () -> + owner + .readiness() + .planCurrent(BINDING, owner.trust(), plannedAt, planningInventory)); + assertThat(plan.notBeforeEpochSecond()).isLessThan(databaseNow); + assertThat(plan.expiresAtEpochSecond()) + .isEqualTo(databaseNow + DISPATCHED_RECOVERY_PLAN_HEADROOM_SECONDS); + assertThat(plan.entries()).hasSize(8); + + Instant refreshedInventoryObservedAt = Instant.ofEpochSecond(databaseClockNow(context)); + InventorySnapshot refreshedInventory = + completeInventorySnapshot(refreshedInventoryObservedAt, observationContext); + assertThat(refreshedInventory.observedAt()).isEqualTo(refreshedInventoryObservedAt); + assertThat(refreshedInventory.digest()).isEqualTo(planningInventory.digest()); + assertThat(refreshedInventory.canonicalBytes()).isEqualTo(planningInventory.canonicalBytes()); + + Path privateMount = Files.createDirectory(tempDirectory.resolve("expiry-private-mount")); + Path publicMount = Files.createDirectory(tempDirectory.resolve("expiry-public-mount")); + Files.writeString( + privateMount.resolve("pending.key"), + privateBundleJson(owner.request(), owner.result(), owner.keyPair())); + Files.writeString(publicMount.resolve("jwks.json"), owner.desiredJwks()); + var expectedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + owner.result().operationId().toString(), + owner.result().targetGeneration(), + owner.result().targetKid(), + owner.result().publicKeyFingerprint()); + assertThat( + completeRemainingProbes( + context, + owner, + plan, + refreshedInventory, + privateMount, + publicMount, + expectedIdentity)) + .isEqualTo(12L); + + var proof = + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentPromotionPrerequisites( + BINDING, owner.trust(), owner.result().operationId(), refreshedInventory) + .orElseThrow()); + assertThat(proof.verifiedProbes()).hasSize(plan.entries().size()); + byte[] exactPreimage = proof.readinessEvidencePreimage(); + assertThat(sha256(exactPreimage)).isEqualTo(proof.readinessEvidenceDigest()); + + var publicationEvidence = proof.publication(); + PromotionPreparation preparation = + new PromotionPreparation( + proof.generationResult().operationId(), + proof.generationResult(), + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + TRUST_DIGEST, + TRUST_REVISION, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + INITIAL_CONFIG_MAP_RESOURCE_VERSION, + AccountJwtJwksPublicationRepository.snapshotDigest(INITIAL_CONFIG_MAP_DATA)), + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + publicationEvidence.receipt().observedResourceVersion(), + publicationEvidence.intent().intentDigest(), + publicationEvidence.receipt().receiptDigest(), + publicationEvidence.mountedCorrespondence().observationDigest(), + proof.plan().planDigest(), + proof.readinessEvidenceDigest(), + publicationEvidence.intent().jwksJson()); + var prepared = + inTransaction( + context, + () -> + owner + .desired() + .prepareCurrentGeneration(BINDING, owner.trust(), preparation, proof)); + assertThat(prepared.status()).isEqualTo("PREPARED"); + assertThat(databaseClockNow(context)) + .as("the exact readiness proof reaches PREPARED before real plan expiry") + .isLessThan(plan.expiresAtEpochSecond()); + + AccountJwtSignerDesiredStateRepository restartedDesired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + AccountJwtJwksPublicationRepository restartedPublication = + new AccountJwtJwksPublicationRepository(context.dsl(), restartedDesired); + AccountJwtValidatorInventoryRepository restartedInventory = + new AccountJwtValidatorInventoryRepository(context.dsl()); + AccountJwtReadinessProbeRepository restartedReadiness = + new AccountJwtReadinessProbeRepository( + context.dsl(), restartedDesired, restartedPublication, restartedInventory); + var restartedProof = + inTransaction( + context, + () -> + restartedReadiness + .readPromotionProof( + BINDING, owner.trust(), owner.result().operationId(), refreshedInventory) + .orElseThrow()); + assertThat(restartedProof.readinessEvidencePreimage()).isEqualTo(exactPreimage); + assertThat(databaseClockNow(context)) + .as("the exact readiness proof remains before expiry through DISPATCHED") + .isLessThan(plan.expiresAtEpochSecond()); + var dispatchedEvidence = + inTransaction( + context, + () -> restartedDesired.readAndMarkPreparedPromotionDispatched(BINDING, owner.trust())); + assertThat(dispatchedEvidence.promotion().privatePromotionDispatched()).isTrue(); + assertThat(databaseClockNow(context)) + .as("the exact readiness proof reaches DISPATCHED before real plan expiry") + .isLessThan(plan.expiresAtEpochSecond()); + var dispatchedProof = + inTransaction( + context, + () -> + restartedReadiness + .readPromotionProof(BINDING, owner.trust(), owner.result().operationId()) + .orElseThrow()); + assertThat(dispatchedProof.readinessEvidencePreimage()).isEqualTo(exactPreimage); + OwnerState restartedOwner = + new OwnerState( + restartedDesired, + restartedPublication, + restartedInventory, + restartedReadiness, + owner.trust(), + owner.request(), + owner.result(), + owner.keyPair(), + owner.desiredJwks()); + assertThat( + inTransaction( + context, + () -> + restartedOwner + .desired() + .prepareCurrentGeneration( + BINDING, restartedOwner.trust(), preparation, dispatchedProof))) + .isEqualTo(prepared); + + var dispatchedPromotion = dispatchedEvidence.promotion(); + PrivatePromotionObservation privatePromotionObservation = + new PrivatePromotionObservation( + dispatchedPromotion.operationId(), + dispatchedPromotion.requestDigest(), + dispatchedPromotion.generationOperationId(), + dispatchedPromotion.generationOperationDigest(), + owner.result().secretUid(), + dispatchedPromotion.expectedPrivateResourceVersion(), + "14", + new PublicKeyIdentity( + dispatchedPromotion.targetGeneration(), + dispatchedPromotion.targetKid(), + dispatchedPromotion.targetPublicKeyFingerprint()), + Optional.empty(), + List.of("current")); + var privatePromotionReceipt = + inTransaction( + context, + () -> + restartedDesired.recordPrivatePromotionResult( + BINDING, owner.trust(), privatePromotionObservation)); + var activeJwksPromotionReceipt = + inTransaction( + context, + () -> + restartedDesired.recordActiveJwksPromotionResult( + BINDING, + owner.trust(), + new ActiveJwksPromotionObservation( + dispatchedPromotion.publicConfigMapUid(), + dispatchedPromotion.expectedPublicResourceVersion(), + "43", + dispatchedPromotion.expectedPublicJwksJson(), + dispatchedPromotion.expectedActiveMarkerJson()))); + var receiptBoundPrepared = + inTransaction( + context, + () -> restartedDesired.readPreparedGenerationForRecovery(BINDING, owner.trust())); + assertThat(receiptBoundPrepared.promotion().privatePromotionReceiptDigest()) + .contains(privatePromotionReceipt.receiptDigest()); + assertThat(receiptBoundPrepared.promotion().activeJwksReceiptDigest()) + .contains(activeJwksPromotionReceipt.receiptDigest()); + + awaitDatabaseClockAtOrAfter(context, plan.expiresAtEpochSecond()); + assertThat(databaseClockNow(context)).isGreaterThanOrEqualTo(plan.expiresAtEpochSecond()); + var expiredDispatchedProof = + inTransaction( + context, + () -> + restartedReadiness + .readPromotionProof(BINDING, owner.trust(), owner.result().operationId()) + .orElseThrow()); + assertThat(expiredDispatchedProof.plan().planDigest()).isEqualTo(plan.planDigest()); + assertThat(expiredDispatchedProof.plan().expiresAtEpochSecond()) + .isEqualTo(plan.expiresAtEpochSecond()); + assertThat(expiredDispatchedProof.readinessEvidencePreimage()).isEqualTo(exactPreimage); + assertThat(expiredDispatchedProof.readinessEvidenceDigest()) + .isEqualTo(proof.readinessEvidenceDigest()); + assertThat(expiredDispatchedProof.verifiedProbes()).hasSize(plan.entries().size()); + assertThat( + inTransaction( + context, + () -> + restartedOwner + .desired() + .prepareCurrentGeneration( + BINDING, restartedOwner.trust(), preparation, expiredDispatchedProof))) + .isEqualTo(prepared); + + var committed = + inTransaction( + context, + () -> + restartedDesired.commitPreparedPromotion( + BINDING, owner.trust(), prepared.operationId(), expiredDispatchedProof)); + assertThat(committed.promotion().status()).isEqualTo("COMMITTED"); + assertThat(committed.promotion().privatePromotionReceiptDigest()) + .contains(privatePromotionReceipt.receiptDigest()); + assertThat(committed.promotion().activeJwksReceiptDigest()) + .contains(activeJwksPromotionReceipt.receiptDigest()); + assertThat(committed.privateReceipt()).isEqualTo(privatePromotionReceipt); + assertThat(committed.publicReceipt()).isEqualTo(activeJwksPromotionReceipt); + } + + @Test + void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart() + throws Exception { + TestContext context = newTestContext(null); + OwnerState owner = createOwnerState(context); + ObservationContext observationContext = + inTransaction( + context, + () -> owner.readiness().readCurrentInventoryObservationContext(BINDING, owner.trust())); + assertThat(observationContext.purpose()) + .isEqualTo(ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES); + assertThat(observationContext.operationId()).isEqualTo(owner.result().operationId()); + assertThat(observationContext.operationDigest()).isEqualTo(owner.result().operationDigest()); + + long databaseNow = databaseNow(context); + long plannedAtEpochSecond = + databaseNow + - AccountJwtReadinessProbeRepository.MAX_VALIDATOR_CACHE_AGE_SECONDS + - AccountJwtReadinessProbeRepository.PROBE_LIFETIME_SECONDS + + BULK_READINESS_PLAN_HEADROOM_SECONDS; + Instant planTimestamp = Instant.ofEpochSecond(plannedAtEpochSecond); + InventorySnapshot planningInventory = + completeInventorySnapshot(planTimestamp, observationContext); + ReadinessProbePlan plan = + inTransaction( + context, + () -> + owner + .readiness() + .planCurrent(BINDING, owner.trust(), planTimestamp, planningInventory)); + assertThat(plan.planVersion()).isEqualTo(2); + assertThat(plan.expiresAtEpochSecond()) + .isEqualTo(databaseNow + BULK_READINESS_PLAN_HEADROOM_SECONDS); + assertThat(plan.validatorInventoryComplete()).isTrue(); + assertThat(plan.inventorySnapshotDigest()).contains(planningInventory.digest()); + assertThat(plan.trustFence()).isEqualTo(owner.trust()); + assertThat(plan.expectedFence().durableActive()).isEmpty(); + assertThat(plan.expectedFence().publishedActive()).isEmpty(); + assertThat(plan.entries()) + .hasSize(8) + .allSatisfy( + entry -> { + assertThat(entry.expectedActive()).isEmpty(); + assertThat(entry.state()).isEqualTo(ProbeState.PLANNED); + }); + assertThat(count(context, "account_jwt_readiness_validator_pods")).isEqualTo(12L); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(1L); + assertThat(count(context, "account_jwt_readiness_probe_entries")).isEqualTo(8L); + assertThat(count(context, "account_jwt_validator_inventory_snapshots")).isEqualTo(1L); + + long harnessValidUntilEpochSecond = plan.expiresAtEpochSecond() + 600L; + String harnessPeerUri = + "spiffe://firemud/ns/" + BINDING.namespace() + "/sa/account-jwt-readiness-harness"; + List harnessPins = List.of("f".repeat(64)); + String harnessInstanceId = "account-harness-test"; + String harnessBindingDigest = + AccountJwtReadinessTrustBinding.computeBindingDigest( + "readiness-r1", + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harnessPeerUri, + harnessPins, + harnessInstanceId, + harnessValidUntilEpochSecond); + var readinessBinding = + new AccountJwtReadinessTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + harnessPeerUri, + harnessPins, + "readiness-r1", + "account-service", + harnessInstanceId, + harnessValidUntilEpochSecond, + harnessBindingDigest); + var deliveryClaim = + inTransaction( + context, + () -> + owner + .readiness() + .claimSingleDelivery( + BINDING, + owner.trust(), + plan, + readinessBinding, + new PeerIdentity(harnessPeerUri, harnessPins.getFirst()), + Instant.ofEpochSecond(databaseNow))); + assertThat(deliveryClaim.planDigest()).isEqualTo(plan.planDigest()); + assertThat(count(context, "account_jwt_readiness_delivery_claims")).isEqualTo(1L); + + InventorySnapshot refreshedInventory = + completeInventorySnapshot(Instant.ofEpochSecond(databaseNow), observationContext); + assertThat(refreshedInventory.digest()).isEqualTo(planningInventory.digest()); + ReadinessProbePlan exactPlanReplay = + inTransaction( + context, + () -> + owner + .readiness() + .planCurrent( + BINDING, + owner.trust(), + Instant.ofEpochSecond(databaseNow), + refreshedInventory)); + assertThat(exactPlanReplay).isEqualTo(plan); + assertThat( + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentPlan(BINDING, owner.trust(), owner.result().operationId()))) + .isEqualTo(plan); + + ObservationContext wrongPurpose = + new ObservationContext( + ObservationPurpose.STRICT_READY, + observationContext.operationId(), + observationContext.operationDigest()); + InventorySnapshot wrongPurposeInventory = + completeInventorySnapshot(Instant.ofEpochSecond(databaseNow), wrongPurpose); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .planCurrent( + BINDING, + owner.trust(), + Instant.ofEpochSecond(databaseNow), + wrongPurposeInventory))) + .isInstanceOf(AccountJwtReadinessProbeRepository.InventoryPlanConflictException.class); + InventorySnapshot changedInventory = + completeInventorySnapshot( + Instant.ofEpochSecond(databaseNow), "10.11.0.99", observationContext); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .planCurrent( + BINDING, + owner.trust(), + Instant.ofEpochSecond(databaseNow), + changedInventory))) + .isInstanceOf(AccountJwtReadinessProbeRepository.InventoryPlanConflictException.class); + + ProbeEntry plannedCanary = + plan.entries().stream() + .filter( + entry -> + entry.validatorId().equals("account-service") + && entry.probeKind() == AccountMountedJwtSignerBundle.ProbeKind.CANARY) + .findFirst() + .orElseThrow(); + Path privateMount = Files.createDirectory(tempDirectory.resolve("private-mount")); + Path publicMount = Files.createDirectory(tempDirectory.resolve("public-mount")); + Files.writeString( + privateMount.resolve("pending.key"), + privateBundleJson(owner.request(), owner.result(), owner.keyPair())); + Files.writeString(publicMount.resolve("jwks.json"), owner.desiredJwks()); + var expectedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + owner.result().operationId().toString(), + owner.result().targetGeneration(), + owner.result().targetKid(), + owner.result().publicKeyFingerprint()); + var signingSpec = + new AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec( + plannedCanary.validatorId(), + plannedCanary.probeKind(), + plannedCanary.tokenProfile(), + plannedCanary.audience(), + plannedCanary.jti(), + plannedCanary.targetGeneration(), + plannedCanary.targetKid(), + plannedCanary.plannedIssuedAtEpochSecond(), + plannedCanary.expiresAtEpochSecond()); + Instant plannedAt = Instant.ofEpochSecond(plannedCanary.plannedIssuedAtEpochSecond()); + AccountMountedJwtSignerBundle.SignedProbeDigest signed = + AccountMountedJwtSignerBundle.signReadinessProbeDigest( + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json"), + expectedIdentity, + signingSpec, + (digest, compactJwt) -> { + assertThat(sha256(compactJwt)).isEqualTo(digest.compactTokenSha256()); + ProbeEntry attempt = + inTransaction( + context, + () -> + owner + .readiness() + .recordSigningAttempt(BINDING, owner.trust(), digest, plannedAt)); + assertThat(attempt.state()).isEqualTo(ProbeState.PLANNED); + assertThat(attempt.signingAttemptedAtEpochSecond()) + .contains(digest.issuedAtEpochSecond()); + ProbeEntry issued = + inTransaction( + context, + () -> + owner + .readiness() + .recordIssued(BINDING, owner.trust(), digest, plannedAt)); + assertThat(issued.state()).isEqualTo(ProbeState.ISSUED); + assertThat(issued.compactTokenSha256()).contains(digest.compactTokenSha256()); + }); + assertThat(signed.compactTokenSha256()).hasSize(64); + + ProbeEntry issuedEntry = + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentPlan(BINDING, owner.trust(), owner.result().operationId())) + .entries() + .stream() + .filter(entry -> entry.jti().equals(plannedCanary.jti())) + .findFirst() + .orElseThrow(); + assertThat(issuedEntry.state()).isEqualTo(ProbeState.ISSUED); + assertThat(issuedEntry.compactTokenSha256()).contains(signed.compactTokenSha256()); + assertThat( + inTransaction( + context, + () -> owner.readiness().recordIssued(BINDING, owner.trust(), signed, plannedAt))) + .isEqualTo(issuedEntry); + + List expectedPods = + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentExpectedPods( + BINDING, owner.trust(), issuedEntry, refreshedInventory)); + assertThat(expectedPods).hasSize(2); + assertThat(expectedPods) + .extracting(pod -> pod.target().podUid()) + .containsExactly( + "77777777-7777-4777-8777-777777777777", "88888888-8888-4888-8888-888888888888"); + assertThat(expectedPods) + .extracting(pod -> pod.target().exactPodEndpoint().orElseThrow().toString()) + .containsExactly("grpcs://10.11.0.11:9443", "grpcs://10.11.0.12:9443"); + assertThat(expectedPods) + .allSatisfy( + pod -> { + assertThat(pod.planDigest()).isEqualTo(plan.planDigest()); + assertThat(pod.jti()).isEqualTo(issuedEntry.jti()); + assertThat(pod.target().inventorySnapshotDigest()) + .isEqualTo(planningInventory.digest()); + assertThat(pod.target().applicabilityMatrixDigest()) + .isEqualTo(plan.applicabilityMatrixDigest()); + assertThat(pod.target().namespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(pod.target().exactPodEndpoint()).isPresent(); + assertThat(pod.target().canonicalServiceUri()) + .contains("spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator"); + assertThat(pod.target().podLeafSpkiSha256()).isPresent(); + assertThat(pod.target().expectation()).isEqualTo(ProbeExpectation.ACCEPT); + }); + + var selector = ownerSelector(plan, issuedEntry, expectedPods.getFirst()); + var ownerEvidence = + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentProbeOwner( + BINDING, owner.trust(), selector, refreshedInventory, BINDING.namespace())); + assertThat(ownerEvidence.plan().planDigest()).isEqualTo(plan.planDigest()); + assertThat(ownerEvidence.entry()).isEqualTo(issuedEntry); + assertThat(ownerEvidence.expectedPod()).isEqualTo(expectedPods.getFirst()); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentProbeOwner( + BINDING, + owner.trust(), + ownerSelector( + plan, + issuedEntry, + expectedPods.getFirst(), + issuedEntry.expectedActive(), + "inventory-r2", + "d".repeat(64)), + refreshedInventory, + BINDING.namespace()))) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentProbeOwner( + BINDING, + owner.trust(), + ownerSelector( + plan, + issuedEntry, + expectedPods.getFirst(), + issuedEntry.expectedActive(), + "inventory-r1", + "e".repeat(64)), + refreshedInventory, + BINDING.namespace()))) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + var inventedActiveFence = + ownerSelector( + plan, + issuedEntry, + expectedPods.getFirst(), + Optional.of(new AccountJwtSignerDesiredStateRepository.ActiveSigner("2", "old-key"))); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentProbeOwner( + BINDING, + owner.trust(), + inventedActiveFence, + refreshedInventory, + BINDING.namespace()))) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + + AuthenticatedAcceptance firstAcceptance = + testAcceptance(issuedEntry, expectedPods.getFirst(), databaseNow); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + issuedEntry, + expectedPods.getFirst(), + firstAcceptance, + changedInventory))) + .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isZero(); + + AuthenticatedAcceptance wrongEndpoint = + testAcceptance( + issuedEntry, + expectedPods.getFirst(), + databaseNow, + issuedEntry.targetKid(), + "grpcs://192.0.2.1:9443"); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + issuedEntry, + expectedPods.getFirst(), + wrongEndpoint, + refreshedInventory))) + .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); + AuthenticatedAcceptance wrongKid = + testAcceptance( + issuedEntry, expectedPods.getFirst(), databaseNow, issuedEntry.targetKid() + "-wrong"); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + issuedEntry, + expectedPods.getFirst(), + wrongKid, + refreshedInventory))) + .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); + + ProbeEntry partial = + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + issuedEntry, + expectedPods.getFirst(), + firstAcceptance, + refreshedInventory)); + assertThat(partial.state()).isEqualTo(ProbeState.ISSUED); + assertThat(partial.verificationReceipt()).isEmpty(); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(1L); + assertThat( + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + issuedEntry, + expectedPods.getFirst(), + firstAcceptance, + refreshedInventory))) + .isEqualTo(partial); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(1L); + + AuthenticatedAcceptance mismatchedDuplicate = + testAcceptance( + issuedEntry, + expectedPods.getFirst(), + databaseNow, + issuedEntry.targetKid(), + "grpcs://192.0.2.2:9443"); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + issuedEntry, + expectedPods.getFirst(), + mismatchedDuplicate, + refreshedInventory))) + .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(1L); + + AuthenticatedAcceptance secondAcceptance = + testAcceptance(issuedEntry, expectedPods.get(1), databaseNow); + insertRawPodReceipt(context, partial, expectedPods.get(1), secondAcceptance); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(2L); + assertReadinessVerifiedTransitionRejectsChangedSigningAttempt( + context, partial, expectedPods.size(), secondAcceptance.observedAtEpochSecond()); + + ProbeEntry verified = + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + partial, + expectedPods.get(1), + secondAcceptance, + refreshedInventory)); + assertThat(verified.state()).isEqualTo(ProbeState.VERIFIED); + assertThat(verified.signingAttemptedAtEpochSecond()) + .isEqualTo(partial.signingAttemptedAtEpochSecond()); + assertThat(verified.verificationReceipt()).isPresent(); + assertThat(verified.verificationReceipt().orElseThrow().receiptVersion()).isEqualTo(2); + assertThat(verified.verificationReceipt().orElseThrow().podReceiptCount()).isEqualTo(2); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(2L); + + assertThat( + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + verified, + expectedPods.get(1), + testAcceptance(issuedEntry, expectedPods.get(1), databaseNow), + refreshedInventory))) + .isEqualTo(verified); + AuthenticatedAcceptance changedClosedReceipt = + testAcceptance( + issuedEntry, + expectedPods.get(1), + databaseNow, + issuedEntry.targetKid(), + "grpcs://192.0.2.3:9443"); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + verified, + expectedPods.get(1), + changedClosedReceipt, + refreshedInventory))) + .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); + + AccountJwtReadinessProbeRepository restartedRepository = + new AccountJwtReadinessProbeRepository( + context.dsl(), owner.desired(), owner.publication(), owner.inventory()); + ReadinessProbePlan restartedPlan = + inTransaction( + context, + () -> + restartedRepository.readCurrentPlan( + BINDING, owner.trust(), owner.result().operationId())); + ProbeEntry restartedEntry = + restartedPlan.entries().stream() + .filter(entry -> entry.jti().equals(verified.jti())) + .findFirst() + .orElseThrow(); + List expectedRestartedEntries = + plan.entries().stream() + .map(entry -> entry.jti().equals(verified.jti()) ? verified : entry) + .toList(); + assertThat(restartedPlan.operationId()).isEqualTo(plan.operationId()); + assertThat(restartedPlan.planDigest()).isEqualTo(plan.planDigest()); + assertThat(restartedPlan.entries()).containsExactlyElementsOf(expectedRestartedEntries); + assertThat(restartedEntry).isEqualTo(verified); + assertThat(restartedEntry.verificationReceipt()) + .contains(verified.verificationReceipt().orElseThrow()); + assertThat(restartedPlan.expectedFence().durableActive()).isEmpty(); + assertThat(restartedPlan.expectedFence().publishedActive()).isEmpty(); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(2L); + + long remainingExpectedPodReceipts = + completeRemainingProbes( + context, owner, plan, refreshedInventory, privateMount, publicMount, expectedIdentity); + long expectedPodReceiptCount = expectedPods.size() + remainingExpectedPodReceipts; + assertThat(expectedPodReceiptCount).isEqualTo(12L); + var proof = + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentPromotionPrerequisites( + BINDING, owner.trust(), owner.result().operationId(), refreshedInventory) + .orElseThrow()); + assertThat(proof.verifiedProbes()).hasSize(plan.entries().size()); + assertThat(sha256(proof.readinessEvidencePreimage())) + .isEqualTo(proof.readinessEvidenceDigest()); + byte[] callerCopy = proof.readinessEvidencePreimage(); + callerCopy[0] ^= 1; + assertThat(sha256(proof.readinessEvidencePreimage())) + .isEqualTo(proof.readinessEvidenceDigest()); + + byte[] exactPreimage = proof.readinessEvidencePreimage(); + assertThatThrownBy( + () -> insertDirectPromotion(context, owner, proof, "0".repeat(64), exactPreimage)) + .satisfies( + failure -> + assertThat(postgresConstraint(failure)) + .isEqualTo("account_jwt_signer_promotion_readiness_digest")); + String changedProofText = + new String(exactPreimage, StandardCharsets.UTF_8) + .replace( + proof.inventoryEvidenceReference(), + proof.inventoryEvidenceReference() + ":changed"); + byte[] changedPreimage = changedProofText.getBytes(StandardCharsets.UTF_8); + assertThatThrownBy( + () -> + insertDirectPromotion( + context, owner, proof, sha256(changedPreimage), changedPreimage)) + .satisfies( + failure -> + assertThat(postgresConstraint(failure)) + .isEqualTo("account_jwt_signer_promotion_readiness_binding")); + + assertThatThrownBy( + () -> + inTransaction( + context, + () -> { + insertDirectGenerationAbortReceipt(context, owner); + insertDirectPromotionInCurrentTransaction( + context, + owner, + proof, + UUID.randomUUID(), + proof.readinessEvidenceDigest(), + exactPreimage); + return null; + })) + .satisfies( + failure -> + assertThat(postgresConstraint(failure)) + .isEqualTo("account_jwt_signer_promotion_insert_binding")); + assertThat(count(context, "account_jwt_signer_generation_abort_receipts")).isZero(); + + var publicationEvidence = proof.publication(); + PromotionPreparation preparation = + new PromotionPreparation( + proof.generationResult().operationId(), + proof.generationResult(), + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + TRUST_DIGEST, + TRUST_REVISION, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + INITIAL_CONFIG_MAP_RESOURCE_VERSION, + AccountJwtJwksPublicationRepository.snapshotDigest(INITIAL_CONFIG_MAP_DATA)), + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + publicationEvidence.receipt().observedResourceVersion(), + publicationEvidence.intent().intentDigest(), + publicationEvidence.receipt().receiptDigest(), + publicationEvidence.mountedCorrespondence().observationDigest(), + proof.plan().planDigest(), + proof.readinessEvidenceDigest(), + publicationEvidence.intent().jwksJson()); + var prepared = + inTransaction( + context, + () -> + owner + .desired() + .prepareCurrentGeneration(BINDING, owner.trust(), preparation, proof)); + assertThat(prepared.status()).isEqualTo("PREPARED"); + assertThat( + inTransaction( + context, + () -> + owner + .desired() + .prepareCurrentGeneration(BINDING, owner.trust(), preparation, proof))) + .isEqualTo(prepared); + assertThat(count(context, "account_jwt_signer_promotion_operations")).isEqualTo(1L); + assertThat(count(context, "account_jwt_readiness_pod_receipts")) + .isEqualTo(expectedPodReceiptCount); + + byte[] persistedPreimage = + java.util.Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT readiness_evidence_preimage FROM account_jwt_signer_promotion_operations " + + "WHERE operation_id = ?", + prepared.operationId()), + "Prepared promotion must retain its exact readiness preimage") + .get("readiness_evidence_preimage", byte[].class); + assertThat(persistedPreimage).isEqualTo(exactPreimage); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_signer_promotion_operations " + + "SET readiness_evidence_digest = ? WHERE operation_id = ?", + "0".repeat(64), + prepared.operationId()))) + .satisfies( + failure -> + assertThat(postgresConstraint(failure)) + .isEqualTo("account_jwt_signer_operation_immutable")); + byte[] changedStoredPreimage = exactPreimage.clone(); + changedStoredPreimage[0] ^= 1; + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_signer_promotion_operations " + + "SET readiness_evidence_preimage = ? WHERE operation_id = ?", + changedStoredPreimage, + prepared.operationId()))) + .satisfies( + failure -> + assertThat(postgresConstraint(failure)) + .isEqualTo("account_jwt_signer_operation_immutable")); + + AccountJwtSignerDesiredStateRepository restartedDesired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + AccountJwtJwksPublicationRepository restartedPublication = + new AccountJwtJwksPublicationRepository(context.dsl(), restartedDesired); + AccountJwtValidatorInventoryRepository restartedInventory = + new AccountJwtValidatorInventoryRepository(context.dsl()); + AccountJwtReadinessProbeRepository restartedReadiness = + new AccountJwtReadinessProbeRepository( + context.dsl(), restartedDesired, restartedPublication, restartedInventory); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> restartedDesired.readCurrentGenerationRequest(BINDING, owner.trust()))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) + .hasMessage("Existing PREPARED signer state requires unavailable lifecycle evidence"); + var restartedProof = + inTransaction( + context, + () -> + restartedReadiness + .readPromotionProof( + BINDING, owner.trust(), owner.result().operationId(), refreshedInventory) + .orElseThrow()); + assertThat(restartedProof.readinessEvidencePreimage()).isEqualTo(exactPreimage); + assertThat(databaseClockNow(context)).isLessThan(plan.expiresAtEpochSecond()); + var dispatchedEvidence = + inTransaction( + context, + () -> restartedDesired.readAndMarkPreparedPromotionDispatched(BINDING, owner.trust())); + assertThat(dispatchedEvidence.promotion().privatePromotionDispatched()).isTrue(); + var dispatchedProof = + inTransaction( + context, + () -> + restartedReadiness + .readPromotionProof(BINDING, owner.trust(), owner.result().operationId()) + .orElseThrow()); + assertThat(dispatchedProof.readinessEvidencePreimage()).isEqualTo(exactPreimage); + assertThat(dispatchedProof.readinessEvidenceDigest()) + .isEqualTo(proof.readinessEvidenceDigest()); + OwnerState restartedOwner = + new OwnerState( + restartedDesired, + restartedPublication, + restartedInventory, + restartedReadiness, + owner.trust(), + owner.request(), + owner.result(), + owner.keyPair(), + owner.desiredJwks()); + assertThat( + inTransaction( + context, + () -> + restartedOwner + .desired() + .prepareCurrentGeneration( + BINDING, restartedOwner.trust(), preparation, dispatchedProof))) + .isEqualTo(prepared); + + // These synthetic owner readbacks stand for the two exact external CAS receipts. + var dispatchedPromotion = dispatchedEvidence.promotion(); + PrivatePromotionObservation privatePromotionObservation = + new PrivatePromotionObservation( + dispatchedPromotion.operationId(), + dispatchedPromotion.requestDigest(), + dispatchedPromotion.generationOperationId(), + dispatchedPromotion.generationOperationDigest(), + owner.result().secretUid(), + dispatchedPromotion.expectedPrivateResourceVersion(), + "14", + new PublicKeyIdentity( + dispatchedPromotion.targetGeneration(), + dispatchedPromotion.targetKid(), + dispatchedPromotion.targetPublicKeyFingerprint()), + Optional.empty(), + List.of("current")); + var privatePromotionReceipt = + inTransaction( + context, + () -> + restartedDesired.recordPrivatePromotionResult( + BINDING, owner.trust(), privatePromotionObservation)); + var activeJwksPromotionReceipt = + inTransaction( + context, + () -> + restartedDesired.recordActiveJwksPromotionResult( + BINDING, + owner.trust(), + new ActiveJwksPromotionObservation( + dispatchedPromotion.publicConfigMapUid(), + dispatchedPromotion.expectedPublicResourceVersion(), + "43", + dispatchedPromotion.expectedPublicJwksJson(), + dispatchedPromotion.expectedActiveMarkerJson()))); + var receiptBoundPrepared = + inTransaction( + context, + () -> restartedDesired.readPreparedGenerationForRecovery(BINDING, owner.trust())); + assertThat(receiptBoundPrepared.promotion().privatePromotionReceiptDigest()) + .contains(privatePromotionReceipt.receiptDigest()); + assertThat(receiptBoundPrepared.promotion().activeJwksReceiptDigest()) + .contains(activeJwksPromotionReceipt.receiptDigest()); + + assertThat(databaseClockNow(context)).isLessThan(plan.expiresAtEpochSecond()); + var receiptBoundProof = + inTransaction( + context, + () -> + restartedReadiness + .readPromotionProof(BINDING, owner.trust(), owner.result().operationId()) + .orElseThrow()); + assertThat(receiptBoundProof.plan().planDigest()).isEqualTo(plan.planDigest()); + assertThat(receiptBoundProof.plan().expiresAtEpochSecond()) + .isEqualTo(plan.expiresAtEpochSecond()); + assertThat(receiptBoundProof.readinessEvidencePreimage()).isEqualTo(exactPreimage); + assertThat(receiptBoundProof.readinessEvidenceDigest()) + .isEqualTo(proof.readinessEvidenceDigest()); + assertThat(receiptBoundProof.verifiedProbes()).hasSize(plan.entries().size()); + assertThat( + inTransaction( + context, + () -> + restartedOwner + .desired() + .prepareCurrentGeneration( + BINDING, restartedOwner.trust(), preparation, receiptBoundProof))) + .isEqualTo(prepared); + + var committed = + inTransaction( + context, + () -> + restartedDesired.commitPreparedPromotion( + BINDING, owner.trust(), prepared.operationId(), receiptBoundProof)); + assertThat(committed.promotion().status()).isEqualTo("COMMITTED"); + assertThat(committed.promotion().privatePromotionReceiptDigest()) + .contains(privatePromotionReceipt.receiptDigest()); + assertThat(committed.promotion().activeJwksReceiptDigest()) + .contains(activeJwksPromotionReceipt.receiptDigest()); + assertThat(committed.privateReceipt()).isEqualTo(privatePromotionReceipt); + assertThat(committed.publicReceipt()).isEqualTo(activeJwksPromotionReceipt); + + assertReadinessEvidenceTruncateDeniedWithoutLoss( + context, + List.of( + "account_jwt_readiness_probe_plans", + "account_jwt_readiness_probe_entries", + "account_jwt_readiness_validator_pods", + "account_jwt_readiness_pod_receipts", + "account_jwt_readiness_delivery_claims")); + } + + private static long completeRemainingProbes( + TestContext context, + OwnerState owner, + ReadinessProbePlan plan, + InventorySnapshot inventory, + Path privateMount, + Path publicMount, + AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity) + throws Exception { + long expectedPodReceiptCount = 0; + for (ProbeEntry planned : plan.entries()) { + ProbeEntry current = + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentPlan(BINDING, owner.trust(), owner.result().operationId())) + .entries() + .stream() + .filter(entry -> entry.jti().equals(planned.jti())) + .findFirst() + .orElseThrow(); + if (current.state() == ProbeState.VERIFIED) { + continue; + } + var signingSpec = + new AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec( + current.validatorId(), + current.probeKind(), + current.tokenProfile(), + current.audience(), + current.jti(), + current.targetGeneration(), + current.targetKid(), + current.plannedIssuedAtEpochSecond(), + current.expiresAtEpochSecond()); + Instant plannedAt = Instant.ofEpochSecond(current.plannedIssuedAtEpochSecond()); + AccountMountedJwtSignerBundle.signReadinessProbeDigest( + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json"), + expectedIdentity, + signingSpec, + (digest, compactJwt) -> { + inTransaction( + context, + () -> + owner + .readiness() + .recordSigningAttempt(BINDING, owner.trust(), digest, plannedAt)); + inTransaction( + context, + () -> owner.readiness().recordIssued(BINDING, owner.trust(), digest, plannedAt)); + }); + ProbeEntry issued = + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentPlan(BINDING, owner.trust(), owner.result().operationId())) + .entries() + .stream() + .filter(entry -> entry.jti().equals(planned.jti())) + .findFirst() + .orElseThrow(); + ProbeEntry issuedForInventory = issued; + List pods = + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentExpectedPods( + BINDING, owner.trust(), issuedForInventory, inventory)); + expectedPodReceiptCount += pods.size(); + for (ExpectedPod pod : pods) { + ProbeEntry currentEvidence = issued; + var acceptance = testAcceptance(currentEvidence, pod, databaseNow(context)); + issued = + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, owner.trust(), currentEvidence, pod, acceptance, inventory)); + } + assertThat(issued.state()).isEqualTo(ProbeState.VERIFIED); + } + return expectedPodReceiptCount; + } + + private static void insertDirectPromotion( + TestContext context, + OwnerState owner, + AccountJwtReadinessProbeRepository.ReadinessPromotionProof proof, + String readinessDigest, + byte[] readinessPreimage) { + inTransaction( + context, + () -> { + insertDirectPromotionInCurrentTransaction( + context, owner, proof, UUID.randomUUID(), readinessDigest, readinessPreimage); + return null; + }); + } + + private static void insertDirectPromotionInCurrentTransaction( + TestContext context, + OwnerState owner, + AccountJwtReadinessProbeRepository.ReadinessPromotionProof proof, + UUID promotionOperationId, + String readinessDigest, + byte[] readinessPreimage) { + var publication = proof.publication(); + String activeGenerationMarker = generationMarkerUnchecked(owner.result()); + int inserted = + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_promotion_operations " + + "(operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "request_digest_version, request_digest, expected_record_version, " + + "expected_previous_generation, expected_previous_kid, target_generation, target_kid, " + + "target_algorithm, target_public_key_fingerprint, " + + "expected_private_secret_resource_version, expected_public_jwks_resource_version, " + + "expected_public_active_generation, expected_public_active_kid, operation_action, " + + "allowed_private_slots_canonical_bytes, status, generation_operation_id, " + + "expected_cluster_incarnation_uid, expected_namespace_uid, " + + "materializer_trust_binding_digest, materializer_trust_config_revision, " + + "api_binding_digest, api_config_revision, expected_private_secret_uid, " + + "expected_public_config_map_uid, prepublication_intent_digest, " + + "prepublication_receipt_digest, mounted_observation_digest, readiness_plan_digest, " + + "readiness_evidence_digest, readiness_evidence_preimage, expected_public_jwks_json, " + + "expected_active_generation_marker_json) " + + "VALUES (?, ?, ?, ?, ?, 1, ?, ?, NULL, NULL, ?, ?, 'RS256', ?, ?, ?, " + + "NULL, NULL, 'PROMOTE_PENDING', ?, 'PREPARED', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + promotionOperationId, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + BINDING.mode().value(), + directPromotionRequestDigest(owner, proof, promotionOperationId, readinessDigest), + owner.result().desiredStateVersion(), + Long.parseLong(owner.result().targetGeneration()), + owner.result().targetKid(), + owner.result().publicKeyFingerprint(), + owner.result().observedResourceVersion(), + publication.receipt().observedResourceVersion(), + "[\"current\",\"pending\",\"previous\"]".getBytes(StandardCharsets.UTF_8), + owner.result().operationId(), + UUID.fromString(owner.trust().expectedClusterIncarnationUid()), + UUID.fromString(owner.trust().expectedNamespaceUid()), + owner.trust().bindingDigest(), + owner.trust().configRevision(), + API_DIGEST, + API_REVISION, + UUID.fromString(owner.result().secretUid()), + UUID.fromString(CONFIG_MAP_UID), + publication.intent().intentDigest(), + publication.receipt().receiptDigest(), + publication.mountedCorrespondence().observationDigest(), + proof.plan().planDigest(), + readinessDigest, + readinessPreimage, + publication.intent().jwksJson(), + activeGenerationMarker); + assertThat(inserted).isEqualTo(1); + } + + private static void insertDirectGenerationAbortReceipt(TestContext context, OwnerState owner) { + int inserted = + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_generation_abort_receipts " + + "(operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, " + + "operation_digest, generation_request_digest, generation_receipt_digest, " + + "expected_state_version, resulting_state_version, expected_cluster_incarnation_uid, " + + "expected_namespace_uid, trust_binding_digest, trust_config_revision, " + + "durable_active_generation, durable_active_kid, published_active_generation, " + + "published_active_kid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL)", + owner.result().operationId(), + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + BINDING.mode().value(), + owner.result().operationDigest(), + owner.result().generationRequestDigest(), + owner.result().receiptDigest(), + owner.result().desiredStateVersion(), + owner.result().desiredStateVersion() + 1L, + UUID.fromString(owner.trust().expectedClusterIncarnationUid()), + UUID.fromString(owner.trust().expectedNamespaceUid()), + owner.trust().bindingDigest(), + owner.trust().configRevision()); + assertThat(inserted).isEqualTo(1); + } + + private static String directPromotionRequestDigest( + OwnerState owner, + AccountJwtReadinessProbeRepository.ReadinessPromotionProof proof, + UUID promotionOperationId, + String readinessDigest) { + var publication = proof.publication(); + var result = owner.result(); + Map preimage = new LinkedHashMap<>(); + preimage.put("digestVersion", "account-jwt-signer-promotion-operation/v1"); + preimage.put("operationId", promotionOperationId.toString()); + preimage.put("generationOperationId", result.operationId().toString()); + preimage.put("generationOperationDigest", result.operationDigest()); + preimage.put("generationReceiptDigest", result.receiptDigest()); + preimage.put("environmentId", BINDING.environmentId()); + preimage.put("clusterId", BINDING.clusterId()); + preimage.put("namespace", BINDING.namespace()); + preimage.put("custodyMode", BINDING.mode().value()); + preimage.put("expectedRecordVersion", Long.toString(result.desiredStateVersion())); + preimage.put("expectedPreviousActive", Map.of("present", false)); + preimage.put("expectedPublishedActive", Map.of("present", false)); + preimage.put("targetGeneration", result.targetGeneration()); + preimage.put("targetKid", result.targetKid()); + preimage.put("targetAlgorithm", "RS256"); + preimage.put("targetPublicKeyFingerprint", result.publicKeyFingerprint()); + preimage.put("expectedPrivateSecretUid", result.secretUid()); + preimage.put("expectedPrivateSecretResourceVersion", result.observedResourceVersion()); + preimage.put("expectedPublicConfigMapUid", CONFIG_MAP_UID); + preimage.put( + "expectedPublicJwksResourceVersion", publication.receipt().observedResourceVersion()); + preimage.put("expectedClusterIncarnationUid", owner.trust().expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", owner.trust().expectedNamespaceUid()); + preimage.put("materializerTrustBindingDigest", owner.trust().bindingDigest()); + preimage.put("materializerTrustConfigRevision", owner.trust().configRevision()); + preimage.put("apiBindingDigest", API_DIGEST); + preimage.put("apiConfigRevision", API_REVISION); + preimage.put("prepublicationIntentDigest", publication.intent().intentDigest()); + preimage.put("prepublicationReceiptDigest", publication.receipt().receiptDigest()); + preimage.put( + "mountedObservationDigest", publication.mountedCorrespondence().observationDigest()); + preimage.put("readinessPlanDigest", proof.plan().planDigest()); + preimage.put("readinessEvidenceDigest", readinessDigest); + preimage.put( + "publicJwksSha256", + sha256(publication.intent().jwksJson().getBytes(StandardCharsets.UTF_8))); + preimage.put("operationAction", "PROMOTE_PENDING"); + preimage.put("allowedPrivateSlots", List.of("current", "pending", "previous")); + try { + return sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage))); + } catch (Exception failure) { + throw new AssertionError( + "Direct promotion digest fixture could not be canonicalized", failure); + } + } + + private static String postgresConstraint(Throwable failure) { + Throwable current = failure; + while (current != null) { + if (current instanceof PSQLException postgresFailure) { + var serverError = postgresFailure.getServerErrorMessage(); + if (serverError != null) { + return serverError.getConstraint(); + } + } + current = current.getCause(); + } + return null; + } + + private static String generationMarkerUnchecked(GenerationResult result) { + try { + return generationMarker(result); + } catch (Exception failure) { + throw new AssertionError("Generation marker fixture could not be serialized", failure); + } + } + + private OwnerState createOwnerState(TestContext context) throws Exception { + AccountJwtSignerDesiredStateRepository desired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + AccountJwtJwksPublicationRepository publication = + new AccountJwtJwksPublicationRepository(context.dsl(), desired); + AccountJwtValidatorInventoryRepository inventory = + new AccountJwtValidatorInventoryRepository(context.dsl()); + AccountJwtReadinessProbeRepository readiness = + new AccountJwtReadinessProbeRepository(context.dsl(), desired, publication, inventory); + TrustFence trust = new TrustFence(CLUSTER_UID, NAMESPACE_UID, TRUST_DIGEST, TRUST_REVISION); + EnrollmentIdentity enrollment = + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + TRUST_DIGEST, + TRUST_REVISION, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + INITIAL_CONFIG_MAP_RESOURCE_VERSION, + AccountJwtJwksPublicationRepository.snapshotDigest(INITIAL_CONFIG_MAP_DATA)); + inTransaction(context, () -> desired.initialize(BINDING, enrollment)); + GenerationRequest requested = + inTransaction(context, () -> desired.ensureCurrentGenerationRequest(BINDING, trust)); + GenerationRequest observed = + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + trust, + requested.operationId(), + requested.operationDigest(), + SECRET_UID, + "12")); + KeyPair keyPair = generateRsa3072(); + PublicJwk targetJwk = publicJwk(requested.targetKid(), (RSAPublicKey) keyPair.getPublic()); + GenerationResult result = + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + trust, + requested.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + targetJwk.json())); + + KeyPair retainedPair = generateRsa3072(); + String retainedJwk = + publicJwk("retained-key", (RSAPublicKey) retainedPair.getPublic()).jsonWithoutKeyOps(); + String desiredJwks = jwks(retainedJwk, targetJwk.json()); + String marker = generationMarker(result); + String expectedSnapshotDigest = + AccountJwtJwksPublicationRepository.snapshotDigest(INITIAL_CONFIG_MAP_DATA); + GenerationRequest currentRequest = + inTransaction(context, () -> desired.readCurrentGenerationRequest(BINDING, trust)); + var intent = + inTransaction( + context, + () -> + publication.recordPrepublicationIntent( + BINDING, + trust, + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + INITIAL_CONFIG_MAP_RESOURCE_VERSION, + expectedSnapshotDigest, + desiredJwks, + marker)); + var publicationReceipt = + inTransaction( + context, + () -> + publication.recordPublicationReceipt( + BINDING, + trust, + result.operationId(), + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "42", + desiredJwks, + marker)); + assertThat(intent.jwksJson()).isEqualTo(desiredJwks); + assertThat(intent.jwksJson()).contains(targetJwk.json()); + inTransaction( + context, + () -> + publication.recordMountedCorrespondence( + BINDING, + trust, + result.operationId(), + sha256(marker.getBytes(StandardCharsets.UTF_8)), + AccountJwtJwksPublicationRepository.publicDataDigest(desiredJwks, marker), + result.publicKeyFingerprint())); + assertThat(publicationReceipt.intentDigest()).isEqualTo(intent.intentDigest()); + return new OwnerState( + desired, publication, inventory, readiness, trust, requested, result, keyPair, desiredJwks); + } + + private TestContext newTestContext(String targetVersion) { + String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); + schemas.add(schema); + var dataSource = POSTGRES.dataSource(schema); + var configuration = + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations("classpath:db/migration"); + if (targetVersion != null) { + configuration.target(targetVersion); + } + configuration.load().migrate(); + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transaction = new TransactionTemplate(transactionManager); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + return new TestContext(schema, dataSource, transaction, dsl); + } + + private static T inTransaction(TestContext context, Supplier operation) { + return context.transaction().execute(status -> operation.get()); + } + + private static long count(TestContext context, String table) { + return java.util.Objects.requireNonNull( + context.dsl().resultQuery("SELECT count(*) FROM " + table).fetchOne(0, Long.class), + "Count query returned no row."); + } + + private static String readinessMatrixWithMissingOrNullField( + String validMatrixJson, String field, boolean explicitNull) { + try { + @SuppressWarnings("unchecked") + Map matrix = (Map) JSON.readValue(validMatrixJson, Map.class); + Map target = matrix; + if (field.equals("validatorId") || field.equals("applicableProfiles")) { + @SuppressWarnings("unchecked") + List> validators = (List>) matrix.get("validators"); + target = + validators.stream() + .filter(validator -> "account-service".equals(validator.get("validatorId"))) + .findFirst() + .orElseThrow(); + } + if (explicitNull) { + target.put(field, null); + } else { + target.remove(field); + } + return JSON.writeValueAsString(matrix); + } catch (Exception failure) { + throw new AssertionError("Readiness inventory SQL fixture could not be mutated", failure); + } + } + + private static String readinessMatrixWithExtraValidator(String validMatrixJson) { + try { + @SuppressWarnings("unchecked") + Map matrix = (Map) JSON.readValue(validMatrixJson, Map.class); + @SuppressWarnings("unchecked") + List> parsedValidators = + (List>) matrix.get("validators"); + List> validators = new java.util.ArrayList<>(parsedValidators); + Map extraValidator = new LinkedHashMap<>(validators.getFirst()); + extraValidator.put("validatorId", "unexpected-validator"); + validators.add(extraValidator); + matrix.put("validators", validators); + matrix.put("inventoryStatus", "PARTIAL_UNCONFIRMED"); + return JSON.writeValueAsString(matrix); + } catch (Exception failure) { + throw new AssertionError("Readiness SQL validator-set fixture could not be mutated", failure); + } + } + + private static String readinessMatrixWithDifferentApplicableProfiles(String validMatrixJson) { + try { + @SuppressWarnings("unchecked") + Map matrix = (Map) JSON.readValue(validMatrixJson, Map.class); + @SuppressWarnings("unchecked") + List> validators = (List>) matrix.get("validators"); + Map accountValidator = + validators.stream() + .filter(validator -> "account-service".equals(validator.get("validatorId"))) + .findFirst() + .orElseThrow(); + @SuppressWarnings("unchecked") + List> parsedProfiles = + (List>) accountValidator.get("applicableProfiles"); + List> profiles = new java.util.ArrayList<>(parsedProfiles); + profiles.removeFirst(); + accountValidator.put("applicableProfiles", profiles); + matrix.put("inventoryStatus", "PARTIAL_UNCONFIRMED"); + return JSON.writeValueAsString(matrix); + } catch (Exception failure) { + throw new AssertionError("Readiness SQL profile fixture could not be mutated", failure); + } + } + + private static void assertReadinessInventoryClosureGuardRejectsMatrixMismatch( + TestContext context, + ReadinessProbePlan plan, + String mismatchedMatrixJson, + String mismatchDescription) { + assertThatThrownBy( + () -> + inTransaction( + context, + () -> { + insertRawReadinessPlanClosure(context, plan, mismatchedMatrixJson, false); + assertThat(count(context, "account_jwt_readiness_probe_entries")) + .isEqualTo(plan.entries().size()); + assertThat(count(context, "account_jwt_readiness_validator_pods")) + .isEqualTo(12L); + return null; + })) + .as("deferred V2 closure must reject %s", mismatchDescription) + .satisfies(failure -> assertThat(postgresSqlState(failure)).isEqualTo("23514")); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); + assertThat(count(context, "account_jwt_readiness_probe_entries")).isZero(); + assertThat(count(context, "account_jwt_readiness_validator_pods")).isZero(); + } + + private static void insertRawReadinessPlanClosure( + TestContext context, + ReadinessProbePlan plan, + String applicabilityMatrixJson, + boolean inventoryComplete) { + insertRawReadinessPlan(context, plan, applicabilityMatrixJson, inventoryComplete); + for (ProbeEntry entry : plan.entries()) { + context + .dsl() + .execute( + """ + INSERT INTO account_jwt_readiness_probe_entries ( + rotation_operation_id, plan_digest, validator_id, token_profile, audience, + probe_kind, jti, target_generation, target_kid, expected_active_generation, + expected_active_kid, registry_version, entry_version, + planned_issued_at_epoch_seconds, expires_at_epoch_seconds, state, entry_plan_version + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + entry.rotationOperationId(), + entry.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name(), + entry.jti(), + Long.parseLong(entry.targetGeneration()), + entry.targetKid(), + entry.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null), + entry.expectedActive().map(value -> value.kid()).orElse(null), + entry.registryVersion(), + entry.entryVersion(), + entry.plannedIssuedAtEpochSecond(), + entry.expiresAtEpochSecond(), + entry.state().name(), + plan.planVersion()); + } + context + .dsl() + .execute( + """ + INSERT INTO account_jwt_readiness_validator_pods ( + rotation_operation_id, plan_digest, validator_id, token_profile, audience, + probe_kind, jti, inventory_snapshot_digest, environment_id, cluster_id, + cluster_incarnation_uid, kubernetes_namespace, namespace_uid, + api_binding_revision, api_binding_digest, inventory_binding_revision, + inventory_binding_digest, deployment_uid, pod_uid, pod_ip, image, + verifier_config_sha256, applicability_matrix_digest, expected_outcome, + exact_pod_endpoint, canonical_service_uri, expected_pod_leaf_spki_sha256 + ) + SELECT entry.rotation_operation_id, + entry.plan_digest, + entry.validator_id, + entry.token_profile, + entry.audience, + entry.probe_kind, + entry.jti, + snapshot.snapshot_digest, + snapshot.environment_id, + snapshot.cluster_id, + snapshot.cluster_incarnation_uid, + snapshot.kubernetes_namespace, + snapshot.namespace_uid, + snapshot.api_binding_revision, + snapshot.api_binding_digest, + snapshot.inventory_binding_revision, + snapshot.inventory_binding_digest, + (validator.value ->> 'deploymentUid')::uuid, + (pod.value ->> 'uid')::uuid, + pod.value ->> 'podIp', + pod.value ->> 'image', + pod.value ->> 'verifierConfigSha256', + plan.applicability_matrix_digest, + CASE + WHEN entry.probe_kind = 'CANARY' + OR EXISTS ( + SELECT 1 + FROM jsonb_array_elements(validator.value -> 'profiles') AS profile(value) + WHERE profile.value ->> 'tokenProfile' = entry.token_profile + AND profile.value ->> 'audience' = entry.audience) + THEN 'ACCEPT' + ELSE 'INAPPLICABLE_REJECT' + END, + pod.value ->> 'exactPodEndpoint', + pod.value ->> 'canonicalServiceUri', + pod.value ->> 'leafSpkiSha256' + FROM account_jwt_readiness_probe_entries AS entry + JOIN account_jwt_readiness_probe_plans AS plan + ON plan.rotation_operation_id = entry.rotation_operation_id + AND plan.plan_digest = entry.plan_digest + JOIN account_jwt_validator_inventory_snapshots AS snapshot + ON snapshot.snapshot_digest = plan.inventory_snapshot_digest + CROSS JOIN LATERAL jsonb_array_elements( + convert_from(snapshot.canonical_snapshot, 'UTF8')::jsonb -> 'validators') AS validator(value) + CROSS JOIN LATERAL jsonb_array_elements(validator.value -> 'pods') AS pod(value) + WHERE entry.rotation_operation_id = ? + AND entry.plan_digest = ? + AND validator.value ->> 'validatorId' = entry.validator_id + """, + plan.operationId(), + plan.planDigest()); + } + + private static void assertReadinessPlanInventoryGuardRejects( + TestContext context, ReadinessProbePlan plan, List requiredFields) { + for (String field : requiredFields) { + for (boolean explicitNull : new boolean[] {false, true}) { + String malformedMatrix = + readinessMatrixWithMissingOrNullField( + plan.applicabilityMatrixJson(), field, explicitNull); + String fieldState = explicitNull ? "null " : "missing "; + assertThatThrownBy( + () -> + inTransaction( + context, + () -> { + insertRawReadinessPlan(context, plan, malformedMatrix); + return null; + })) + .as("raw SQL must reject V%s %s%s", plan.planVersion(), fieldState, field) + .satisfies(failure -> assertThat(postgresSqlState(failure)).isEqualTo("23514")); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); + } + } + + context + .transaction() + .execute( + status -> { + insertRawReadinessPlan(context, plan, plan.applicabilityMatrixJson()); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(1L); + status.setRollbackOnly(); + return null; + }); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); + } + + private static void insertRawReadinessPlan( + TestContext context, ReadinessProbePlan plan, String applicabilityMatrixJson) { + insertRawReadinessPlan( + context, plan, applicabilityMatrixJson, plan.validatorInventoryComplete()); + } + + private static void insertRawReadinessPlan( + TestContext context, + ReadinessProbePlan plan, + String applicabilityMatrixJson, + boolean validatorInventoryComplete) { + new JdbcTemplate(context.dataSource()) + .update( + """ + INSERT INTO account_jwt_readiness_probe_plans ( + rotation_operation_id, environment_id, cluster_id, kubernetes_namespace, custody_mode, + operation_digest, generation_request_digest, generation_receipt_digest, + desired_state_version, expected_cluster_incarnation_uid, expected_namespace_uid, + trust_binding_digest, trust_config_revision, target_generation, target_kid, + target_public_key_fingerprint, expected_active_generation, expected_active_kid, + expected_published_generation, expected_published_kid, publication_intent_digest, + publication_receipt_digest, mounted_observation_digest, applicability_matrix_json, + applicability_matrix_digest, validator_inventory_complete, maximum_cache_age_seconds, + planned_at_epoch_seconds, not_before_epoch_seconds, expires_at_epoch_seconds, + plan_version, plan_digest, inventory_snapshot_digest + ) VALUES ( + ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? + ) + """, + plan.operationId(), + plan.binding().environmentId(), + plan.binding().clusterId(), + plan.binding().namespace(), + plan.binding().mode().value(), + plan.operationDigest(), + plan.generationRequestDigest(), + plan.generationReceiptDigest(), + plan.desiredStateVersion(), + UUID.fromString(plan.trustFence().expectedClusterIncarnationUid()), + UUID.fromString(plan.trustFence().expectedNamespaceUid()), + plan.trustFence().bindingDigest(), + plan.trustFence().configRevision(), + Long.parseLong(plan.targetGeneration()), + plan.targetKid(), + plan.targetPublicKeyFingerprint(), + plan.expectedFence() + .durableActive() + .map(value -> Long.parseLong(value.generation())) + .orElse(null), + plan.expectedFence().durableActive().map(value -> value.kid()).orElse(null), + plan.expectedFence() + .publishedActive() + .map(value -> Long.parseLong(value.generation())) + .orElse(null), + plan.expectedFence().publishedActive().map(value -> value.kid()).orElse(null), + plan.publicationIntentDigest(), + plan.publicationReceiptDigest(), + plan.mountedObservationDigest(), + applicabilityMatrixJson, + plan.applicabilityMatrixDigest(), + validatorInventoryComplete, + plan.maximumCacheAgeSeconds(), + plan.plannedAtEpochSecond(), + plan.notBeforeEpochSecond(), + plan.expiresAtEpochSecond(), + plan.planVersion(), + plan.planDigest(), + plan.inventorySnapshotDigest().orElse(null)); + } + + private static void assertReadinessEvidenceTruncateDeniedWithoutLoss( + TestContext context, List tables) { + Map retainedCounts = new LinkedHashMap<>(); + for (String table : tables) { + retainedCounts.put(table, count(context, table)); + } + assertThat(retainedCounts.values()).allSatisfy(count -> assertThat(count).isPositive()); + + for (String table : tables) { + for (String cascade : List.of("", " CASCADE")) { + assertThatThrownBy( + () -> + inTransaction( + context, + () -> { + context.dsl().execute("TRUNCATE TABLE " + table + cascade); + return null; + })) + .as("raw TRUNCATE must retain readiness evidence in %s%s", table, cascade) + .satisfies( + failure -> { + String sqlState = postgresSqlState(failure); + List expectedSqlStates = + cascade.isEmpty() ? List.of("23514", "0A000") : List.of("23514"); + assertThat(sqlState).isIn(expectedSqlStates); + if ("23514".equals(sqlState)) { + assertThat(postgresServerMessage(failure)) + .contains("Account JWT readiness evidence"); + } + }); + retainedCounts.forEach( + (retainedTable, expectedCount) -> + assertThat(count(context, retainedTable)).isEqualTo(expectedCount)); + } + } + } + + private static void insertRawPodReceipt( + TestContext context, + ProbeEntry entry, + ExpectedPod expectedPod, + AuthenticatedAcceptance acceptance) { + Map digestFields = new LinkedHashMap<>(); + digestFields.put("domain", "account-jwt-readiness-per-pod-receipt/v1"); + digestFields.put("rotationOperationId", entry.rotationOperationId().toString()); + digestFields.put("planDigest", entry.planDigest()); + digestFields.put("validatorId", entry.validatorId()); + digestFields.put("tokenProfile", entry.tokenProfile()); + digestFields.put("audience", entry.audience()); + digestFields.put("probeKind", entry.probeKind().name()); + digestFields.put("podUid", expectedPod.target().podUid()); + digestFields.put("jti", entry.jti().toString()); + digestFields.put("sourceEntryVersion", entry.entryVersion()); + digestFields.put("compactTokenSha256", entry.compactTokenSha256().orElseThrow()); + digestFields.put("targetGeneration", entry.targetGeneration()); + digestFields.put("targetKid", entry.targetKid()); + Map expectedActive = new LinkedHashMap<>(); + expectedActive.put("present", entry.expectedActive().isPresent()); + entry + .expectedActive() + .ifPresent( + active -> { + expectedActive.put("generation", active.generation()); + expectedActive.put("kid", active.kid()); + }); + digestFields.put("expectedActive", expectedActive); + digestFields.put("outcome", acceptance.result().name()); + digestFields.put("observedPodUid", acceptance.podUid()); + digestFields.put("image", acceptance.image()); + digestFields.put("verifierConfigSha256", acceptance.verifierConfigSha256()); + digestFields.put("verifiedKid", acceptance.verifiedKid()); + digestFields.put("receiverEndpoint", URI.create(acceptance.actualPodEndpoint()).toString()); + digestFields.put("receiverServiceUri", acceptance.actualServiceUri()); + digestFields.put("receiverPeerSpkiSha256", acceptance.actualPeerSpkiSha256()); + digestFields.put("observedAtEpochSecond", acceptance.observedAtEpochSecond()); + String receiptDigest; + try { + receiptDigest = + sha256(Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(digestFields))); + } catch (Exception failure) { + throw new AssertionError("Raw per-Pod receipt fixture could not be canonicalized", failure); + } + var target = expectedPod.target(); + context + .dsl() + .execute( + "INSERT INTO account_jwt_readiness_pod_receipts (" + + "rotation_operation_id, plan_digest, validator_id, token_profile, audience, " + + "probe_kind, pod_uid, receipt_version, jti, source_entry_version, " + + "compact_token_sha256, target_generation, target_kid, expected_active_generation, " + + "expected_active_kid, outcome, observed_pod_uid, observed_image, " + + "observed_verifier_config_sha256, verified_kid, receiver_endpoint, " + + "receiver_service_uri, receiver_peer_spki_sha256, observed_at_epoch_seconds, receipt_sha256) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + entry.rotationOperationId(), + entry.planDigest(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind().name(), + UUID.fromString(target.podUid()), + entry.jti(), + entry.entryVersion(), + entry.compactTokenSha256().orElseThrow(), + Long.parseLong(entry.targetGeneration()), + entry.targetKid(), + entry.expectedActive().map(value -> Long.parseLong(value.generation())).orElse(null), + entry.expectedActive().map(value -> value.kid()).orElse(null), + acceptance.result().name(), + UUID.fromString(acceptance.podUid()), + acceptance.image(), + acceptance.verifierConfigSha256(), + acceptance.verifiedKid(), + acceptance.actualPodEndpoint(), + acceptance.actualServiceUri(), + acceptance.actualPeerSpkiSha256(), + acceptance.observedAtEpochSecond(), + receiptDigest); + } + + private static void assertReadinessVerifiedTransitionRejectsChangedSigningAttempt( + TestContext context, + ProbeEntry issuedEntry, + int expectedPodCount, + long verifiedAtEpochSecond) { + String alteredReceiptDigest = "f".repeat(64); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> { + context + .dsl() + .execute( + "UPDATE account_jwt_readiness_probe_entries SET " + + "state = 'VERIFIED', entry_version = entry_version + 1, " + + "signing_attempted_at_epoch_seconds = " + + "signing_attempted_at_epoch_seconds + 1, " + + "verification_receipt_version = 2, " + + "verification_source_entry_version = entry_version, " + + "verified_at_epoch_seconds = ?, verified_kid = target_kid, " + + "validator_instance_id = 'raw-sql-validator-1', " + + "validator_binding_digest = ?, " + + "validator_config_revision = 'config-r1', " + + "validator_peer_uri = ?, validator_peer_spki_sha256 = ?, " + + "verification_receipt_sha256 = ?, pod_receipt_count = ?, " + + "pod_receipt_closure_sha256 = ? " + + "WHERE rotation_operation_id = ? AND validator_id = ? " + + "AND token_profile = ? AND audience = ? AND probe_kind = ?", + verifiedAtEpochSecond, + "d".repeat(64), + "spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator", + "e".repeat(64), + alteredReceiptDigest, + expectedPodCount, + alteredReceiptDigest, + issuedEntry.rotationOperationId(), + issuedEntry.validatorId(), + issuedEntry.tokenProfile(), + issuedEntry.audience(), + issuedEntry.probeKind().name()); + return null; + })) + .satisfies(failure -> assertThat(postgresSqlState(failure)).isEqualTo("23514")); + + var retainedEntry = + context + .dsl() + .fetchOne( + "SELECT state, signing_attempted_at_epoch_seconds " + + "FROM account_jwt_readiness_probe_entries " + + "WHERE rotation_operation_id = ? AND validator_id = ? AND token_profile = ? " + + "AND audience = ? AND probe_kind = ?", + issuedEntry.rotationOperationId(), + issuedEntry.validatorId(), + issuedEntry.tokenProfile(), + issuedEntry.audience(), + issuedEntry.probeKind().name()); + assertThat(retainedEntry).isNotNull(); + assertThat(retainedEntry.get("state", String.class)).isEqualTo("ISSUED"); + assertThat(retainedEntry.get("signing_attempted_at_epoch_seconds", Long.class)) + .isEqualTo(issuedEntry.signingAttemptedAtEpochSecond().orElseThrow()); + } + + private static String postgresSqlState(Throwable failure) { + Throwable current = failure; + while (current != null) { + if (current instanceof PSQLException postgresFailure) { + return postgresFailure.getSQLState(); + } + current = current.getCause(); + } + return null; + } + + private static String postgresServerMessage(Throwable failure) { + Throwable current = failure; + while (current != null) { + if (current instanceof PSQLException postgresFailure) { + var serverError = postgresFailure.getServerErrorMessage(); + return serverError == null ? postgresFailure.getMessage() : serverError.getMessage(); + } + current = current.getCause(); + } + return String.valueOf(failure.getMessage()); + } + + private static long databaseNow(TestContext context) { + return java.util.Objects.requireNonNull( + context + .dsl() + .resultQuery("SELECT floor(extract(epoch FROM CURRENT_TIMESTAMP))::bigint") + .fetchOne(0, Long.class), + "Database clock query returned no row."); + } + + private static void awaitDatabaseClockAtOrAfter(TestContext context, long epochSecond) { + Awaitility.await() + .alias("PostgreSQL clock reaches the immutable readiness plan expiry") + .pollInterval(Duration.ofMillis(100)) + .atMost(Duration.ofSeconds(DISPATCHED_RECOVERY_EXPIRY_WAIT_SECONDS)) + .until(() -> databaseClockNow(context) >= epochSecond); + } + + private static long databaseClockNow(TestContext context) { + return java.util.Objects.requireNonNull( + context + .dsl() + .resultQuery("SELECT floor(extract(epoch FROM clock_timestamp()))::bigint") + .fetchOne(0, Long.class), + "Database clock query returned no row."); + } + + private static AuthenticatedAcceptance testAcceptance( + ProbeEntry entry, ExpectedPod expectedPod, long observedAtEpochSecond) { + return testAcceptance(entry, expectedPod, observedAtEpochSecond, entry.targetKid()); + } + + private static AuthenticatedAcceptance testAcceptance( + ProbeEntry entry, ExpectedPod expectedPod, long observedAtEpochSecond, String verifiedKid) { + return testAcceptance( + entry, + expectedPod, + observedAtEpochSecond, + verifiedKid, + expectedPod.target().exactPodEndpoint().orElseThrow().toString()); + } + + private static AuthenticatedAcceptance testAcceptance( + ProbeEntry entry, + ExpectedPod expectedPod, + long observedAtEpochSecond, + String verifiedKid, + String actualPodEndpoint) { + var target = expectedPod.target(); + return AccountJwtReadinessReceiverInvocationPort.authenticatedAcceptance( + target.podUid(), + actualPodEndpoint, + target.image(), + target.verifierConfigSha256(), + target.canonicalServiceUri().orElseThrow(), + target.podLeafSpkiSha256().orElseThrow(), + entry.jti(), + entry.compactTokenSha256().orElseThrow(), + verifiedKid, + target.expectation(), + observedAtEpochSecond); + } + + private static AccountJwtReadinessProbeOwnerSelector ownerSelector( + ReadinessProbePlan plan, ProbeEntry entry, ExpectedPod expectedPod) { + return ownerSelector(plan, entry, expectedPod, entry.expectedActive()); + } + + private static AccountJwtReadinessProbeOwnerSelector ownerSelector( + ReadinessProbePlan plan, + ProbeEntry entry, + ExpectedPod expectedPod, + Optional activeFence) { + return ownerSelector(plan, entry, expectedPod, activeFence, "inventory-r1", "d".repeat(64)); + } + + private static AccountJwtReadinessProbeOwnerSelector ownerSelector( + ReadinessProbePlan plan, + ProbeEntry entry, + ExpectedPod expectedPod, + Optional activeFence, + String sourceInventoryRevision, + String sourceInventoryDigest) { + var target = expectedPod.target(); + LocalIdentity localIdentity = + new LocalIdentity( + target.validatorId(), + target.deploymentUid(), + target.podUid(), + target.podIp(), + target.exactPodEndpoint().orElseThrow().toString(), + target.canonicalServiceUri().orElseThrow(), + target.image(), + target.verifierConfigSha256(), + target.applicabilityMatrixDigest(), + sourceInventoryRevision, + sourceInventoryDigest, + target.podLeafSpkiSha256().orElseThrow()); + return new AccountJwtReadinessProbeOwnerSelector( + plan.operationId(), + plan.operationDigest(), + plan.planDigest(), + plan.planVersion(), + entry.registryVersion(), + entry.validatorId(), + entry.tokenProfile(), + entry.audience(), + entry.probeKind(), + target.expectation(), + entry.jti(), + entry.entryVersion(), + entry.targetGeneration(), + entry.targetKid(), + activeFence, + entry.plannedIssuedAtEpochSecond(), + entry.expiresAtEpochSecond(), + plan.expiresAtEpochSecond(), + entry.compactTokenSha256().orElseThrow(), + localIdentity); + } + + 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) { + String accountImage = "registry.example/account-validator@sha256:" + "1".repeat(64); + String gameSessionImage = "registry.example/game-session-validator@sha256:" + "3".repeat(64); + String accountConfigDigest = "2".repeat(64); + String gameSessionConfigDigest = "4".repeat(64); + String accountServiceUri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator"; + String gameSessionServiceUri = "spiffe://firemud/ns/firemud-prod/sa/game-session-jwt-validator"; + List accountProfiles = + List.of( + new ProfileExpectation("control-ui", "control-ui"), + new ProfileExpectation("game-session-account-delegation", "account-service"), + new ProfileExpectation("player-bootstrap", "player-bootstrap")); + List gameSessionProfiles = + List.of(new ProfileExpectation("game-session-account-delegation", "account-service")); + List accountPods = + List.of( + inventoryPod( + "account-a", + "77777777-7777-4777-8777-777777777777", + "account-rs", + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "acct1", + firstAccountPodIp, + 9443, + accountImage, + accountConfigDigest, + accountServiceUri, + "5".repeat(64)), + inventoryPod( + "account-b", + "88888888-8888-4888-8888-888888888888", + "account-rs", + "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", + "acct1", + "10.11.0.12", + 9443, + accountImage, + accountConfigDigest, + accountServiceUri, + "6".repeat(64))); + List gameSessionPods = + List.of( + inventoryPod( + "game-session-a", + "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", + "game-session-rs", + "cccccccc-cccc-4ccc-8ccc-cccccccccccc", + "games", + "10.12.0.11", + 9444, + gameSessionImage, + gameSessionConfigDigest, + gameSessionServiceUri, + "7".repeat(64))); + List validators = + List.of( + new ValidatorObservation( + "account-service", + "account-service", + "66666666-6666-4666-8666-666666666666", + 1L, + "51", + 2, + accountImage, + accountConfigDigest, + 300, + accountProfiles, + accountPods, + List.of()), + new ValidatorObservation( + "game-session-service", + "game-session-service", + "99999999-9999-4999-8999-999999999999", + 1L, + "52", + 1, + gameSessionImage, + gameSessionConfigDigest, + 300, + gameSessionProfiles, + gameSessionPods, + List.of())); + List> validatorMaps = + List.of( + inventoryValidatorMap(validators.get(0), accountServiceUri, 9443), + inventoryValidatorMap(validators.get(1), gameSessionServiceUri, 9444)); + Map preimage = new LinkedHashMap<>(); + preimage.put("domain", "firemud-account-validator-inventory/v2"); + preimage.put("environmentId", BINDING.environmentId()); + preimage.put("clusterId", BINDING.clusterId()); + preimage.put("clusterIncarnationUid", 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", "d".repeat(64)); + preimage.put( + "observationContext", + Map.of( + "purpose", observationContext.purpose().name(), + "operationId", observationContext.operationId().toString(), + "operationDigest", observationContext.operationDigest())); + preimage.put("validators", validatorMaps); + byte[] bytes; + try { + bytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(preimage)); + } catch (Exception failure) { + throw new AssertionError(failure); + } + InventorySnapshot snapshot = mock(InventorySnapshot.class); + when(snapshot.observedAt()).thenReturn(observedAt); + when(snapshot.environmentId()).thenReturn(BINDING.environmentId()); + when(snapshot.clusterId()).thenReturn(BINDING.clusterId()); + when(snapshot.clusterIncarnationUid()).thenReturn(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("d".repeat(64)); + when(snapshot.observationContext()).thenReturn(Optional.of(observationContext)); + when(snapshot.validators()).thenReturn(validators); + when(snapshot.canonicalBytes()).thenReturn(bytes.clone()); + when(snapshot.digest()).thenReturn(sha256(bytes)); + return snapshot; + } + + private 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 String privateBundleJson( + GenerationRequest request, GenerationResult result, KeyPair pair) { + Map bundle = new LinkedHashMap<>(); + bundle.put("version", 1); + bundle.put("environmentId", request.binding().environmentId()); + bundle.put("clusterId", request.binding().clusterId()); + bundle.put("namespace", request.binding().namespace()); + bundle.put("operationId", request.operationId().toString()); + bundle.put("generation", result.targetGeneration()); + bundle.put("kid", result.targetKid()); + bundle.put("algorithm", "RS256"); + bundle.put( + "privateKeyPkcs8", + Base64.getUrlEncoder().withoutPadding().encodeToString(pair.getPrivate().getEncoded())); + bundle.put("publicKeyFingerprint", result.publicKeyFingerprint()); + try { + return JSON.writeValueAsString(bundle); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } + + private static String generationMarker(GenerationResult result) throws Exception { + 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", API_DIGEST); + binding.put("apiConfigRevision", API_REVISION); + marker.put("binding", binding); + marker.put("publicConfigMap", Map.of("name", "jwt-jwks")); + marker.put("expectedDurableActive", Map.of("present", false)); + marker.put("expectedPublishedActive", Map.of("present", false)); + marker.put( + "pending", + Map.of( + "generation", + result.targetGeneration(), + "kid", + result.targetKid(), + "algorithm", + result.targetAlgorithm(), + "publicKeyFingerprint", + result.publicKeyFingerprint())); + return canonicalJson(marker); + } + + 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 jwks(String retainedJwk, String targetJwk) { + return "{\"keys\":[" + retainedJwk + "," + targetJwk + "]}"; + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + private static KeyPair generateRsa3072() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3_072); + return generator.generateKeyPair(); + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.NoSuchAlgorithmException failure) { + throw new IllegalStateException("SHA-256 is required for the persistence fixture", failure); + } + } + + private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + + private record OwnerState( + AccountJwtSignerDesiredStateRepository desired, + AccountJwtJwksPublicationRepository publication, + AccountJwtValidatorInventoryRepository inventory, + AccountJwtReadinessProbeRepository readiness, + TrustFence trust, + GenerationRequest request, + GenerationResult result, + KeyPair keyPair, + String desiredJwks) {} + + private record TestContext( + String schema, + javax.sql.DataSource dataSource, + TransactionTemplate transaction, + DSLContext dsl) {} +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java new file mode 100644 index 0000000000..3fa03a6257 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java @@ -0,0 +1,165 @@ +package net.firedevops.firemud.accountservice.authordraft; + +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.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CurrentnessEvidence; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.EnvironmentBoundCurrentness; +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.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; +import org.junit.jupiter.api.Test; + +class AccountControlUiAuthorityTest { + @Test + void retainsFenceSourceVersionIndependentlyFromActualFenceValue() { + UUID account = UUID.randomUUID(); + var first = AccountControlUiAuthority.requireIssuanceFenceSource(member(account, 4L, 12L)); + var advanced = AccountControlUiAuthority.requireIssuanceFenceSource(member(account, 4L, 13L)); + + assertThat(first.value()).isEqualTo(4L); + assertThat(first.sourceVersion()).isEqualTo(12L); + assertThat(advanced.value()).isEqualTo(first.value()); + assertThat(advanced.sourceVersion()).isEqualTo(13L); + } + + @Test + void rejectsFenceSourceThatDoesNotMatchTheAuthenticatedMemberValue() { + UUID account = UUID.randomUUID(); + var member = member(account, 4L, 12L, 5L); + + assertThatThrownBy(() -> AccountControlUiAuthority.requireIssuanceFenceSource(member)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("issuance fence source"); + } + + @Test + void typedIssuanceFenceRejectsNonPositiveSourceVersion() { + assertThatThrownBy(() -> new IssuanceFence(UUID.randomUUID(), 4L, 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must be positive"); + } + + private static CreatorControlCaptureSources member(UUID account, long fence, long sourceVersion) { + return member(account, fence, sourceVersion, fence); + } + + private static CreatorControlCaptureSources member( + UUID account, long fence, long sourceVersion, long authenticatedMemberFence) { + var issuerFence = new IssuanceFence(account, fence, sourceVersion); + var issuer = new ScopeState(AuthorityScope.issuer("firemud-account-service"), 1L, 1L, null); + var accountState = new ScopeState(AuthorityScope.account(account), 1L, 1L, issuerFence); + var snapshot = new CompositeSnapshot(issuer, accountState, List.of(), List.of(), issuerFence); + return new CreatorControlCaptureSources( + account, + UUID.randomUUID(), + snapshot, + Map.of(), + null, + Long.toString(authenticatedMemberFence), + null, + null, + null, + null, + null, + List.of(), + List.of(), + Instant.EPOCH); + } + + @Test + void explicitTypedNoDeadlineReadbackPermitsExistingCompositionToContinue() { + var sources = mock(AccountDraftSourceCompositionService.class); + var existing = mock(AccountDraftSourceCompositionService.ExistingSources.class); + var hosted = mock(EnvironmentBoundCurrentness.class); + var terms = mock(CurrentnessEvidence.class); + var environment = mock(CapturedEnvironmentBoundary.class); + UUID tenant = UUID.randomUUID(); + when(sources.readExistingSources(environment, tenant)).thenReturn(existing); + when(existing.hostedTerms()).thenReturn(hosted); + when(hosted.terms()).thenReturn(terms); + when(terms.validUntil()).thenReturn(null); + when(terms.disclosedDeadline()).thenReturn(null); + // Stop at the next stage: this is not a fabricated successful source/provenance fixture. + when(existing.membership()) + .thenThrow(new IllegalStateException("membership-stage-test-sentinel")); + var authority = new AccountControlUiAuthority(sources); + assertThatThrownBy(() -> authority.capture(UUID.randomUUID(), tenant, environment)) + .hasMessage("membership-stage-test-sentinel"); + assertThatThrownBy(() -> authority.captureInitial(tenant, environment)) + .hasMessage("membership-stage-test-sentinel"); + } + + @Test + void bothCapturePathsDenyDeadlineQualifiedOwnerReadbackBeforeMembershipOrSourceCapture() { + // Explicit owner service doubles: this tests the enforcement boundary, not source provenance. + var sources = mock(AccountDraftSourceCompositionService.class); + var existing = mock(AccountDraftSourceCompositionService.ExistingSources.class); + var hosted = mock(EnvironmentBoundCurrentness.class); + var terms = mock(CurrentnessEvidence.class); + var environment = mock(CapturedEnvironmentBoundary.class); + UUID tenant = UUID.randomUUID(); + when(sources.readExistingSources(environment, tenant)).thenReturn(existing); + when(existing.hostedTerms()).thenReturn(hosted); + when(hosted.terms()).thenReturn(terms); + when(terms.validUntil()).thenReturn(Instant.parse("2099-01-01T00:00:00Z")); + var authority = new AccountControlUiAuthority(sources); + + assertThatThrownBy(() -> authority.capture(UUID.randomUUID(), tenant, environment)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Deadline-qualified"); + assertThatThrownBy(() -> authority.captureInitial(tenant, environment)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Deadline-qualified"); + verify(existing, never()).membership(); + verify(hosted, never()).sourceEvidence(); + } + + @Test + void absentTypedOwnerCurrentnessCannotMasqueradeAsNoDeadline() { + var sources = mock(AccountDraftSourceCompositionService.class); + var existing = mock(AccountDraftSourceCompositionService.ExistingSources.class); + var hosted = mock(EnvironmentBoundCurrentness.class); + var environment = mock(CapturedEnvironmentBoundary.class); + UUID tenant = UUID.randomUUID(); + when(sources.readExistingSources(environment, tenant)).thenReturn(existing); + when(existing.hostedTerms()).thenReturn(hosted); + var authority = new AccountControlUiAuthority(sources); + assertThatThrownBy(() -> authority.capture(UUID.randomUUID(), tenant, environment)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> authority.captureInitial(tenant, environment)) + .isInstanceOf(NullPointerException.class); + verify(existing, never()).membership(); + } + + @Test + void canonicalizationPreservesExactlyRepresentableNestedCounters() { + var bytes = + AccountControlUiAuthority.canonical( + Map.of("tuple", List.of(Map.of("counter", 42L), Map.of("counter", 9007199254740992L)))); + assertThat(new String(bytes, StandardCharsets.UTF_8)).contains("9007199254740992", "42"); + } + + @Test + void canonicalizationRejectsArithmeticChangeInsteadOfIssuingRoundedAuthority() { + for (long counter : new long[] {9007199254740993L, Long.MAX_VALUE}) { + assertThatThrownBy( + () -> + AccountControlUiAuthority.canonical( + Map.of("tuple", List.of(Map.of("counter", counter))))) + .isInstanceOf(IllegalArgumentException.class); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionServiceTest.java new file mode 100644 index 0000000000..72a32185f7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionServiceTest.java @@ -0,0 +1,375 @@ +package unit.net.firedevops.firemud.accountservice.authordraft; + +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.doAnswer; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountDraftSourceCompositionService; +import net.firedevops.firemud.accountservice.creatorparty.CreatorPartyEncoding; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.AssociationReceipt; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.InitialAssociationReadback; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartyRepository.InitialAssociationScope; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource; +import net.firedevops.firemud.accountservice.creatorparty.IndividualCreatorPartySource.VerificationStatus; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CurrentnessEvidence; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.EnvironmentBoundCurrentness; +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.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceCheckpoint; +import net.firedevops.firemud.accountservice.repository.AccountTenantCreationBootstrapOperationRepository.StoredOperation; +import net.firedevops.firemud.accountservice.service.AccountGenerationProjection; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.CreatorControlCaptureSources; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxCheckpointEntry; +import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer.OutboxSourceEvidence; +import net.firedevops.firemud.accountservice.service.AccountTenantCreationBootstrapService; +import net.firedevops.firemud.accountservice.service.IssuerGenerationProjection; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +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.jooq.ConnectionRunnable; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mock owner-boundary composition proof; physical lock contention requires PostgreSQL proof. */ +class AccountDraftSourceCompositionServiceTest { + @AfterEach + void clearTransaction() { + TransactionSynchronizationManager.clear(); + } + + @Test + void composesInOwnerOrderAndPreservesSequenceZeroBirthEvidence() throws Exception { + Fixture f = new Fixture(); + var capture = f.read(); + assertThat(capture.membership()).isSameAs(f.membership); + assertThat(capture.issuerAccount()).isSameAs(f.source); + assertThat(capture.association()).isEqualTo(f.association); + assertThat(capture.hostedTerms()).isSameAs(f.currentTerms); + var order = inOrder(f.parties, f.memberships, f.upstream, f.terms); + order.verify(f.parties).lockExistingInitialAssociationScope(f.tenant); + order.verify(f.memberships).readExistingCreatorControlCaptureSources(f.account, f.tenant); + order.verify(f.upstream).readCurrentIssuerAccountSources("firemud-account-service", f.account); + order.verify(f.terms).requireCurrentnessInOwnerTransaction(f.environment, f.partyId); + order.verify(f.parties).readExistingInitialAssociation(f.tenant); + order.verifyNoMoreInteractions(); + } + + @Test + void deniesMissingReadOnlyAutocommitAndWrongPhysicalIsolationBeforeSources() throws Exception { + Fixture f = new Fixture(); + assertThatThrownBy(() -> f.service.readExistingSources(f.environment, f.tenant)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + assertThatThrownBy(() -> f.service.readExistingSources(f.environment, f.tenant)) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + when(f.connection.getAutoCommit()).thenReturn(true); + f.rejects(); + when(f.connection.getAutoCommit()).thenReturn(false); + when(f.connection.isReadOnly()).thenReturn(true); + f.rejects(); + when(f.connection.isReadOnly()).thenReturn(false); + when(f.connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_REPEATABLE_READ); + f.rejects(); + verifyNoInteractions(f.parties, f.memberships, f.upstream, f.terms); + } + + @Test + void failedMembershipPrerequisiteCannotReachUpstreamTermsOrFinalReadback() throws Exception { + Fixture f = new Fixture(); + when(f.memberships.readExistingCreatorControlCaptureSources(f.account, f.tenant)) + .thenThrow(new IllegalStateException("Absent current membership")); + f.rejects(); + verifyNoInteractions(f.upstream, f.terms); + org.mockito.Mockito.verify(f.parties, org.mockito.Mockito.never()) + .readExistingInitialAssociation(any()); + } + + @Test + void changedAccountSourceAndIssuanceFenceDenyBeforeTerms() throws Exception { + Fixture changedSource = new Fixture(); + when(changedSource.issuer.generation()).thenReturn(2L); + changedSource.rejects(); + verifyNoInteractions(changedSource.terms); + Fixture changedFence = new Fixture(); + when(changedFence.source.issuanceFence()) + .thenReturn(new IssuanceFence(changedFence.account, 2L, 2L)); + changedFence.rejects(); + verifyNoInteractions(changedFence.terms); + } + + @Test + void foreignTermsOwnerDeniesBeforeAssociationReadback() throws Exception { + Fixture f = new Fixture(); + when(f.currentness.accountId()).thenReturn(UUID.randomUUID()); + f.rejects(); + org.mockito.Mockito.verify(f.parties, org.mockito.Mockito.never()) + .readExistingInitialAssociation(any()); + } + + @Test + void changedTenantDeniesBeforeUpstreamOrTerms() throws Exception { + Fixture f = new Fixture(); + when(f.membership.tenantUuid()).thenReturn(UUID.randomUUID()); + f.rejects(); + verifyNoInteractions(f.upstream, f.terms); + } + + @Test + void comparesCollaboratorPositiveEventBytesWithoutClaimingCodecOrProducerProof() + throws Exception { + // Synthetic collaborator event: equality proof only, not a valid owner-event codec fixture. + Fixture f = new Fixture(); + var authority = f.membership.authoritySnapshot(); + String stream = f.issuer.checkpoint().outboxStreamKey(); + String accountStream = f.accountSource.checkpoint().outboxStreamKey(); + String digest = "sha256:" + "b".repeat(64); + when(f.issuer.generation()).thenReturn(2L); + when(f.issuer.sourceVersion()).thenReturn(2L); + when(f.issuer.checkpoint()) + .thenReturn(new SourceCheckpoint(stream, 1L, Optional.of("event"), Optional.of(digest))); + when(f.membership.authoritySnapshot()) + .thenReturn( + new CompositeSnapshot( + new ScopeState(authority.issuer().scope(), 2L, 2L, null), + authority.account(), + authority.tenants(), + authority.memberships(), + authority.issuanceFence())); + when(f.membership.outboxCheckpoints()) + .thenReturn( + List.of( + new OutboxCheckpointEntry(stream, "1"), + new OutboxCheckpointEntry(accountStream, "0"))); + when(f.membership.outboxSourceEvidence()) + .thenReturn( + List.of(new OutboxSourceEvidence(stream, "1", "event", digest, "{\"fixture\":1}"))); + when(f.source.canonicalIssuerProjection().sourceEvent()) + .thenReturn(Optional.of("{\"fixture\":1}")); + assertThat(f.read().issuerAccount()).isSameAs(f.source); + when(f.source.canonicalIssuerProjection().sourceEvent()) + .thenReturn(Optional.of("{\"fixture\":2}")); + f.rejects(); + } + + @Test + void changedAssociationHistoryAndExactPartySourceDeny() throws Exception { + Fixture changedHistory = new Fixture(); + when(changedHistory.parties.readExistingInitialAssociation(changedHistory.tenant)) + .thenReturn( + new InitialAssociationReadback( + changedHistory.creator, + new AssociationReceipt( + UUID.randomUUID(), + changedHistory.tenant, + changedHistory.partyId, + UUID.randomUUID(), + "retained-history"), + changedHistory.party)); + changedHistory.rejects(); + Fixture changedParty = new Fixture(); + when(changedParty.currentTerms.sourceEvidence()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.CREATOR_PARTY, + changedParty.partyId.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + changedParty.rejects(); + } + + private static final class Fixture { + private final UUID tenant = UUID.randomUUID(); + private final UUID account = UUID.randomUUID(); + private final UUID partyId = UUID.randomUUID(); + private final UUID request = UUID.randomUUID(); + private final UUID bootstrapId = UUID.randomUUID(); + private final DSLContext dsl = mock(DSLContext.class); + private final Connection connection = mock(Connection.class); + private final IndividualCreatorPartyRepository parties = + mock(IndividualCreatorPartyRepository.class); + private final AccountTenantCreationBootstrapService memberships = + mock(AccountTenantCreationBootstrapService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountAuthoritySourceEvidenceRepository upstream = + mock(AccountAuthoritySourceEvidenceRepository.class); + private final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + private final CreatorControlCaptureSources membership = + mock(CreatorControlCaptureSources.class); + private final IssuerAccountSourceSnapshot source = mock(IssuerAccountSourceSnapshot.class); + private final CurrentSourceEvidence issuer = mock(CurrentSourceEvidence.class); + private final CurrentSourceEvidence accountSource = mock(CurrentSourceEvidence.class); + private final EnvironmentBoundCurrentness currentTerms = + mock(EnvironmentBoundCurrentness.class); + private final CurrentnessEvidence currentness = mock(CurrentnessEvidence.class); + private final IndividualCreatorPartySource party = + new IndividualCreatorPartySource( + partyId, + account, + VerificationStatus.VERIFIED, + 1L, + "policy", + 1L, + "verification", + 1L, + 1L); + private final FreshTenantCreatorEvidence creator; + private final InitialAssociationReadback association; + private final AccountDraftSourceCompositionService service; + + private Fixture() throws Exception { + when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_READ_COMMITTED); + doAnswer( + invocation -> { + invocation.getArgument(0).run(connection); + return null; + }) + .when(dsl) + .connection(any(ConnectionRunnable.class)); + UUID creationRequest = UUID.randomUUID(); + UUID operation = UUID.randomUUID(); + String digest = + GameTenantCreationDigest.requestDigest("test", creationRequest, "game", "Game", null); + var creation = + new FreshTenantCreationEvidence( + 1, + "test", + creationRequest, + operation, + digest, + tenant, + 1L, + "game", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( + "test", creationRequest, operation, digest, tenant, 1L, "game", "NEW_GAME_ROW")); + String authDigest = "sha256:" + "a".repeat(64); + creator = + new FreshTenantCreatorEvidence( + 1, + creation, + account, + bootstrapId, + authDigest, + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, account, bootstrapId, authDigest)); + association = + new InitialAssociationReadback( + creator, + new AssociationReceipt(request, tenant, partyId, UUID.randomUUID(), "history"), + party); + when(parties.lockExistingInitialAssociationScope(tenant)) + .thenReturn(new InitialAssociationScope(tenant, request, account, partyId)); + when(parties.readExistingInitialAssociation(tenant)).thenReturn(association); + when(memberships.readExistingCreatorControlCaptureSources(account, tenant)) + .thenReturn(membership); + when(membership.accountUuid()).thenReturn(account); + when(membership.tenantUuid()).thenReturn(tenant); + when(membership.creationSource()).thenReturn(creation); + var bootstrap = mock(StoredOperation.class); + when(membership.bootstrapReceipt()).thenReturn(bootstrap); + when(bootstrap.requestId()).thenReturn(bootstrapId); + when(bootstrap.accountAuthorizationOperationId()).thenReturn(bootstrapId); + when(bootstrap.accountAuthorizationDigest()).thenReturn(authDigest); + when(bootstrap.creatorEvidenceDigest()).thenReturn(creator.evidenceDigest()); + when(bootstrap.creatorEvidencePayload()).thenReturn(CreatorPartyEncoding.creation(creator)); + var fence = new IssuanceFence(account, 1L, 1L); + var issuerScope = AuthorityScope.issuer("firemud-account-service"); + var accountScope = AuthorityScope.account(account); + when(membership.authoritySnapshot()) + .thenReturn( + new CompositeSnapshot( + new ScopeState(issuerScope, 1L, 1L, null), + new ScopeState(accountScope, 1L, 1L, fence), + List.of(), + List.of(), + fence)); + when(membership.issuanceFence()).thenReturn("1"); + when(source.issuanceFence()).thenReturn(fence); + when(source.issuer()).thenReturn(issuer); + when(source.account()).thenReturn(accountSource); + String issuerStream = "account:auth-authority:v1:issuer/firemud-account-service"; + String accountStream = "account:auth-authority:v1:account/" + account; + configureSource(issuer, issuerScope, null, issuerStream); + configureSource(accountSource, accountScope, fence, accountStream); + when(membership.outboxCheckpoints()) + .thenReturn( + List.of( + new OutboxCheckpointEntry(issuerStream, "0"), + new OutboxCheckpointEntry(accountStream, "0"))); + when(membership.outboxSourceEvidence()).thenReturn(List.of()); + var issuerProjection = mock(IssuerGenerationProjection.class); + var accountProjection = mock(AccountGenerationProjection.class); + when(issuerProjection.sourceEvent()).thenReturn(Optional.empty()); + when(accountProjection.sourceEvent()).thenReturn(Optional.empty()); + when(source.canonicalIssuerProjection()).thenReturn(issuerProjection); + when(source.canonicalAccountProjection()).thenReturn(accountProjection); + when(upstream.readCurrentIssuerAccountSources("firemud-account-service", account)) + .thenReturn(source); + when(terms.requireCurrentnessInOwnerTransaction(environment, partyId)) + .thenReturn(currentTerms); + when(currentTerms.terms()).thenReturn(currentness); + when(currentness.accountId()).thenReturn(account); + when(currentness.creatorPartyId()).thenReturn(partyId); + when(currentTerms.sourceEvidence()) + .thenReturn( + List.of( + new SourceEvidence( + SourceKind.CREATOR_PARTY, + partyId.toString(), + "1", + "1", + null, + null, + CreatorPartyEncoding.party(party)))); + service = + new AccountDraftSourceCompositionService(dsl, parties, memberships, terms, upstream); + } + + private void configureSource( + CurrentSourceEvidence value, AuthorityScope scope, IssuanceFence fence, String stream) { + when(value.scope()).thenReturn(scope); + when(value.generation()).thenReturn(1L); + when(value.sourceVersion()).thenReturn(1L); + when(value.issuanceFence()).thenReturn(fence); + when(value.checkpoint()) + .thenReturn(new SourceCheckpoint(stream, 0L, Optional.empty(), Optional.empty())); + } + + private AccountDraftSourceCompositionService.ExistingSources read() { + TransactionSynchronizationManager.setActualTransactionActive(true); + return service.readExistingSources(environment, tenant); + } + + private void rejects() { + assertThatThrownBy(this::read).isInstanceOf(IllegalStateException.class); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java new file mode 100644 index 0000000000..9fb4d37984 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java @@ -0,0 +1,312 @@ +package net.firedevops.firemud.accountservice.config; + +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.nio.file.attribute.PosixFilePermission; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +class AccountJwtReadinessTrustBindingTest { + private static final long NOW = 1_800_000_000L; + + @TempDir Path tempDirectory; + + @Test + void missingOrDisabledConfigurationNeverCreatesReadinessTrust() { + assertThat(new AccountJwtReadinessTrustBinding(false, "/unused", Clock.systemUTC()).current()) + .isEmpty(); + assertThat(new AccountJwtReadinessTrustBinding(true, "", Clock.systemUTC()).current()) + .isEmpty(); + } + + @Test + void strictBindingPinsAccountRuntimeAndDedicatedHarnessIdentity() { + var binding = + AccountJwtReadinessTrustBinding.parseProtectedBytes( + protectedConfig(NOW + 60).getBytes(StandardCharsets.UTF_8), NOW); + + assertThat(binding.environmentId()).isEqualTo("prod"); + assertThat(binding.clusterId()).isEqualTo("prod-cluster-1"); + assertThat(binding.namespace()).isEqualTo("firemud-prod"); + assertThat(binding.expectedPeerUri()) + .isEqualTo("spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"); + assertThat(binding.validatorId()).isEqualTo("account-service"); + assertThat(binding.validatorInstanceId()).isEqualTo("account-validator-instance-7"); + assertThat(binding.validUntilEpochSecond()).isEqualTo(NOW + 60); + assertThat(binding.isCurrentAt(NOW)).isTrue(); + assertThat(binding.isCurrentAt(NOW + 60)).isFalse(); + } + + @Test + void missingExpiredDuplicateUnknownAndChangedIdentityBindingsAreRejected() { + String valid = protectedConfig(NOW + 60); + assertThatThrownBy( + () -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + valid.getBytes(StandardCharsets.UTF_8), NOW + 60)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + (valid + "validatorInstanceId=other\n").getBytes(StandardCharsets.UTF_8), NOW)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + (valid + "untrusted=true\n").getBytes(StandardCharsets.UTF_8), NOW)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + valid + .replace( + "validatorInstanceId=account-validator-instance-7", + "validatorInstanceId=other") + .getBytes(StandardCharsets.UTF_8), + NOW)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + valid.replace("enabled=true", "enabled=false").getBytes(StandardCharsets.UTF_8), + NOW)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void acceptsRootOwnedOwnerWritableDirectoryButRejectsWritableProtectedFile() throws Exception { + Path directory = Files.createDirectory(tempDirectory.resolve("protected")); + Path binding = directory.resolve("binding.conf"); + Files.writeString(binding, protectedConfig(NOW + 60), StandardCharsets.UTF_8); + Assumptions.assumeTrue(((Number) Files.getAttribute(directory, "unix:uid")).longValue() == 0L); + Assumptions.assumeTrue(((Number) Files.getAttribute(binding, "unix:uid")).longValue() == 0L); + Assumptions.assumeTrue(hasProtectedDirectoryAncestors(directory)); + Files.setPosixFilePermissions( + directory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE)); + Files.setPosixFilePermissions( + binding, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ)); + + assertThat( + new AccountJwtReadinessTrustBinding( + true, + binding.toString(), + Clock.fixed(Instant.ofEpochSecond(NOW), ZoneOffset.UTC)) + .current()) + .isPresent(); + + Files.setPosixFilePermissions( + directory, + 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)); + assertThat( + new AccountJwtReadinessTrustBinding( + true, + binding.toString(), + Clock.fixed(Instant.ofEpochSecond(NOW), ZoneOffset.UTC)) + .current()) + .isEmpty(); + Files.setPosixFilePermissions( + directory, + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE)); + + Files.setPosixFilePermissions( + binding, Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)); + assertThat( + new AccountJwtReadinessTrustBinding( + true, + binding.toString(), + Clock.fixed(Instant.ofEpochSecond(NOW), ZoneOffset.UTC)) + .current()) + .isEmpty(); + } + + @Test + void rejectsWritableAncestorEvenWhenTheImmediateDirectoryIsProtected() throws Exception { + Path writableAncestor = Files.createDirectory(tempDirectory.resolve("ancestor")); + Path intermediate = Files.createDirectory(writableAncestor.resolve("middle")); + Path directory = Files.createDirectory(intermediate.resolve("protected")); + Path binding = directory.resolve("binding.conf"); + Files.writeString(binding, protectedConfig(NOW + 60), StandardCharsets.UTF_8); + Path absoluteBinding = binding.toAbsolutePath().normalize(); + Path absoluteWritableAncestor = writableAncestor.toRealPath(); + Set protectedDirectoryMode = + Set.of( + PosixFilePermission.OWNER_READ, + PosixFilePermission.OWNER_WRITE, + PosixFilePermission.OWNER_EXECUTE, + PosixFilePermission.GROUP_READ, + PosixFilePermission.GROUP_EXECUTE, + PosixFilePermission.OTHERS_READ, + PosixFilePermission.OTHERS_EXECUTE); + Set writableDirectoryMode = new HashSet<>(protectedDirectoryMode); + writableDirectoryMode.add(PosixFilePermission.GROUP_WRITE); + Map owners = new HashMap<>(); + Map> directoryModes = new HashMap<>(); + for (Path ancestor = directory.toRealPath(); + ancestor != null; + ancestor = ancestor.getParent()) { + owners.put(ancestor, 0L); + directoryModes.put(ancestor, protectedDirectoryMode); + } + Set fileMode = + Set.of(PosixFilePermission.OWNER_READ, PosixFilePermission.GROUP_READ); + + try (MockedStatic mockedFiles = + Mockito.mockStatic(Files.class, Mockito.CALLS_REAL_METHODS)) { + mockedFiles + .when( + () -> + Files.getAttribute( + absoluteBinding, "unix:uid", java.nio.file.LinkOption.NOFOLLOW_LINKS)) + .thenReturn(0L); + mockedFiles + .when( + () -> + Files.getPosixFilePermissions( + absoluteBinding, java.nio.file.LinkOption.NOFOLLOW_LINKS)) + .thenReturn(fileMode); + for (Path ancestor : owners.keySet()) { + Path resolvedAncestor = ancestor; + mockedFiles + .when( + () -> + Files.getAttribute( + resolvedAncestor, "unix:uid", java.nio.file.LinkOption.NOFOLLOW_LINKS)) + .thenAnswer(invocation -> owners.get(resolvedAncestor)); + mockedFiles + .when( + () -> + Files.getPosixFilePermissions( + resolvedAncestor, java.nio.file.LinkOption.NOFOLLOW_LINKS)) + .thenAnswer(invocation -> directoryModes.get(resolvedAncestor)); + } + + assertThat( + new AccountJwtReadinessTrustBinding( + true, + binding.toString(), + Clock.fixed(Instant.ofEpochSecond(NOW), ZoneOffset.UTC)) + .current()) + .isPresent(); + + directoryModes.put(absoluteWritableAncestor, writableDirectoryMode); + assertThat( + new AccountJwtReadinessTrustBinding( + true, + binding.toString(), + Clock.fixed(Instant.ofEpochSecond(NOW), ZoneOffset.UTC)) + .current()) + .isEmpty(); + + directoryModes.put(absoluteWritableAncestor, protectedDirectoryMode); + owners.put(absoluteWritableAncestor, 1000L); + assertThat( + new AccountJwtReadinessTrustBinding( + true, + binding.toString(), + Clock.fixed(Instant.ofEpochSecond(NOW), ZoneOffset.UTC)) + .current()) + .isEmpty(); + } + } + + private static boolean hasProtectedDirectoryAncestors(Path directory) throws Exception { + for (Path ancestor = directory.toRealPath(); + ancestor != null; + ancestor = ancestor.getParent()) { + Object owner = + Files.getAttribute(ancestor, "unix:uid", java.nio.file.LinkOption.NOFOLLOW_LINKS); + if (!(owner instanceof Number uid) || uid.longValue() != 0L) { + return false; + } + Set permissions = + Files.getPosixFilePermissions(ancestor, java.nio.file.LinkOption.NOFOLLOW_LINKS); + if (permissions.contains(PosixFilePermission.GROUP_WRITE) + || permissions.contains(PosixFilePermission.OTHERS_WRITE)) { + return false; + } + } + return true; + } + + private static String protectedConfig(long validUntil) { + String clusterUid = "11111111-1111-4111-8111-111111111111"; + String namespaceUid = "22222222-2222-4222-8222-222222222222"; + String uri = "spiffe://firemud/ns/firemud-prod/sa/account-jwt-readiness-harness"; + List pins = List.of("a".repeat(64)); + String digest = + AccountJwtReadinessTrustBinding.computeBindingDigest( + "revision-7", + "prod", + "prod-cluster-1", + "firemud-prod", + clusterUid, + namespaceUid, + uri, + pins, + "account-validator-instance-7", + validUntil); + return "enabled=true\n" + + "configRevision=revision-7\n" + + "environmentId=prod\n" + + "clusterId=prod-cluster-1\n" + + "namespace=firemud-prod\n" + + "expectedClusterIncarnationUid=" + + clusterUid + + "\n" + + "expectedNamespaceUid=" + + namespaceUid + + "\n" + + "expectedPeerUri=" + + uri + + "\n" + + "peerSpkiSha256Pins=" + + String.join(",", pins) + + "\n" + + "validatorId=account-service\n" + + "validatorInstanceId=account-validator-instance-7\n" + + "validUntilEpochSecond=" + + validUntil + + "\n" + + "bindingDigest=" + + digest + + "\n"; + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java new file mode 100644 index 0000000000..98b4ba081a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java @@ -0,0 +1,339 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding; +import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProtectedInventory; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtValidatorInventoryBindingTest { + private static final String API_DIGEST = "a".repeat(64); + private static final String IMAGE = "registry.example/firemud/player@sha256:" + "b".repeat(64); + 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 DEPLOYMENT_UID = "33333333-3333-4333-8333-333333333333"; + private static final String POD_UID_ONE = "44444444-4444-4444-8444-444444444444"; + private static final String POD_UID_TWO = "55555555-5555-4555-8555-555555555555"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void defaultBindingIsInactiveWithoutReadingFilesystem() { + assertThat(new AccountJwtValidatorInventoryBinding().current()).isEmpty(); + } + + @Test + void acceptsProtectedDirectoryWhenTheFullAncestorChainPasses() throws Exception { + Path leaf = Path.of(".").toRealPath(); + var verifier = mock(AccountJwtValidatorInventoryBinding.ProtectedDirectoryVerifier.class); + + assertThatCode( + () -> AccountJwtValidatorInventoryBinding.verifyProtectedDirectoryChain(leaf, verifier)) + .doesNotThrowAnyException(); + + for (Path current = leaf; current != null; current = current.getParent()) { + verify(verifier).verify(current); + } + verifyNoMoreInteractions(verifier); + } + + @Test + void rejectsWritableAncestorAfterAcceptingTheProtectedLeaf() throws Exception { + Path leaf = Path.of(".").toRealPath(); + Path writableAncestor = leaf.getParent(); + var verifier = mock(AccountJwtValidatorInventoryBinding.ProtectedDirectoryVerifier.class); + doAnswer( + invocation -> { + Path directory = invocation.getArgument(0); + if (writableAncestor.equals(directory)) { + throw new IllegalStateException("Directory is writable by an untrusted principal"); + } + return null; + }) + .when(verifier) + .verify(any()); + + assertThatThrownBy( + () -> AccountJwtValidatorInventoryBinding.verifyProtectedDirectoryChain(leaf, verifier)) + .isInstanceOf(IllegalStateException.class); + + verify(verifier).verify(leaf); + verify(verifier).verify(writableAncestor); + verifyNoMoreInteractions(verifier); + } + + @Test + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = "Canonical protected mount paths are fixed inputs for this binding proof") + void parsesOnlyCompletePinnedRs256ApplicabilityAndProducesCanonicalRuntimeConfig() { + ProtectedInventory inventory = + AccountJwtValidatorInventoryBinding.parseProtectedBytes(validBindingBytes()); + + assertThat(inventory.environmentId()).isEqualTo("test"); + assertThat(inventory.clusterId()).isEqualTo("cluster-test"); + assertThat(inventory.namespace()).isEqualTo("firemud-test"); + assertThat(inventory.expectedClusterIncarnationUid()).isEqualTo(CLUSTER_UID); + assertThat(inventory.expectedNamespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(inventory.validators()).hasSize(1); + var validator = inventory.validators().get(0); + assertThat(validator.deploymentUid()).isEqualTo(DEPLOYMENT_UID); + assertThat(validator.image()).isEqualTo(IMAGE); + assertThat(validator.receiverServiceUri()) + .isEqualTo("spiffe://firemud/ns/firemud-test/sa/player-service"); + assertThat(validator.receiverPort()).isEqualTo(8443); + assertThat(validator.receiverPods()).hasSize(2); + assertThat(validator.canonicalRuntimeConfig()) + .contains("\"algorithm\":\"RS256\"") + .contains("\"maxCacheAgeSeconds\":60") + .contains("\"jwksUri\":\"https://account-api.test/.well-known/jwks.json\""); + + ParsedBinding matchingApi = + new ParsedBinding( + "api-r1", + "test", + "cluster-test", + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("/etc/firemud/account-jwt-api/serving-ca.pem"), + "c".repeat(64), + Path.of("/var/run/secrets/firemud/account-jwt-api-token/token"), + "firemud-test", + CLUSTER_UID, + NAMESPACE_UID, + "system:serviceaccount:firemud-test:account-service", + API_DIGEST); + assertThat(inventory.matchesApiBinding(matchingApi)).isTrue(); + assertThat(inventory.matchesApiBinding(null)).isFalse(); + } + + @Test + void rejectsDigestTamperingUnknownFieldsAndUnpinnedImage() throws Exception { + byte[] valid = validBindingBytes(); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + new String(valid, StandardCharsets.UTF_8) + .replace("cluster-test", "other-cluster") + .getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalStateException.class); + + Map withUnknown = parseMap(valid); + withUnknown.put("ambientTrust", true); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(withUnknown))) + .isInstanceOf(IllegalStateException.class); + + byte[] unpinnedImage = validBindingBytes("registry.example/firemud/player:latest"); + assertThatThrownBy(() -> AccountJwtValidatorInventoryBinding.parseProtectedBytes(unpinnedImage)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void rejectsNonHttpsOrNonCanonicalJwksUri() { + byte[] malformed = validBindingBytes("http://account-api.test/.well-known/jwks.json", IMAGE); + assertThatThrownBy(() -> AccountJwtValidatorInventoryBinding.parseProtectedBytes(malformed)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void rejectsUnsortedDuplicateAndNoncanonicalPodIdentityPins() throws Exception { + Map unsorted = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map validator = + (Map) ((List) unsorted.get("validators")).get(0); + List pins = (List) validator.get("receiverPods"); + validator.put("receiverPods", List.of(pins.get(1), pins.get(0))); + rebindDigest(unsorted); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(unsorted))) + .isInstanceOf(IllegalStateException.class); + + Map noncanonicalIp = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map noncanonicalValidator = + (Map) ((List) noncanonicalIp.get("validators")).get(0); + @SuppressWarnings("unchecked") + Map firstPin = + (Map) ((List) noncanonicalValidator.get("receiverPods")).get(0); + firstPin.put("podIp", "010.0.0.10"); + rebindDigest(noncanonicalIp); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(noncanonicalIp))) + .isInstanceOf(IllegalStateException.class); + + Map uppercaseSpki = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map uppercaseValidator = + (Map) ((List) uppercaseSpki.get("validators")).get(0); + @SuppressWarnings("unchecked") + Map secondPin = + (Map) ((List) uppercaseValidator.get("receiverPods")).get(1); + secondPin.put("leafSpkiSha256", "D".repeat(64)); + rebindDigest(uppercaseSpki); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(uppercaseSpki))) + .isInstanceOf(IllegalStateException.class); + + Map sharedPodKey = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map sharedKeyValidator = + (Map) ((List) sharedPodKey.get("validators")).get(0); + @SuppressWarnings("unchecked") + List> sharedKeyPins = + (List>) sharedKeyValidator.get("receiverPods"); + sharedKeyPins.get(1).put("leafSpkiSha256", sharedKeyPins.get(0).get("leafSpkiSha256")); + rebindDigest(sharedPodKey); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(sharedPodKey))) + .isInstanceOf(IllegalStateException.class); + + Map canonicalIpv6 = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map ipv6Validator = + (Map) ((List) canonicalIpv6.get("validators")).get(0); + @SuppressWarnings("unchecked") + Map ipv6Pin = + (Map) ((List) ipv6Validator.get("receiverPods")).get(0); + ipv6Pin.put("podIp", "2001:db8::1"); + rebindDigest(canonicalIpv6); + assertThat( + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(canonicalIpv6)) + .validators() + .get(0) + .receiverPods() + .get(0) + .podIp()) + .isEqualTo("2001:db8::1"); + + ipv6Pin.put("podIp", "2001:0db8:0:0:0:0:0:1"); + rebindDigest(canonicalIpv6); + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(canonicalIpv6))) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void rejectsOnePodLeafKeyPinnedToDifferentValidatorPods() throws Exception { + Map sharedIdentity = parseMap(validBindingBytes()); + @SuppressWarnings("unchecked") + Map firstValidator = + (Map) ((List) sharedIdentity.get("validators")).get(0); + Map secondValidator = new LinkedHashMap<>(firstValidator); + secondValidator.put("validatorId", "other-service"); + secondValidator.put("deploymentName", "other-service"); + secondValidator.put("deploymentUid", "66666666-6666-4666-8666-666666666666"); + secondValidator.put("selector", Map.of("app", "other-service")); + secondValidator.put("containerName", "other-service"); + secondValidator.put("receiverServiceUri", "spiffe://firemud/ns/firemud-test/sa/other-service"); + @SuppressWarnings("unchecked") + List> firstPins = + (List>) firstValidator.get("receiverPods"); + Map otherFirstPin = new LinkedHashMap<>(firstPins.get(0)); + otherFirstPin.put("podUid", "77777777-7777-4777-8777-777777777777"); + otherFirstPin.put("podIp", "10.0.1.10"); + Map otherSecondPin = new LinkedHashMap<>(firstPins.get(1)); + otherSecondPin.put("podUid", "88888888-8888-4888-8888-888888888888"); + otherSecondPin.put("podIp", "10.0.1.11"); + secondValidator.put("receiverPods", List.of(otherFirstPin, otherSecondPin)); + sharedIdentity.put("validators", List.of(firstValidator, secondValidator)); + rebindDigest(sharedIdentity); + + assertThatThrownBy( + () -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(sharedIdentity))) + .isInstanceOf(IllegalStateException.class); + } + + private static byte[] validBindingBytes() { + return validBindingBytes("https://account-api.test/.well-known/jwks.json", IMAGE); + } + + private static byte[] validBindingBytes(String image) { + return validBindingBytes("https://account-api.test/.well-known/jwks.json", image); + } + + private static byte[] validBindingBytes(String jwksUri, String image) { + Map profile = + Map.of("tokenProfile", "game-session-account-delegation", "audience", "account-service"); + Map validator = new LinkedHashMap<>(); + validator.put("validatorId", "player-service"); + validator.put("deploymentName", "player-service"); + validator.put("deploymentUid", DEPLOYMENT_UID); + validator.put("selector", Map.of("app", "player-service")); + validator.put("replicas", 2); + validator.put("containerName", "player-service"); + validator.put("image", image); + validator.put("jwksUri", jwksUri); + validator.put("maxCacheAgeSeconds", 60); + validator.put("profiles", List.of(profile)); + validator.put("receiverServiceUri", "spiffe://firemud/ns/firemud-test/sa/player-service"); + validator.put("receiverPort", 8443); + validator.put( + "receiverPods", + List.of( + Map.of("podUid", POD_UID_ONE, "podIp", "10.0.0.10", "leafSpkiSha256", "c".repeat(64)), + Map.of("podUid", POD_UID_TWO, "podIp", "10.0.0.11", "leafSpkiSha256", "d".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", "test"); + root.put("clusterId", "cluster-test"); + root.put("namespace", "firemud-test"); + root.put("expectedClusterIncarnationUid", CLUSTER_UID); + root.put("expectedNamespaceUid", NAMESPACE_UID); + root.put("apiBindingRevision", "api-r1"); + root.put("apiBindingDigest", API_DIGEST); + root.put("validators", List.of(validator)); + root.put("bindingDigest", "0".repeat(64)); + try { + JsonNode unsigned = JSON.readTree(JSON.writeValueAsBytes(root)); + root.put("bindingDigest", AccountJwtValidatorInventoryBinding.computeBindingDigest(unsigned)); + return JSON.writeValueAsBytes(root); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } + + private static void rebindDigest(Map root) throws Exception { + root.put("bindingDigest", "0".repeat(64)); + JsonNode unsigned = JSON.readTree(JSON.writeValueAsBytes(root)); + root.put("bindingDigest", AccountJwtValidatorInventoryBinding.computeBindingDigest(unsigned)); + } + + @SuppressWarnings("unchecked") + private static Map parseMap(byte[] value) throws Exception { + JsonNode root = JSON.readTree(value); + return JSON.readValue(JSON.writeValueAsBytes(root), Map.class); + } +} 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 new file mode 100644 index 0000000000..58ac45e7dc --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventorySourceTest.java @@ -0,0 +1,946 @@ +package net.firedevops.firemud.accountservice.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +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.ApiCall; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiOperation; +import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse; +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.AccountJwtValidatorInventorySource; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventoryUnavailableException; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext; +import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; + +class AccountJwtValidatorInventorySourceTest { + 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 DEPLOYMENT_UID = "33333333-3333-4333-8333-333333333333"; + private static final String REPLICA_SET_UID = "44444444-4444-4444-8444-444444444444"; + private static final String POD_UID = "55555555-5555-4555-8555-555555555555"; + private static final String POD_IP = "10.10.0.15"; + private static final String POD_SPKI = "e".repeat(64); + private static final String POD_TEMPLATE_HASH = "abcde12345"; + private static final String API_DIGEST = "a".repeat(64); + private static final String IMAGE_DIGEST = "d".repeat(64); + private static final String IMAGE = "registry.example/firemud/player@sha256:" + IMAGE_DIGEST; + private static final String EXPECTED_USERNAME = + "system:serviceaccount:" + NAMESPACE + ":account-service"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final Clock CLOCK = + Clock.fixed(Instant.parse("2026-10-05T00:00:00Z"), ZoneOffset.UTC); + + @Test + void defaultBindingsRemainInactiveAndUnavailable() { + AccountJwtValidatorInventorySource source = + new AccountJwtValidatorInventorySource( + new AccountJwtJwksApiBinding(), new AccountJwtValidatorInventoryBinding(), CLOCK); + + assertThatThrownBy(source::observe) + .isInstanceOf(InventoryUnavailableException.class) + .hasNoCause(); + } + + @Test + void rejectsPrivateSignerMaterialInInitAndEphemeralContainersAndProjectedVolumes() + throws Exception { + Fixture initContainer = new Fixture(); + ObjectNode deployment = (ObjectNode) JSON.readTree(deploymentJson("10", 1, 1, 1, false)); + ObjectNode deploymentSpec = (ObjectNode) deployment.path("spec").path("template").path("spec"); + deploymentSpec.set( + "initContainers", + JSON.readTree( + "[{\"name\":\"setup\",\"envFrom\":[{\"secretRef\":{" + + "\"name\":\"jwt-signing-keys\"}}]}]")); + initContainer.stubDeployment(new ApiResponse(200, JSON.writeValueAsBytes(deployment))); + assertUnavailable(initContainer); + + Fixture ephemeralContainer = new Fixture(); + JsonNode podList = JSON.readTree(podListJson()); + ObjectNode podSpec = (ObjectNode) podList.path("items").get(0).path("spec"); + podSpec.set( + "ephemeralContainers", + JSON.readTree( + "[{\"name\":\"debug\",\"volumeMounts\":[{" + + "\"name\":\"jwt-signing-keys\",\"mountPath\":\"/private\"}]}]")); + ephemeralContainer.stubPods(new ApiResponse(200, JSON.writeValueAsBytes(podList))); + assertUnavailable(ephemeralContainer); + + Fixture projectedSecret = new Fixture(); + ObjectNode projectedDeployment = + (ObjectNode) JSON.readTree(deploymentJson("10", 1, 1, 1, false)); + ObjectNode projectedSpec = + (ObjectNode) projectedDeployment.path("spec").path("template").path("spec"); + projectedSpec.set( + "volumes", + JSON.readTree( + "[{\"name\":\"private-material\",\"projected\":{\"sources\":[{" + + "\"secret\":{\"name\":\"jwt-signing-keys\"}}]}}]")); + projectedSecret.stubDeployment( + new ApiResponse(200, JSON.writeValueAsBytes(projectedDeployment))); + assertUnavailable(projectedSecret); + } + + @Test + void rejectsSelectedValidatorEnvFromConfigMapAndSecretReferencesAndMalformedValues() + throws Exception { + for (String envFrom : + List.of( + "[{\"configMapRef\":{\"name\":\"runtime-config\"}}]", + "[{\"secretRef\":{\"name\":\"runtime-secrets\"}}]", + "{\"secretRef\":{\"name\":\"runtime-secrets\"}}", + "[null]")) { + Fixture fixture = new Fixture(); + ObjectNode deployment = (ObjectNode) JSON.readTree(deploymentJson("10", 1, 1, 1, false)); + ((ObjectNode) deployment.path("spec").path("template").path("spec").path("containers").get(0)) + .set("envFrom", JSON.readTree(envFrom)); + fixture.stubDeployment(new ApiResponse(200, JSON.writeValueAsBytes(deployment))); + assertUnavailable(fixture); + } + } + + @Test + void acceptsSelectedValidatorWithoutEnvFromOrWithNullOrEmptyEnvFrom() throws Exception { + for (String envFrom : List.of("null", "[]")) { + Fixture fixture = new Fixture(); + ObjectNode deployment = (ObjectNode) JSON.readTree(deploymentJson("10", 1, 1, 1, false)); + ((ObjectNode) deployment.path("spec").path("template").path("spec").path("containers").get(0)) + .set("envFrom", JSON.readTree(envFrom)); + fixture.stubDeployment(new ApiResponse(200, JSON.writeValueAsBytes(deployment))); + + assertThat(fixture.source.observe()).isNotNull(); + } + assertThat(new Fixture().source.observe()).isNotNull(); + } + + @Test + void allowsNonSigningEnvFromOnAnAuxiliaryContainer() throws Exception { + Fixture fixture = new Fixture(); + ObjectNode deployment = (ObjectNode) JSON.readTree(deploymentJson("10", 1, 1, 1, false)); + ArrayNode containers = + (ArrayNode) deployment.path("spec").path("template").path("spec").path("containers"); + containers.add( + JSON.readTree( + "{\"name\":\"metrics-sidecar\",\"image\":\"metrics:1\"," + + "\"envFrom\":[{\"configMapRef\":{\"name\":\"metrics-config\"}}," + + "{\"secretRef\":{\"name\":\"metrics-secrets\"}}]}")); + fixture.stubDeployment(new ApiResponse(200, JSON.writeValueAsBytes(deployment))); + + assertThat(fixture.source.observe()).isNotNull(); + } + + @Test + void acceptsPublicJwksSecretAndProjectedSources() throws Exception { + Fixture fixture = new Fixture(); + ObjectNode deployment = (ObjectNode) JSON.readTree(deploymentJson("10", 1, 1, 1, false)); + ObjectNode podSpec = (ObjectNode) deployment.path("spec").path("template").path("spec"); + ObjectNode container = (ObjectNode) podSpec.path("containers").get(0); + container.set( + "volumeMounts", + JSON.readTree( + "[{\"name\":\"jwt-jwks\",\"mountPath\":\"/var/run/secrets/firemud/jwks\"," + + "\"readOnly\":true}]")); + podSpec.set( + "volumes", + JSON.readTree( + "[{\"name\":\"jwt-jwks\",\"secret\":{\"secretName\":\"jwt-jwks\"}}," + + "{\"name\":\"jwt-jwks-projected\",\"projected\":{\"sources\":[{" + + "\"secret\":{\"name\":\"jwt-jwks\"}}]}}]")); + fixture.stubDeployment(new ApiResponse(200, JSON.writeValueAsBytes(deployment))); + + assertThat(fixture.source.observe()).isNotNull(); + } + + @Test + void returnsOnlyStableActualPodAndDeploymentIdentitiesAsNonAuthorizingEvidence() + throws Exception { + Fixture fixture = new Fixture(); + + InventorySnapshot snapshot = fixture.source.observe(); + + assertThat(snapshot.environmentId()).isEqualTo(ENVIRONMENT); + assertThat(snapshot.clusterIncarnationUid()).isEqualTo(CLUSTER_UID); + assertThat(snapshot.namespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(snapshot.validators()).hasSize(1); + assertThat(snapshot.validators().get(0).deploymentUid()).isEqualTo(DEPLOYMENT_UID); + assertThat(snapshot.validators().get(0).pods()) + .extracting(AccountJwtValidatorInventorySource.PodObservation::uid) + .containsExactly(POD_UID); + assertThat(snapshot.validators().get(0).pods().get(0).ownerUid()).isEqualTo(REPLICA_SET_UID); + assertThat(snapshot.validators().get(0).pods().get(0).podIp()).isEqualTo(POD_IP); + assertThat(snapshot.validators().get(0).pods().get(0).endpoint()) + .isEqualTo(URI.create("grpcs://10.10.0.15:8443")); + assertThat(snapshot.validators().get(0).pods().get(0).receiverServiceUri()) + .isEqualTo("spiffe://firemud/ns/firemud-test/sa/player-service"); + assertThat(snapshot.validators().get(0).pods().get(0).leafSpkiSha256()).isEqualTo(POD_SPKI); + assertThat(snapshot.validators().get(0).replicaSets()) + .singleElement() + .satisfies( + replicaSet -> { + assertThat(replicaSet.ownerDeploymentName()).isEqualTo("player-service"); + assertThat(replicaSet.ownerDeploymentUid()).isEqualTo(DEPLOYMENT_UID); + }); + assertThat(snapshot.digest()).matches("[0-9a-f]{64}"); + assertThat(new String(snapshot.canonicalBytes(), StandardCharsets.UTF_8)) + .contains("ownerDeploymentUid", DEPLOYMENT_UID, "podTemplateHash", POD_TEMPLATE_HASH) + .doesNotContain("observedAt"); + } + + @Test + void unchangedProtectedInventoryKeepsContentDigestAcrossLaterObservation() throws Exception { + Fixture fixture = new Fixture(); + InventorySnapshot first = fixture.source.observe(); + InventorySnapshot later = + new AccountJwtValidatorInventorySource( + fixture.apiBinding, + fixture.inventoryBinding, + Clock.offset(CLOCK, Duration.ofSeconds(10))) + .observe(); + + assertThat(later.observedAt()).isAfter(first.observedAt()); + assertThat(later.digest()).isEqualTo(first.digest()); + assertThat(later.canonicalBytes()).containsExactly(first.canonicalBytes()); + } + + @Test + void initialOperationCanEnumerateExactRunningCandidatesBeforeKubernetesReadiness() + throws Exception { + Fixture fixture = new Fixture(); + fixture.stubNotReadyCandidates(); + ObservationContext context = initialObservationContext(); + + InventorySnapshot snapshot = fixture.source.observe(context); + + assertThat(snapshot.observationContext()).contains(context); + assertThat(snapshot.validators()) + .singleElement() + .satisfies( + validator -> { + assertThat(validator.pods()) + .extracting(AccountJwtValidatorInventorySource.PodObservation::uid) + .containsExactly(POD_UID); + assertThat(validator.image()).isEqualTo(IMAGE); + assertThat(validator.verifierConfigSha256()).isNotBlank(); + }); + assertThat(new String(snapshot.canonicalBytes(), StandardCharsets.UTF_8)) + .contains( + "INITIAL_NO_ACTIVE_SIGNER_CANDIDATES", + context.operationId().toString(), + context.operationDigest()) + .doesNotContain("ordinaryReady"); + } + + @Test + void nonReadyCandidatesRemainUnavailableForNormalRotationAndUnboundObservation() + throws Exception { + Fixture fixture = new Fixture(); + fixture.stubNotReadyCandidates(); + + assertUnavailable(fixture); + assertThatThrownBy( + () -> + fixture.source.observe( + new ObservationContext( + ObservationPurpose.STRICT_READY, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "9".repeat(64)))) + .isInstanceOf(InventoryUnavailableException.class) + .hasNoCause(); + } + + @Test + void initialCandidateInventoryStillRejectsMissingOrSwappedPinnedPods() throws Exception { + ObservationContext context = initialObservationContext(); + Fixture missing = new Fixture(); + missing.stubNotReadyCandidates(); + when(missing.operation.listValidatorPods( + same(missing.inventory), same(missing.validator), isNull())) + .thenReturn( + new ApiResponse( + 200, + jsonBytes( + Map.of( + "apiVersion", + "v1", + "kind", + "PodList", + "metadata", + Map.of("resourceVersion", "20", "continue", ""), + "items", + List.of())))); + + Fixture swapped = new Fixture(); + swapped.stubNotReadyCandidates(); + when(swapped.operation.listValidatorPods( + same(swapped.inventory), same(swapped.validator), isNull())) + .thenReturn( + new ApiResponse( + 200, podListJson(POD_IP, "66666666-6666-4666-8666-666666666666", false))); + + assertBootstrapUnavailable(missing, context); + assertBootstrapUnavailable(swapped, context); + } + + @Test + void deniesUnexpectedAuthenticatedPrincipalAndNamespaceIncarnation() throws Exception { + Fixture wrongPrincipal = new Fixture(); + wrongPrincipal.stubSelfReview("system:serviceaccount:" + NAMESPACE + ":other"); + assertUnavailable(wrongPrincipal); + verify(wrongPrincipal.operation, times(0)) + .readValidatorDeployment(same(wrongPrincipal.inventory), same(wrongPrincipal.validator)); + + Fixture wrongNamespace = new Fixture(); + wrongNamespace.stubTargetNamespace("99999999-9999-4999-8999-999999999999"); + assertUnavailable(wrongNamespace); + verify(wrongNamespace.operation, times(0)).readValidatorDeployment(any(), any()); + } + + @Test + void deniesLegacyHmacRuntimeAndPartialDeploymentRollout() throws Exception { + Fixture legacy = new Fixture(); + legacy.stubDeployment(new ApiResponse(200, deploymentJson("10", 1, 1, 1, true))); + assertUnavailable(legacy); + + Fixture partial = new Fixture(); + partial.stubDeployment(new ApiResponse(200, deploymentJson("10", 1, 1, 0, false))); + assertUnavailable(partial); + } + + @Test + void rejectsNullPodListEntriesAsUnavailableInventory() throws Exception { + Fixture fixture = new Fixture(); + byte[] nullPodList = + jsonBytes( + Map.of( + "apiVersion", + "v1", + "kind", + "PodList", + "metadata", + Map.of("resourceVersion", "20"), + "items", + java.util.Collections.singletonList(null))); + when(fixture.operation.listValidatorPods( + same(fixture.inventory), same(fixture.validator), isNull())) + .thenReturn(new ApiResponse(200, nullPodList)); + + assertUnavailable(fixture); + } + + @Test + void deniesADeploymentThatChangesBetweenTheTwoInventoryReads() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.operation.readValidatorDeployment( + same(fixture.inventory), same(fixture.validator))) + .thenReturn( + new ApiResponse(200, deploymentJson("10", 1, 1, 1, false)), + new ApiResponse(200, deploymentJson("11", 2, 2, 1, false))); + + assertUnavailable(fixture); + } + + @Test + void deniesPodAddressThatDiffersFromTheProtectedPodBoundTlsPin() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.operation.listValidatorPods( + same(fixture.inventory), same(fixture.validator), isNull())) + .thenReturn(new ApiResponse(200, podListJson("10.10.0.16"))); + + assertUnavailable(fixture); + } + + @Test + void deniesLivePodUidMissingFromTheProtectedReceiverIdentityMap() throws Exception { + Fixture fixture = + new Fixture( + validInventoryBytes( + "66666666-6666-4666-8666-666666666666", + POD_IP, + POD_SPKI, + IMAGE, + "https://account-api.test/.well-known/jwks.json", + "inventory-r1")); + + assertUnavailable(fixture); + } + + @Test + void changedProtectedPodKeyOrBindingRevisionChangesInventoryContentIdentity() throws Exception { + InventorySnapshot original = new Fixture().source.observe(); + InventorySnapshot changed = + new Fixture( + validInventoryBytes( + POD_UID, + POD_IP, + "f".repeat(64), + IMAGE, + "https://account-api.test/.well-known/jwks.json", + "inventory-r1")) + .source.observe(); + InventorySnapshot changedSourceRevision = + new Fixture( + validInventoryBytes( + POD_UID, + POD_IP, + POD_SPKI, + IMAGE, + "https://account-api.test/.well-known/jwks.json", + "inventory-r2")) + .source.observe(); + + assertThat(changed.digest()).isNotEqualTo(original.digest()); + assertThat(changedSourceRevision.digest()).isNotEqualTo(original.digest()); + } + + @Test + void deniesLiveImageOrVerifierConfigurationThatDriftsFromProtectedInventory() throws Exception { + Fixture changedImage = + new Fixture( + validInventoryBytes( + POD_UID, + POD_IP, + POD_SPKI, + "registry.example/firemud/player@sha256:" + "f".repeat(64), + "https://account-api.test/.well-known/jwks.json", + "inventory-r2")); + Fixture changedConfig = + new Fixture( + validInventoryBytes( + POD_UID, + POD_IP, + POD_SPKI, + IMAGE, + "https://replacement-api.test/.well-known/jwks.json", + "inventory-r2")); + + assertUnavailable(changedImage); + assertUnavailable(changedConfig); + } + + @Test + void deniesReplicaSetOwnedByDifferentDeploymentEvenWhenPodOwnerMatches() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.operation.readValidatorReplicaSet( + same(fixture.inventory), same(fixture.validator), eq("player-service-abcde"))) + .thenReturn( + new ApiResponse( + 200, + replicaSetJson( + "40", + "44444444-4444-4444-8444-444444444444", + "other-service", + "99999999-9999-4999-8999-999999999999"))); + + assertUnavailable(fixture); + } + + @Test + void deniesReplicaSetUidReplacementOrOwnershipChangeBetweenInventoryReads() throws Exception { + Fixture fixture = new Fixture(); + when(fixture.operation.readValidatorReplicaSet( + same(fixture.inventory), same(fixture.validator), eq("player-service-abcde"))) + .thenReturn( + new ApiResponse( + 200, replicaSetJson("40", REPLICA_SET_UID, "player-service", DEPLOYMENT_UID)), + new ApiResponse( + 200, + replicaSetJson( + "41", + "66666666-6666-4666-8666-666666666666", + "player-service", + DEPLOYMENT_UID))); + + assertUnavailable(fixture); + } + + @Test + void deniesADeploymentPodListWhosePaginationNeverCompletes() throws Exception { + Fixture fixture = new Fixture(); + byte[] unfinishedPage = + jsonBytes( + Map.of( + "apiVersion", + "v1", + "kind", + "PodList", + "metadata", + Map.of("resourceVersion", "20", "continue", "next-page"), + "items", + List.of())); + when(fixture.operation.listValidatorPods( + same(fixture.inventory), same(fixture.validator), any())) + .thenReturn(new ApiResponse(200, unfinishedPage)); + + assertUnavailable(fixture); + + verify(fixture.operation, times(16)) + .listValidatorPods(same(fixture.inventory), same(fixture.validator), any()); + } + + private static void assertUnavailable(Fixture fixture) { + assertThatThrownBy(fixture.source::observe) + .isInstanceOf(InventoryUnavailableException.class) + .hasNoCause(); + } + + private static void assertBootstrapUnavailable(Fixture fixture, ObservationContext context) { + assertThatThrownBy(() -> fixture.source.observe(context)) + .isInstanceOf(InventoryUnavailableException.class) + .hasNoCause(); + } + + private static ObservationContext initialObservationContext() { + return new ObservationContext( + ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "9".repeat(64)); + } + + private static byte[] deploymentJson( + String resourceVersion, + int generation, + int observedGeneration, + int readyReplicas, + boolean legacyHmac) + throws Exception { + return deploymentJson( + resourceVersion, generation, observedGeneration, readyReplicas, legacyHmac, false); + } + + private static byte[] deploymentJson( + String resourceVersion, + int generation, + int observedGeneration, + int readyReplicas, + boolean legacyHmac, + boolean omitZeroReadinessCounts) + throws Exception { + List> env = new ArrayList<>(); + env.add(Map.of("name", "FIREMUD_JWT_VERIFIER_CONFIG", "value", runtimeConfig())); + if (legacyHmac) { + env.add(Map.of("name", "FIREMUD_AUTH_JWT_SECRET", "value", "not-retained")); + } + Map container = + Map.of("name", "player-service", "image", IMAGE, "env", env, "volumeMounts", List.of()); + Map template = + Map.of( + "metadata", Map.of("labels", Map.of("app", "player-service")), + "spec", Map.of("containers", List.of(container), "volumes", List.of())); + Map spec = + Map.of( + "replicas", + 1, + "selector", + Map.of("matchLabels", Map.of("app", "player-service")), + "template", + template); + Map status = new LinkedHashMap<>(); + status.put("observedGeneration", observedGeneration); + if (!omitZeroReadinessCounts || readyReplicas != 0) { + status.put("readyReplicas", readyReplicas); + } + status.put("updatedReplicas", 1); + if (!omitZeroReadinessCounts || readyReplicas != 0) { + status.put("availableReplicas", readyReplicas); + } + return jsonBytes( + Map.of( + "apiVersion", + "apps/v1", + "kind", + "Deployment", + "metadata", + Map.of( + "name", "player-service", + "namespace", NAMESPACE, + "uid", DEPLOYMENT_UID, + "resourceVersion", resourceVersion, + "generation", generation), + "spec", + spec, + "status", + status)); + } + + private static byte[] podListJson() throws Exception { + return podListJson(POD_IP); + } + + private static byte[] podListJson(String podIp) throws Exception { + return podListJson(podIp, POD_UID, true); + } + + private static byte[] podListJson(String podIp, String podUid, boolean ready) throws Exception { + Map container = + Map.of( + "name", + "player-service", + "image", + IMAGE, + "env", + List.of(Map.of("name", "FIREMUD_JWT_VERIFIER_CONFIG", "value", runtimeConfig())), + "volumeMounts", + List.of()); + Map pod = + Map.of( + "apiVersion", "v1", + "kind", "Pod", + "metadata", + Map.of( + "name", + "player-service-abcde-12345", + "namespace", + NAMESPACE, + "uid", + podUid, + "resourceVersion", + "30", + "labels", + Map.of("app", "player-service", "pod-template-hash", POD_TEMPLATE_HASH), + "ownerReferences", + List.of( + Map.of( + "apiVersion", "apps/v1", + "kind", "ReplicaSet", + "name", "player-service-abcde", + "uid", REPLICA_SET_UID, + "controller", true))), + "spec", Map.of("containers", List.of(container), "volumes", List.of()), + "status", + Map.of( + "phase", + "Running", + "podIP", + podIp, + "conditions", + List.of(Map.of("type", "Ready", "status", ready ? "True" : "False")), + "containerStatuses", + List.of( + Map.of( + "name", + "player-service", + "ready", + ready, + "imageID", + "docker-pullable://registry.example/player@sha256:" + IMAGE_DIGEST)))); + return jsonBytes( + Map.of( + "apiVersion", + "v1", + "kind", + "PodList", + "metadata", + Map.of("resourceVersion", "20", "continue", ""), + "items", + List.of(pod))); + } + + private static byte[] replicaSetJson( + String resourceVersion, String uid, String ownerName, String ownerUid) throws Exception { + return replicaSetJson(resourceVersion, uid, ownerName, ownerUid, 1); + } + + private static byte[] replicaSetJson( + String resourceVersion, String uid, String ownerName, String ownerUid, int readyReplicas) + throws Exception { + return replicaSetJson(resourceVersion, uid, ownerName, ownerUid, readyReplicas, false); + } + + private static byte[] replicaSetJson( + String resourceVersion, + String uid, + String ownerName, + String ownerUid, + int readyReplicas, + boolean omitZeroReadyReplicas) + throws Exception { + Map container = + Map.of( + "name", + "player-service", + "image", + IMAGE, + "env", + List.of(Map.of("name", "FIREMUD_JWT_VERIFIER_CONFIG", "value", runtimeConfig())), + "volumeMounts", + List.of()); + Map status = new LinkedHashMap<>(); + status.put("observedGeneration", 1); + if (!omitZeroReadyReplicas || readyReplicas != 0) { + status.put("readyReplicas", readyReplicas); + } + return jsonBytes( + Map.of( + "apiVersion", + "apps/v1", + "kind", + "ReplicaSet", + "metadata", + Map.of( + "name", + "player-service-abcde", + "namespace", + NAMESPACE, + "uid", + uid, + "resourceVersion", + resourceVersion, + "generation", + 1, + "ownerReferences", + List.of( + Map.of( + "apiVersion", + "apps/v1", + "kind", + "Deployment", + "name", + ownerName, + "uid", + ownerUid, + "controller", + true))), + "spec", + Map.of( + "replicas", 1, + "selector", + Map.of( + "matchLabels", + Map.of("app", "player-service", "pod-template-hash", POD_TEMPLATE_HASH)), + "template", + Map.of( + "metadata", + Map.of( + "labels", + Map.of( + "app", + "player-service", + "pod-template-hash", + POD_TEMPLATE_HASH)), + "spec", Map.of("containers", List.of(container), "volumes", List.of()))), + "status", + status)); + } + + private static String runtimeConfig() { + return AccountJwtValidatorInventoryBinding.parseProtectedBytes(validInventoryBytes()) + .validators() + .get(0) + .canonicalRuntimeConfig(); + } + + private static byte[] validInventoryBytes() { + return validInventoryBytes( + POD_UID, + POD_IP, + POD_SPKI, + IMAGE, + "https://account-api.test/.well-known/jwks.json", + "inventory-r1"); + } + + private static byte[] validInventoryBytes( + String podUid, + String podIp, + String podSpki, + String image, + String jwksUri, + String configRevision) { + Map validator = new LinkedHashMap<>(); + validator.put("validatorId", "player-service"); + validator.put("deploymentName", "player-service"); + validator.put("deploymentUid", DEPLOYMENT_UID); + validator.put("selector", Map.of("app", "player-service")); + validator.put("replicas", 1); + validator.put("containerName", "player-service"); + validator.put("image", image); + validator.put("jwksUri", jwksUri); + 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-test/sa/player-service"); + validator.put("receiverPort", 8443); + validator.put( + "receiverPods", + List.of(Map.of("podUid", podUid, "podIp", podIp, "leafSpkiSha256", podSpki))); + Map root = new LinkedHashMap<>(); + root.put("version", "account-jwt-validator-inventory-binding/v2"); + root.put("enabled", "true"); + root.put("configRevision", configRevision); + root.put("environmentId", ENVIRONMENT); + root.put("clusterId", CLUSTER); + root.put("namespace", NAMESPACE); + root.put("expectedClusterIncarnationUid", CLUSTER_UID); + root.put("expectedNamespaceUid", NAMESPACE_UID); + root.put("apiBindingRevision", "api-r1"); + root.put("apiBindingDigest", API_DIGEST); + root.put("validators", List.of(validator)); + root.put("bindingDigest", "0".repeat(64)); + try { + var unsigned = JSON.readTree(JSON.writeValueAsBytes(root)); + root.put("bindingDigest", AccountJwtValidatorInventoryBinding.computeBindingDigest(unsigned)); + return JSON.writeValueAsBytes(root); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } + + @SuppressFBWarnings( + value = "DMI_HARDCODED_ABSOLUTE_FILENAME", + justification = "Canonical protected paths are fixed test binding inputs") + private static ParsedBinding apiBinding() { + return new ParsedBinding( + "api-r1", + ENVIRONMENT, + CLUSTER, + URI.create("https://kubernetes.test:6443"), + "kubernetes.test", + Path.of("/etc/firemud/account-jwt-api/serving-ca.pem"), + "c".repeat(64), + Path.of("/var/run/secrets/firemud/account-jwt-api-token/token"), + NAMESPACE, + CLUSTER_UID, + NAMESPACE_UID, + EXPECTED_USERNAME, + API_DIGEST); + } + + private static byte[] jsonBytes(Object value) { + try { + return JSON.writeValueAsBytes(value); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } + + private static byte[] namespaceJson(String namespace, String uid) { + return jsonBytes( + Map.of( + "apiVersion", + "v1", + "kind", + "Namespace", + "metadata", + Map.of("name", namespace, "uid", uid), + "status", + Map.of("phase", "Active"))); + } + + private static byte[] selfReviewJson(String username) { + return jsonBytes( + Map.of( + "apiVersion", "authentication.k8s.io/v1", + "kind", "SelfSubjectReview", + "status", Map.of("userInfo", Map.of("username", username)))); + } + + private static final class Fixture { + private final AccountJwtJwksApiBinding apiBinding = mock(AccountJwtJwksApiBinding.class); + private final AccountJwtValidatorInventoryBinding inventoryBinding = + mock(AccountJwtValidatorInventoryBinding.class); + private final ApiOperation operation = mock(ApiOperation.class); + private final ProtectedInventory inventory; + private final ValidatorExpectation validator; + private final AccountJwtValidatorInventorySource source; + + private Fixture() throws Exception { + this(validInventoryBytes()); + } + + private Fixture(byte[] inventoryBytes) throws Exception { + inventory = AccountJwtValidatorInventoryBinding.parseProtectedBytes(inventoryBytes); + validator = inventory.validators().get(0); + when(apiBinding.beginOperation()).thenReturn(operation); + when(operation.binding()).thenReturn(apiBinding()); + when(inventoryBinding.current()).thenReturn(Optional.of(inventory)); + when(operation.send(eq(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL), any(byte[].class))) + .thenReturn(new ApiResponse(201, selfReviewJson(EXPECTED_USERNAME))); + when(operation.send(ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null)) + .thenReturn(new ApiResponse(200, namespaceJson("kube-system", CLUSTER_UID))); + when(operation.send(ApiCall.READ_TARGET_NAMESPACE, null)) + .thenReturn(new ApiResponse(200, namespaceJson(NAMESPACE, NAMESPACE_UID))); + ApiResponse deployment = new ApiResponse(200, deploymentJson("10", 1, 1, 1, false)); + ApiResponse pods = new ApiResponse(200, podListJson()); + when(operation.readValidatorDeployment(same(inventory), same(validator))) + .thenReturn(deployment); + when(operation.listValidatorPods(same(inventory), same(validator), isNull())) + .thenReturn(pods); + when(operation.readValidatorReplicaSet( + same(inventory), same(validator), eq("player-service-abcde"))) + .thenReturn( + new ApiResponse( + 200, replicaSetJson("40", REPLICA_SET_UID, "player-service", DEPLOYMENT_UID))); + source = new AccountJwtValidatorInventorySource(apiBinding, inventoryBinding, CLOCK); + } + + private void stubSelfReview(String username) { + when(operation.send(eq(ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL), any(byte[].class))) + .thenReturn(new ApiResponse(201, selfReviewJson(username))); + } + + private void stubTargetNamespace(String uid) { + when(operation.send(ApiCall.READ_TARGET_NAMESPACE, null)) + .thenReturn(new ApiResponse(200, namespaceJson(NAMESPACE, uid))); + } + + private void stubDeployment(ApiResponse response) { + when(operation.readValidatorDeployment(same(inventory), same(validator))) + .thenReturn(response); + } + + private void stubPods(ApiResponse response) { + when(operation.listValidatorPods(same(inventory), same(validator), isNull())) + .thenReturn(response); + } + + private void stubNotReadyCandidates() throws Exception { + stubDeployment(new ApiResponse(200, deploymentJson("10", 1, 1, 0, false, true))); + when(operation.listValidatorPods(same(inventory), same(validator), isNull())) + .thenReturn(new ApiResponse(200, podListJson(POD_IP, POD_UID, false))); + when(operation.readValidatorReplicaSet( + same(inventory), same(validator), eq("player-service-abcde"))) + .thenReturn( + new ApiResponse( + 200, + replicaSetJson( + "40", REPLICA_SET_UID, "player-service", DEPLOYMENT_UID, 0, true))); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingTest.java new file mode 100644 index 0000000000..a21d577c1f --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingTest.java @@ -0,0 +1,54 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class AccountGameplayCredentialRequestBindingTest { + private static final String KEY_ID = "test-account-login-key"; + private static final String DIGEST = "ab".repeat(32); + + @Test + void acceptsVersionedLowercaseSha256BindingAndRedactsItsContents() { + AccountGameplayCredentialRequestBinding binding = + new AccountGameplayCredentialRequestBinding(1, KEY_ID, DIGEST); + + assertEquals(1, binding.digestSchemaVersion()); + assertEquals(KEY_ID, binding.digestKeyId()); + assertEquals(DIGEST, binding.credentialRequestDigest()); + assertEquals("AccountGameplayCredentialRequestBinding[redacted]", binding.toString()); + assertFalse(binding.toString().contains(KEY_ID)); + assertFalse(binding.toString().contains(DIGEST)); + } + + @Test + void rejectsUnsupportedSchemaAndMalformedKeyIdentifiers() { + assertThrows( + IllegalArgumentException.class, + () -> new AccountGameplayCredentialRequestBinding(2, KEY_ID, DIGEST)); + assertThrows( + IllegalArgumentException.class, + () -> new AccountGameplayCredentialRequestBinding(1, "", DIGEST)); + assertThrows( + IllegalArgumentException.class, + () -> new AccountGameplayCredentialRequestBinding(1, "key with spaces", DIGEST)); + assertThrows( + IllegalArgumentException.class, + () -> new AccountGameplayCredentialRequestBinding(1, "k".repeat(33), DIGEST)); + } + + @Test + void rejectsMissingOrMalformedRequestDigests() { + assertThrows( + NullPointerException.class, + () -> new AccountGameplayCredentialRequestBinding(1, KEY_ID, null)); + assertThrows( + IllegalArgumentException.class, + () -> new AccountGameplayCredentialRequestBinding(1, KEY_ID, "ab".repeat(31))); + assertThrows( + IllegalArgumentException.class, + () -> new AccountGameplayCredentialRequestBinding(1, KEY_ID, "AB".repeat(32))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentityTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentityTest.java new file mode 100644 index 0000000000..6c74c23c53 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationPendingIdentityTest.java @@ -0,0 +1,120 @@ +package net.firedevops.firemud.accountservice.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class AccountGameplayDelegationPendingIdentityTest { + private static final UUID OPERATION_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID REQUEST_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID ACCOUNT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID CALLER_CONTEXT_ID = + UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID TOKEN_JTI = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final String DIGEST = "ab".repeat(32); + + @Test + void preservesAllIdentityFieldsAndAcceptsTheExistingWorkloadBoundary() { + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + "x".repeat(256), + CALLER_CONTEXT_ID, + AccountGameplayCredentialRequestBindingFixture.binding(), + DIGEST, + TOKEN_JTI, + 10, + 11, + 12); + + assertEquals(OPERATION_ID, identity.operationId()); + assertEquals(REQUEST_ID, identity.requestId()); + assertEquals(ACCOUNT_ID, identity.accountId()); + assertEquals("x".repeat(256), identity.callerWorkload()); + assertEquals(CALLER_CONTEXT_ID, identity.callerContextId()); + assertEquals( + AccountGameplayCredentialRequestBindingFixture.binding(), + identity.credentialRequestBinding()); + assertEquals(DIGEST, identity.requestDigest()); + assertEquals(TOKEN_JTI, identity.tokenJti()); + assertEquals(10, identity.issuedAtEpochSecond()); + assertEquals(11, identity.notBeforeEpochSecond()); + assertEquals(12, identity.expiresAtEpochSecond()); + } + + @Test + void requiresTheExistingIdentityUuidFields() { + assertThrows(NullPointerException.class, () -> identity(null, REQUEST_ID, ACCOUNT_ID, "game")); + assertThrows( + NullPointerException.class, () -> identity(OPERATION_ID, null, ACCOUNT_ID, "game")); + assertThrows( + NullPointerException.class, () -> identity(OPERATION_ID, REQUEST_ID, null, "game")); + assertThrows( + NullPointerException.class, + () -> + new AccountGameplayDelegationPendingIdentity( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + "game", + null, + AccountGameplayCredentialRequestBindingFixture.binding(), + DIGEST, + TOKEN_JTI, + 10, + 11, + 12)); + assertThrows( + NullPointerException.class, + () -> + new AccountGameplayDelegationPendingIdentity( + OPERATION_ID, + REQUEST_ID, + ACCOUNT_ID, + "game", + CALLER_CONTEXT_ID, + AccountGameplayCredentialRequestBindingFixture.binding(), + DIGEST, + null, + 10, + 11, + 12)); + } + + @Test + void requiresTheExistingDigestAndCallerWorkloadShapes() { + assertThrows( + IllegalArgumentException.class, + () -> identity(OPERATION_ID, REQUEST_ID, ACCOUNT_ID, "game", null)); + assertThrows( + IllegalArgumentException.class, () -> identity(OPERATION_ID, REQUEST_ID, ACCOUNT_ID, null)); + assertThrows( + IllegalArgumentException.class, + () -> identity(OPERATION_ID, REQUEST_ID, ACCOUNT_ID, "x".repeat(257))); + } + + private static AccountGameplayDelegationPendingIdentity identity( + UUID operationId, UUID requestId, UUID accountId, String callerWorkload) { + return identity(operationId, requestId, accountId, callerWorkload, DIGEST); + } + + private static AccountGameplayDelegationPendingIdentity identity( + UUID operationId, UUID requestId, UUID accountId, String callerWorkload, String digest) { + return new AccountGameplayDelegationPendingIdentity( + operationId, + requestId, + accountId, + callerWorkload, + CALLER_CONTEXT_ID, + AccountGameplayCredentialRequestBindingFixture.binding(), + digest, + TOKEN_JTI, + 10, + 11, + 12); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java new file mode 100644 index 0000000000..de62ed19c3 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java @@ -0,0 +1,257 @@ +package net.firedevops.firemud.accountservice.repository; + +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.verifyNoInteractions; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.MountObservation; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner; +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.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtJwksPublicationRepositoryTest { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + 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"); + private static final UUID OPERATION_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String JWKS = "{\"keys\":[]}"; + private static final String MARKER = "{\"phase\":\"PREPUBLISHED\"}"; + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void currentReadsRemainMandatoryAccountTransactions() throws Exception { + assertMandatory("readCurrentIntent", Binding.class, TrustFence.class); + assertMandatory("readCurrentPublication", Binding.class, TrustFence.class); + assertMandatory("readPreparedPublicationForRecovery", Binding.class, TrustFence.class); + assertMandatory( + "recordPrepublicationIntent", + Binding.class, + TrustFence.class, + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .GenerationResult.class, + net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository + .GenerationRequest.class, + String.class, + String.class, + String.class, + String.class, + String.class, + String.class, + String.class); + } + + @Test + void lockingCurrentAndRecoveryReadsRejectReadOnlyOwnerTransactionsBeforeDatabaseAccess() + throws Exception { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository repository = + new AccountJwtJwksPublicationRepository(dsl, desired); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy(() -> repository.readCurrentIntent(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account JWT JWKS persistence transaction must be writable"); + assertThatThrownBy(() -> repository.readCurrentPublication(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account JWT JWKS persistence transaction must be writable"); + assertThatThrownBy(() -> repository.readPreparedPublicationForRecovery(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account JWT JWKS persistence transaction must be writable"); + + Transactional recoveryRead = + AccountJwtJwksPublicationRepository.class + .getMethod("readPreparedPublicationForRecovery", Binding.class, TrustFence.class) + .getAnnotation(Transactional.class); + assertThat(recoveryRead).isNotNull(); + assertThat(recoveryRead.readOnly()).isFalse(); + verifyNoInteractions(dsl, desired); + } + + @Test + void publicationRepositoryRejectsCallsOutsideAnOwningAccountTransaction() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository repository = + new AccountJwtJwksPublicationRepository(dsl, desired); + + assertThatThrownBy(() -> repository.readCurrentIntent(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owning Account transaction"); + + verifyNoInteractions(dsl, desired); + } + + @Test + void snapshotAndPublicDataDigestsBindEveryObservedPublicByte() { + String first = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", JWKS, "other.txt", "preserve")); + String sameDifferentOrder = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("other.txt", "preserve", "jwks.json", JWKS)); + String changed = + AccountJwtJwksPublicationRepository.snapshotDigest( + Map.of("jwks.json", JWKS, "other.txt", "changed")); + + assertThat(first).hasSize(64).isEqualTo(sameDifferentOrder).isNotEqualTo(changed); + assertThat(AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER)) + .isNotEqualTo(AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER + " ")); + } + + @Test + void immutableEvidenceDigestsBindIntentReceiptAndMountedCorrespondence() { + PrepublicationIntent intent = intent(); + PublicationReceipt receipt = PublicationReceipt.create(intent, "42"); + MountObservation observation = MountObservation.create(intent, receipt); + + assertThat(intent.intentDigest()).isEqualTo(PrepublicationIntent.digest(intent)); + assertThat(receipt.receiptDigest()).isEqualTo(PublicationReceipt.digest(receipt)); + assertThat(observation.observationDigest()).isEqualTo(MountObservation.digest(observation)); + assertThat(observation.publicationReceiptDigest()).isEqualTo(receipt.receiptDigest()); + assertThat(intent.jwksJson()).doesNotContain("privateKey", "\"d\""); + } + + @Test + void immutableEvidenceRejectsChangedDigestAndNonAdvancingRemoteReadback() { + PrepublicationIntent intent = intent(); + + assertThatThrownBy( + () -> + new PrepublicationIntent( + intent.operationId(), + intent.binding(), + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + intent.trustFence(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + intent.configMapName(), + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + intent.targetGeneration(), + intent.targetKid(), + intent.publicKeyFingerprint(), + intent.expectedDurableActive(), + intent.expectedPublishedActive(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + "f".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intent digest"); + + assertThatThrownBy( + () -> + new PrepublicationIntent( + intent.operationId(), + intent.binding(), + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + intent.trustFence(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + intent.configMapName(), + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + intent.targetGeneration(), + intent.targetKid(), + intent.publicKeyFingerprint(), + intent.expectedDurableActive(), + intent.expectedPublishedActive(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + "0".repeat(64))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("intent digest"); + + assertThatThrownBy(() -> PublicationReceipt.create(intent, intent.expectedResourceVersion())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("resourceVersion did not advance"); + } + + private static PrepublicationIntent intent() { + return PrepublicationIntent.create( + OPERATION_ID, + BINDING, + "b".repeat(64), + "c".repeat(64), + "d".repeat(64), + 2L, + TRUST, + "e".repeat(64), + "api-r1", + "jwt-jwks", + "44444444-4444-4444-8444-444444444444", + "41", + "f".repeat(64), + "1", + "jwt-1-test", + "9".repeat(64), + Optional.empty(), + Optional.empty(), + JWKS, + MARKER, + AccountJwtJwksPublicationRepository.publicDataDigest(JWKS, MARKER), + sha256(MARKER)); + } + + 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 ex) { + throw new IllegalStateException(ex); + } + } + + private static void assertMandatory(String method, Class... parameterTypes) throws Exception { + Transactional transactional = + AccountJwtJwksPublicationRepository.class + .getMethod(method, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java new file mode 100644 index 0000000000..281daec872 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.accountservice.repository; + +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.verifyNoInteractions; + +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +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.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtReadinessProbeRepositoryTest { + 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 + void requiresAnOwningAccountTransactionBeforeReadingOtherAuthorities() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository publication = + mock(AccountJwtJwksPublicationRepository.class); + AccountJwtReadinessProbeRepository repository = + new AccountJwtReadinessProbeRepository(dsl, desired, publication); + + assertThatThrownBy(() -> repository.planCurrent(BINDING, TRUST, Instant.ofEpochSecond(10_000))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owning Account transaction"); + + verifyNoInteractions(dsl, desired, publication); + } + + @Test + void promotionProofReadsRequireWritableOwnerTransactionForLockedEvidence() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository desired = + mock(AccountJwtSignerDesiredStateRepository.class); + AccountJwtJwksPublicationRepository publication = + mock(AccountJwtJwksPublicationRepository.class); + AccountJwtReadinessProbeRepository repository = + new AccountJwtReadinessProbeRepository(dsl, desired, publication); + UUID operationId = UUID.randomUUID(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy( + () -> repository.readCurrentPromotionPrerequisites(BINDING, TRUST, operationId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + assertThatThrownBy(() -> repository.readPromotionProof(BINDING, TRUST, operationId)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + } finally { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + verifyNoInteractions(dsl, desired, publication); + } + + @Test + void matrixIsCanonicalExplicitAndStillMarkedIncomplete() { + String matrix = AccountJwtReadinessProbeRepository.applicabilityMatrixJson(); + + assertThat(matrix) + .isEqualTo( + "{\"inventoryStatus\":\"PARTIAL_UNCONFIRMED\",\"schemaVersion\":1," + + "\"validators\":[{\"applicableProfiles\":[{\"audience\":\"control-ui\"," + + "\"tokenProfile\":\"control-ui\"},{\"audience\":\"player-bootstrap\"," + + "\"tokenProfile\":\"player-bootstrap\"},{\"audience\":\"account-service\"," + + "\"tokenProfile\":\"game-session-account-delegation\"}]," + + "\"validatorId\":\"account-service\"}]}"); + assertThat(matrix).doesNotContain("credential-authenticate-account"); + } + + @Test + void firstInstallFenceHasExactAbsentActiveAndPublishedPair() { + AccountJwtReadinessProbeRepository.SignerFence fence = + new AccountJwtReadinessProbeRepository.SignerFence(Optional.empty(), Optional.empty()); + + assertThat(fence.durableActive()).isEmpty(); + assertThat(fence.publishedActive()).isEmpty(); + assertThatThrownBy( + () -> + new AccountJwtReadinessProbeRepository.SignerFence( + Optional.empty(), + Optional.of( + new AccountJwtSignerDesiredStateRepository.ActiveSigner("1", "old-key")))) + .isInstanceOf(AccountJwtReadinessProbeRepository.QuarantinedStateException.class); + } + + @Test + void plannedFirstInstallEntryCarriesAnAbsentPreviousActiveFence() { + var entry = + new AccountJwtReadinessProbeRepository.ProbeEntry( + UUID.randomUUID(), + "a".repeat(64), + "account-service", + "game-session-account-delegation", + "account-service", + net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle + .ProbeKind.REPRESENTATIVE, + UUID.randomUUID(), + "1", + "first-key", + Optional.empty(), + 1, + 1, + 20_000, + 20_300, + AccountJwtReadinessProbeRepository.ProbeState.PLANNED, + Optional.empty(), + Optional.empty(), + Optional.empty(), + Optional.empty()); + + assertThat(entry.expectedActive()).isEmpty(); + assertThat(entry.state()).isEqualTo(AccountJwtReadinessProbeRepository.ProbeState.PLANNED); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java new file mode 100644 index 0000000000..6561bbb11d --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java @@ -0,0 +1,1441 @@ +package net.firedevops.firemud.accountservice.repository; + +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.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 java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.interfaces.RSAPublicKey; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; +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.PromotionPreparation; +import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +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.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +class AccountJwtSignerDesiredStateRepositoryTest { + private static final Binding BINDING = + new Binding( + "prod", + "prod-cluster-1", + "firemud-prod", + 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), + "binding-r1"); + private static final UUID SECRET_UID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final String READINESS_EVIDENCE_PREIMAGE = "{\"verifiedProbes\":[{}]}"; + private static final EnrollmentIdentity ENROLLMENT = + new EnrollmentIdentity( + TRUST.expectedClusterIncarnationUid(), + TRUST.expectedNamespaceUid(), + TRUST.bindingDigest(), + TRUST.configRevision(), + "b".repeat(64), + "api-r1", + "44444444-4444-4444-8444-444444444444", + "12", + "c".repeat(64)); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void durableGenerationEntryPointsRequireAnAccountTransaction() throws Exception { + assertMandatory("initialize", Binding.class, EnrollmentIdentity.class); + assertMandatory("read", Binding.class); + assertMandatory("ensureCurrentGenerationRequest", Binding.class, TrustFence.class); + assertMandatoryWritable( + "abortUnpreparedGeneration", Binding.class, TrustFence.class, GenerationResult.class); + assertMandatory("readCurrentGenerationRequest", Binding.class, TrustFence.class); + assertMandatory( + "recordSecretObservation", + Binding.class, + TrustFence.class, + UUID.class, + String.class, + String.class, + String.class); + assertMandatory( + "recordGenerationResult", + Binding.class, + TrustFence.class, + UUID.class, + String.class, + String.class, + String.class, + String.class, + String.class); + assertMandatoryWritable("readPreparedGenerationForRecovery", Binding.class, TrustFence.class); + assertMandatoryWritable( + "readAndMarkPreparedPromotionDispatched", Binding.class, TrustFence.class); + assertMandatoryWritable( + "readCurrentCommittedSigner", Binding.class, TrustFence.class, String.class, String.class); + assertMandatoryWritable( + "commitPreparedPromotion", + Binding.class, + TrustFence.class, + UUID.class, + ReadinessPromotionProof.class); + assertMandatoryWritable( + "prepareCurrentGeneration", + Binding.class, + TrustFence.class, + PromotionPreparation.class, + ReadinessPromotionProof.class); + } + + @Test + void promotionCommitRequiresOwnerCreatedReadinessProofBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + repository.commitPreparedPromotion( + BINDING, + TRUST, + UUID.fromString("44444444-4444-4444-8444-444444444444"), + null))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("readiness proof"); + verifyNoInteractions(dsl); + } + + @Test + void lockedPromotionReadsRejectReadOnlyTransactionsBeforeSql() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + try { + assertThatThrownBy(() -> repository.readPreparedGenerationForRecovery(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); + assertThatThrownBy(() -> repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable Account transaction"); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + @Test + void preparedPromotionDispatchReturnsReadbackAndRetryDoesNotRepeatCas() throws Exception { + Conversation conversation = new Conversation(); + GenerationRequest request = inWritableTransaction(conversation::ensureRequest); + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + request.operationId(), + request.operationDigest(), + SECRET_UID.toString(), + "12")); + PublicJwk jwk = publicJwk(request.targetKid()); + GenerationResult result = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + request.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + conversation.preparePromotionForDispatch(request, result); + + var first = + inWritableTransaction( + () -> conversation.repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST)); + assertThat(first.promotion().privatePromotionDispatched()).isTrue(); + assertThat(conversation.promotionDispatchCasCount).isEqualTo(1); + + var retry = + inWritableTransaction( + () -> conversation.repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST)); + assertThat(retry.promotion().privatePromotionDispatched()).isTrue(); + assertThat(retry).isEqualTo(first); + assertThat(conversation.promotionDispatchCasCount).isEqualTo(1); + } + + @Test + void preparedPromotionDispatchRejectsExpiredReadinessBeforeDurableDispatch() throws Exception { + Conversation conversation = new Conversation(); + GenerationRequest request = inWritableTransaction(conversation::ensureRequest); + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + request.operationId(), + request.operationDigest(), + SECRET_UID.toString(), + "12")); + PublicJwk jwk = publicJwk(request.targetKid()); + GenerationResult result = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + request.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + conversation.preparePromotionForDispatch(request, result); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> conversation.repository.readCurrentGenerationRequest(BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) + .hasMessageContaining( + "Existing PREPARED signer state requires unavailable lifecycle evidence"); + conversation.expireReadinessPlan(); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.readAndMarkPreparedPromotionDispatched( + BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) + .hasMessageContaining("expired before private dispatch"); + assertThat(conversation.promotionDispatchCasCount).isZero(); + assertThat(conversation.executedStatements) + .noneMatch(sql -> sql.contains("UPDATE account_jwt_signer_promotion_operations")); + } + + @Test + void preparedPromotionDispatchCasRechecksReadinessDeadlineAtomically() throws Exception { + Conversation conversation = new Conversation(); + GenerationRequest request = inWritableTransaction(conversation::ensureRequest); + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + request.operationId(), + request.operationDigest(), + SECRET_UID.toString(), + "12")); + PublicJwk jwk = publicJwk(request.targetKid()); + GenerationResult result = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + request.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + conversation.preparePromotionForDispatch(request, result); + conversation.expireReadinessAtDispatchCas(); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.readAndMarkPreparedPromotionDispatched( + BINDING, TRUST))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.VersionConflictException.class); + assertThat(conversation.promotionDispatchCasCount).isZero(); + assertThat(conversation.executedStatements) + .anySatisfy( + sql -> { + assertThat(sql).contains("WITH readiness_clock AS MATERIALIZED"); + assertThat(sql).contains("clock_timestamp()"); + assertThat(sql).contains("plan.expires_at_epoch_seconds"); + assertThat(sql).contains("entry.expires_at_epoch_seconds"); + assertThat(sql).doesNotContain("CURRENT_TIMESTAMP"); + }); + } + + @Test + void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() throws Exception { + Conversation conversation = new Conversation(); + GenerationRequest request = inWritableTransaction(conversation::ensureRequest); + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + request.operationId(), + request.operationDigest(), + SECRET_UID.toString(), + "12")); + PublicJwk jwk = publicJwk(request.targetKid()); + GenerationResult result = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + request.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + conversation.preparePromotionForDispatch(request, result); + ReadinessPromotionProof exactProof = + conversation.readinessProof( + result, READINESS_EVIDENCE_PREIMAGE.getBytes(StandardCharsets.UTF_8)); + + conversation.expireReadinessPlan(); + conversation.recordPromotionReceipts(result); + int statementsBeforeUndeliveredRecovery = conversation.executedStatements.size(); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.commitPreparedPromotion( + BINDING, TRUST, conversation.preparedPromotionId, exactProof))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) + .hasMessageContaining( + "Promotion dispatch state is inconsistent with its receipts or terminal status"); + assertThat( + conversation.executedStatements.subList( + statementsBeforeUndeliveredRecovery, conversation.executedStatements.size())) + .noneMatch(sql -> sql.contains("SET status = 'COMMITTED'")); + + conversation.preparedPromotionValues.put("private_promotion_receipt_digest", null); + conversation.preparedPromotionValues.put("private_promotion_observed_resource_version", null); + conversation.preparedPromotionValues.put("active_jwks_receipt_digest", null); + conversation.preparedPromotionValues.put("active_jwks_public_data_digest", null); + conversation.preparedPromotionValues.put("active_jwks_observed_resource_version", null); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.readAndMarkPreparedPromotionDispatched( + BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) + .hasMessageContaining("expired before private dispatch"); + assertThat(conversation.promotionDispatchCasCount).isZero(); + conversation.readinessPlanExpired = false; + + inWritableTransaction( + () -> conversation.repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST)); + conversation.recordPromotionReceipts(result); + conversation.expireReadinessPlan(); + Record expiredPlan = conversation.readinessPlanRow(); + assertThat(expiredPlan.get("checked_epoch", Long.class)) + .isGreaterThan(expiredPlan.get("expires_at_epoch_seconds", Long.class)); + + TrustFence changedTrust = + new TrustFence( + TRUST.expectedClusterIncarnationUid(), + TRUST.expectedNamespaceUid(), + TRUST.bindingDigest(), + "binding-r2"); + int statementsBeforeChangedTrust = conversation.executedStatements.size(); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.commitPreparedPromotion( + BINDING, changedTrust, conversation.preparedPromotionId, exactProof))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.BindingMismatchException.class) + .hasMessageContaining("pinned enrollment"); + assertThat( + conversation.executedStatements.subList( + statementsBeforeChangedTrust, conversation.executedStatements.size())) + .noneMatch(sql -> sql.contains("SET status = 'COMMITTED'")); + + conversation.changePreparedStateForCommit(); + int statementsBeforeChangedState = conversation.executedStatements.size(); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.commitPreparedPromotion( + BINDING, TRUST, conversation.preparedPromotionId, exactProof))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) + .hasMessageContaining("exact desired-state fence"); + assertThat( + conversation.executedStatements.subList( + statementsBeforeChangedState, conversation.executedStatements.size())) + .noneMatch(sql -> sql.contains("SET status = 'COMMITTED'")); + conversation.restorePreparedStateForCommit(); + + byte[] changedPreimage = READINESS_EVIDENCE_PREIMAGE.getBytes(StandardCharsets.UTF_8); + changedPreimage[0] ^= 1; + ReadinessPromotionProof changedProof = conversation.readinessProof(result, changedPreimage); + int statementsBeforeChangedProof = conversation.executedStatements.size(); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.commitPreparedPromotion( + BINDING, TRUST, conversation.preparedPromotionId, changedProof))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class) + .hasMessageContaining("frozen PREPARED evidence"); + assertThat( + conversation.executedStatements.subList( + statementsBeforeChangedProof, conversation.executedStatements.size())) + .noneMatch(sql -> sql.contains("SET status = 'COMMITTED'")); + + String exactPrivateReceiptDigest = + (String) conversation.preparedPromotionValues.get("private_promotion_receipt_digest"); + conversation.preparedPromotionValues.put("private_promotion_receipt_digest", "0".repeat(64)); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.commitPreparedPromotion( + BINDING, TRUST, conversation.preparedPromotionId, exactProof))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) + .hasMessageContaining("private promotion receipt digest is invalid"); + conversation.preparedPromotionValues.put("status", "PREPARED"); + conversation.preparedPromotionValues.put( + "private_promotion_receipt_digest", exactPrivateReceiptDigest); + + var committed = + inWritableTransaction( + () -> + conversation.repository.commitPreparedPromotion( + BINDING, TRUST, conversation.preparedPromotionId, exactProof)); + assertThat(committed.promotion().status()).isEqualTo("COMMITTED"); + assertThat(committed.desiredState().recordVersion()).isEqualTo(4L); + String terminalUpdate = + conversation.executedStatements.stream() + .filter(sql -> sql.contains("SET status = 'COMMITTED'")) + .findFirst() + .orElseThrow(); + assertThat(terminalUpdate) + .contains("readiness_evidence_preimage") + .contains("entry.verified_at_epoch_seconds < entry.expires_at_epoch_seconds") + .doesNotContain("plan.expires_at_epoch_seconds", "CURRENT_TIMESTAMP", "clock_timestamp"); + } + + @Test + void accountCreatesAndReplaysOnlyItsOwnBoundGenerationRequest() { + Conversation conversation = new Conversation(); + + GenerationRequest first = inWritableTransaction(conversation::ensureRequest); + GenerationRequest retry = inWritableTransaction(conversation::ensureRequest); + + assertThat(first).isEqualTo(retry); + assertThat(first.phase()).isEqualTo(GenerationPhase.OBSERVE_PRIVATE_SECRET); + assertThat(first.operationId().version()).isEqualTo(4); + assertThat(first.operationDigest()).hasSize(64); + assertThat(first.desiredStateVersion()).isEqualTo(2); + assertThat(first.targetGeneration()).isEqualTo("1"); + assertThat(first.targetKid()).startsWith("jwt-1-"); + assertThat(first.expectedActive()).isEmpty(); + assertThat(first.expectedPublishedActive()).isEmpty(); + assertThat(first.privateSecretName()).isEqualTo("jwt-signing-keys"); + assertThat(first.expectedSecretResourceVersion()).isEmpty(); + assertThat(first.publicKeyFingerprint()).isEmpty(); + assertThat(first.publicJwkJson()).isEmpty(); + assertThat(conversation.operationInsert).isNotNull(); + assertThat(conversation.executedStatements) + .anyMatch(sql -> sql.contains("account_jwt_signer_generation_operations")) + .anyMatch(sql -> sql.contains("generation_operation_id")) + .noneMatch(sql -> sql.contains("target_public_key_fingerprint")); + verify(conversation.dsl, times(2)).execute(anyString(), any(Object[].class)); + } + + @Test + void historicalAbortedGenerationHighWaterPreventsReuseWithoutActiveSigner() { + Conversation conversation = new Conversation(1L); + + GenerationRequest next = inWritableTransaction(conversation::ensureRequest); + + assertThat(next.targetGeneration()).isEqualTo("2"); + assertThat(next.expectedActive()).isEmpty(); + assertThat(next.expectedPublishedActive()).isEmpty(); + assertThat(conversation.executedStatements) + .anyMatch(sql -> sql.contains("account_jwt_signer_generation_operations")); + verify(conversation.dsl) + .fetchOne( + org.mockito.ArgumentMatchers.argThat( + sql -> + sql.contains("COALESCE(MAX(target_generation), 0)") + && sql.contains("account_jwt_signer_generation_operations")), + any(Object[].class)); + } + + @Test + void generationRequestDefensivelyCopiesItsValidatedPrivateSlots() { + Conversation conversation = new Conversation(); + GenerationRequest source = inWritableTransaction(conversation::ensureRequest); + List suppliedSlots = new ArrayList<>(source.allowedPrivateSlots()); + + GenerationRequest copied = + new GenerationRequest( + source.phase(), + source.operationId(), + source.operationDigest(), + source.generationRequestDigest(), + source.desiredStateVersion(), + source.binding(), + source.trustFence(), + source.privateSecretName(), + source.targetGeneration(), + source.targetKid(), + source.targetAlgorithm(), + source.operationAction(), + suppliedSlots, + source.expectedActive(), + source.expectedPublishedActive(), + source.secretUid(), + source.expectedSecretResourceVersion(), + source.generationReceiptDigest(), + source.publicKeyFingerprint(), + source.publicJwkJson(), + source.observedSecretResourceVersion()); + + suppliedSlots.clear(); + + assertThat(copied.allowedPrivateSlots()).containsExactly("pending"); + assertThatThrownBy(() -> copied.allowedPrivateSlots().add("current")) + .isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void committedActiveSignerNeedsAnExplicitDurableRotationRequest() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + Map values = new HashMap<>(); + values.put("environment_id", BINDING.environmentId()); + values.put("cluster_id", BINDING.clusterId()); + values.put("kubernetes_namespace", BINDING.namespace()); + values.put("custody_mode", BINDING.mode().value()); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put( + "public_jwks_config_map_name", + AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME); + values.put("record_version", 8L); + values.put("durable_active_generation", 4L); + values.put("durable_active_kid", "jwt-4-active"); + values.put("published_active_generation", 4L); + values.put("published_active_kid", "jwt-4-active"); + values.put("generation_operation_id", null); + values.put("prepared_operation_id", null); + values.put( + "enrollment_cluster_incarnation_uid", + UUID.fromString(TRUST.expectedClusterIncarnationUid())); + values.put("enrollment_namespace_uid", UUID.fromString(TRUST.expectedNamespaceUid())); + values.put("enrollment_materializer_binding_digest", TRUST.bindingDigest()); + values.put("enrollment_materializer_config_revision", TRUST.configRevision()); + values.put("enrollment_api_binding_digest", "b".repeat(64)); + values.put("enrollment_api_config_revision", "api-r1"); + values.put( + "enrollment_public_config_map_uid", + UUID.fromString("33333333-3333-4333-8333-333333333333")); + values.put("enrollment_public_config_map_resource_version", "12"); + values.put("enrollment_public_config_map_snapshot_digest", "c".repeat(64)); + Record activeState = record(values); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(activeState); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> repository.ensureCurrentGenerationRequest(BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class) + .hasMessageContaining("durable rotation request"); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void secretObservationUnlocksOnlyTheExactGenerationFenceAndChangedReplayConflicts() { + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + GenerationRequest replay = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + + assertThat(pending.phase()).isEqualTo(GenerationPhase.GENERATE_PENDING); + assertThat(pending.generationRequestDigest()).hasSize(64); + assertThat(pending.secretUid()).isEqualTo(SECRET_UID.toString()); + assertThat(pending.expectedSecretResourceVersion()).isEqualTo("12"); + assertThat(pending.publicKeyFingerprint()).isEmpty(); + assertThat(replay).isEqualTo(pending); + int executedBeforeConflict = conversation.executedStatements.size(); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "changed-rv"))) + .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); + assertThat(conversation.executedStatements).hasSize(executedBeforeConflict); + } + + @Test + void generationReceiptDerivesCanonicalRsaFingerprintAndRemainsNonPromoting() throws Exception { + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + GenerationRequest pending = + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); + PublicJwk jwk = publicJwk(operation.targetKid()); + + GenerationResult result = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + operation.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + GenerationResult replay = + inWritableTransaction( + () -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + operation.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); + + assertThat(result).isEqualTo(replay); + assertThat(result.publicKeyFingerprint()).isEqualTo(jwk.fingerprint()); + assertThat(result.expectedPriorResourceVersion()).isEqualTo("12"); + assertThat(result.observedResourceVersion()).isEqualTo("13"); + assertThat(result.publicJwkJson()).doesNotContain("\"d\""); + int executedBeforePromotionAttempt = conversation.executedStatements.size(); + PromotionPreparation callerSuppliedPreparation = + new PromotionPreparation( + result.operationId(), + result, + ENROLLMENT, + "b".repeat(64), + "api-r1", + "44444444-4444-4444-8444-444444444444", + "14", + "d".repeat(64), + "e".repeat(64), + "f".repeat(64), + "1".repeat(64), + "2".repeat(64), + "{\"keys\":[" + result.publicJwkJson() + "]}"); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.prepareCurrentGeneration( + BINDING, TRUST, callerSuppliedPreparation, null))) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("Account-verified readiness proof is required"); + assertThat(conversation.executedStatements).hasSize(executedBeforePromotionAttempt); + } + + @Test + void absentOperationAndWrongCurrentOperationFailBeforeAnyMutation() { + DSLContext emptyDsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository emptyRepository = + new AccountJwtSignerDesiredStateRepository(emptyDsl); + Record emptyState = stateRow(BINDING, 1, null, null, null, null, null); + when(emptyDsl.fetchOne(anyString(), any(Object[].class))).thenReturn(emptyState); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> emptyRepository.readCurrentGenerationRequest(BINDING, TRUST))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class); + verify(emptyDsl, never()).execute(anyString(), any(Object[].class)); + + Conversation conversation = new Conversation(); + GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); + UUID wrongOperation = UUID.fromString("55555555-5555-4555-8555-555555555555"); + int executedBeforeStaleCall = conversation.executedStatements.size(); + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + wrongOperation, + operation.operationDigest(), + SECRET_UID.toString(), + "12"))) + .isInstanceOf( + AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException.class); + assertThat(conversation.executedStatements).hasSize(executedBeforeStaleCall); + } + + @Test + void privateOrMalformedPublicJwkIsRejectedBeforeStorageAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + + assertThatThrownBy( + () -> + inWritableTransaction( + () -> + repository.recordGenerationResult( + BINDING, + TRUST, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "a".repeat(64), + SECRET_UID.toString(), + "12", + "13", + "{\"d\":\"private\"}"))) + .isInstanceOf(IllegalArgumentException.class); + verify(dsl, never()).fetchOne(anyString(), any(Object[].class)); + verify(dsl, never()).execute(anyString(), any(Object[].class)); + } + + @Test + void initializationStaysExplicitAndNonAuthorizing() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + Record initializedState = stateRow(BINDING, 1, null, null, null, null, null); + when(dsl.execute(anyString(), any(Object[].class))).thenReturn(1); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(initializedState); + + var state = inWritableTransaction(() -> repository.initialize(BINDING, ENROLLMENT)); + + assertThat(state.recordVersion()).isEqualTo(1); + assertThat(state.durableActive()).isEmpty(); + assertThat(state.publishedActive()).isEmpty(); + assertThat(state.generationOperationId()).isEmpty(); + assertThat(state.preparedOperationId()).isEmpty(); + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bindings = ArgumentCaptor.forClass(Object[].class); + verify(dsl).execute(sql.capture(), bindings.capture()); + assertThat(sql.getValue()) + .contains("generation_operation_id") + .contains("prepared_operation_id"); + Object[] values = bindings.getValue(); + assertThat(values[4]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.expectedClusterIncarnationUid())); + assertThat(values[5]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.expectedNamespaceUid())); + assertThat(values[10]) + .isInstanceOf(UUID.class) + .isEqualTo(UUID.fromString(ENROLLMENT.publicConfigMapUid())); + } + + private void assertMandatory(String methodName, Class... parameterTypes) + throws ReflectiveOperationException { + Transactional transactional = + AccountJwtSignerDesiredStateRepository.class + .getMethod(methodName, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + } + + private void assertMandatoryWritable(String methodName, Class... parameterTypes) + throws ReflectiveOperationException { + Transactional transactional = + AccountJwtSignerDesiredStateRepository.class + .getMethod(methodName, parameterTypes) + .getAnnotation(Transactional.class); + assertThat(transactional).isNotNull(); + assertThat(transactional.propagation()).isEqualTo(Propagation.MANDATORY); + assertThat(transactional.readOnly()).isFalse(); + } + + private static Record stateRow( + Binding binding, + long version, + Long durableGeneration, + String durableKid, + Long publishedGeneration, + String publishedKid, + UUID generationOperationId) { + return stateRow( + binding, + version, + durableGeneration, + durableKid, + publishedGeneration, + publishedKid, + generationOperationId, + null); + } + + private static Record stateRow( + Binding binding, + long version, + Long durableGeneration, + String durableKid, + Long publishedGeneration, + String publishedKid, + UUID generationOperationId, + UUID preparedOperationId) { + Map values = new HashMap<>(); + values.put("environment_id", binding.environmentId()); + values.put("cluster_id", binding.clusterId()); + values.put("kubernetes_namespace", binding.namespace()); + values.put("custody_mode", binding.mode().value()); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put( + "public_jwks_config_map_name", + AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME); + values.put("record_version", version); + values.put("durable_active_generation", durableGeneration); + values.put("durable_active_kid", durableKid); + values.put("published_active_generation", publishedGeneration); + values.put("published_active_kid", publishedKid); + values.put("generation_operation_id", generationOperationId); + values.put("prepared_operation_id", preparedOperationId); + values.put( + "enrollment_cluster_incarnation_uid", + UUID.fromString(ENROLLMENT.expectedClusterIncarnationUid())); + values.put("enrollment_namespace_uid", UUID.fromString(ENROLLMENT.expectedNamespaceUid())); + values.put( + "enrollment_materializer_binding_digest", ENROLLMENT.materializerTrustBindingDigest()); + values.put( + "enrollment_materializer_config_revision", ENROLLMENT.materializerTrustConfigRevision()); + values.put("enrollment_api_binding_digest", ENROLLMENT.apiBindingDigest()); + values.put("enrollment_api_config_revision", ENROLLMENT.apiConfigRevision()); + values.put( + "enrollment_public_config_map_uid", UUID.fromString(ENROLLMENT.publicConfigMapUid())); + values.put( + "enrollment_public_config_map_resource_version", + ENROLLMENT.publicConfigMapResourceVersion()); + values.put( + "enrollment_public_config_map_snapshot_digest", ENROLLMENT.publicConfigMapSnapshotDigest()); + return record(values); + } + + private static Record generationOperationRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest_version", 1); + values.put("operation_digest", parameters[5]); + values.put("expected_record_version", parameters[6]); + values.put("expected_previous_generation", parameters[7]); + values.put("expected_previous_kid", parameters[8]); + values.put("expected_published_generation", parameters[9]); + values.put("expected_published_kid", parameters[10]); + values.put("target_generation", parameters[11]); + values.put("target_kid", parameters[12]); + values.put("target_algorithm", parameters[13]); + values.put("expected_cluster_incarnation_uid", parameters[14]); + values.put("expected_namespace_uid", parameters[15]); + values.put("trust_binding_digest", parameters[16]); + values.put("trust_config_revision", parameters[17]); + values.put("operation_action", "MATERIALIZE_PENDING"); + values.put("allowed_private_slots_canonical_bytes", parameters[18]); + return record(values); + } + + private static Record secretObservationRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest", parameters[5]); + values.put("expected_record_version", parameters[6]); + values.put("expected_cluster_incarnation_uid", parameters[7]); + values.put("expected_namespace_uid", parameters[8]); + values.put("trust_binding_digest", parameters[9]); + values.put("trust_config_revision", parameters[10]); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put("secret_uid", parameters[11]); + values.put("observed_resource_version", parameters[12]); + values.put("observation_digest", parameters[13]); + values.put("generation_request_digest", parameters[14]); + return record(values); + } + + private static Record generationResultRow(Object[] parameters) { + Map values = new HashMap<>(); + values.put("operation_id", parameters[0]); + values.put("environment_id", parameters[1]); + values.put("cluster_id", parameters[2]); + values.put("kubernetes_namespace", parameters[3]); + values.put("custody_mode", parameters[4]); + values.put("operation_digest", parameters[5]); + values.put("generation_request_digest", parameters[6]); + values.put("desired_state_version", parameters[7]); + values.put("expected_cluster_incarnation_uid", parameters[8]); + values.put("expected_namespace_uid", parameters[9]); + values.put("trust_binding_digest", parameters[10]); + values.put("trust_config_revision", parameters[11]); + values.put("private_secret_name", AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME); + values.put("secret_uid", parameters[12]); + values.put("expected_prior_resource_version", parameters[13]); + values.put("observed_resource_version", parameters[14]); + values.put("target_generation", parameters[15]); + values.put("target_kid", parameters[16]); + values.put("target_algorithm", "RS256"); + values.put("public_key_fingerprint", parameters[17]); + values.put("public_jwk_json", parameters[18]); + values.put("receipt_digest", parameters[19]); + return record(values); + } + + private static String promotionRequestDigest( + UUID promotionId, + GenerationRequest generation, + GenerationResult result, + String publicJwksJson) + throws Exception { + Map preimage = new HashMap<>(); + preimage.put("digestVersion", "account-jwt-signer-promotion-operation/v1"); + preimage.put("operationId", promotionId.toString()); + preimage.put("generationOperationId", generation.operationId().toString()); + preimage.put("generationOperationDigest", generation.operationDigest()); + preimage.put("generationReceiptDigest", result.receiptDigest()); + preimage.put("environmentId", BINDING.environmentId()); + preimage.put("clusterId", BINDING.clusterId()); + preimage.put("namespace", BINDING.namespace()); + preimage.put("custodyMode", BINDING.mode().value()); + preimage.put("expectedRecordVersion", "2"); + preimage.put("expectedPreviousActive", Map.of("present", false)); + preimage.put("expectedPublishedActive", Map.of("present", false)); + preimage.put("targetGeneration", generation.targetGeneration()); + preimage.put("targetKid", generation.targetKid()); + preimage.put("targetAlgorithm", "RS256"); + preimage.put("targetPublicKeyFingerprint", result.publicKeyFingerprint()); + preimage.put("expectedPrivateSecretUid", result.secretUid()); + preimage.put("expectedPrivateSecretResourceVersion", result.observedResourceVersion()); + preimage.put("expectedPublicConfigMapUid", ENROLLMENT.publicConfigMapUid()); + preimage.put("expectedPublicJwksResourceVersion", "14"); + preimage.put("expectedClusterIncarnationUid", TRUST.expectedClusterIncarnationUid()); + preimage.put("expectedNamespaceUid", TRUST.expectedNamespaceUid()); + preimage.put("materializerTrustBindingDigest", TRUST.bindingDigest()); + preimage.put("materializerTrustConfigRevision", TRUST.configRevision()); + preimage.put("apiBindingDigest", ENROLLMENT.apiBindingDigest()); + preimage.put("apiConfigRevision", ENROLLMENT.apiConfigRevision()); + preimage.put("prepublicationIntentDigest", "d".repeat(64)); + preimage.put("prepublicationReceiptDigest", "e".repeat(64)); + preimage.put("mountedObservationDigest", "f".repeat(64)); + preimage.put("readinessPlanDigest", "1".repeat(64)); + preimage.put("readinessEvidenceDigest", sha256(READINESS_EVIDENCE_PREIMAGE)); + preimage.put("publicJwksSha256", sha256(publicJwksJson)); + preimage.put("operationAction", "PROMOTE_PENDING"); + preimage.put("allowedPrivateSlots", List.of("current", "pending", "previous")); + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(preimage)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } + + private static String sha256(String value) throws Exception { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); + } + + private static PublicJwk publicJwk(String kid) throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + RSAPublicKey key = (RSAPublicKey) generator.generateKeyPair().getPublic(); + String modulus = encodeUnsigned(key.getModulus()); + String exponent = encodeUnsigned(key.getPublicExponent()); + Map jwk = new java.util.TreeMap<>(); + 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 = + new String( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(jwk)), + StandardCharsets.UTF_8); + String fingerprint = + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest( + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder() + .build() + .writeValueAsString( + Map.of("e", exponent, "kty", "RSA", "n", modulus))))); + return new PublicJwk(json, fingerprint); + } + + private static String encodeUnsigned(BigInteger value) { + byte[] bytes = value.toByteArray(); + int offset = bytes.length > 1 && bytes[0] == 0 ? 1 : 0; + return java.util.Base64.getUrlEncoder() + .withoutPadding() + .encodeToString(java.util.Arrays.copyOfRange(bytes, offset, bytes.length)); + } + + @SuppressWarnings({"rawtypes", "unchecked"}) + private static Record record(Map values) { + Record row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(invocation -> values.get(invocation.getArgument(0))); + return row; + } + + private static Record scalarLongRecord(long value) { + Record row = mock(Record.class); + when(row.get(0, Long.class)).thenReturn(value); + return row; + } + + private static T inWritableTransaction(java.util.function.Supplier operation) { + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + try { + return operation.get(); + } finally { + TransactionSynchronizationManager.clear(); + } + } + + private record PublicJwk(String json, String fingerprint) {} + + private final class Conversation { + private final DSLContext dsl = mock(DSLContext.class); + private final AccountJwtSignerDesiredStateRepository repository = + new AccountJwtSignerDesiredStateRepository(dsl); + private final List executedStatements = new java.util.ArrayList<>(); + private final long historicalGenerationHighWater; + private Object[] operationInsert; + private Object[] observationInsert; + private Object[] resultInsert; + private int stateReadCount; + private UUID preparedPromotionId; + private Map preparedPromotionValues; + private int promotionDispatchCasCount; + private boolean readinessPlanExpired; + private boolean readinessExpiresAtDispatchCas; + private boolean preparedStateChangedForCommit; + + private Conversation() { + this(0L); + } + + private Conversation(long historicalGenerationHighWater) { + this.historicalGenerationHighWater = historicalGenerationHighWater; + when(dsl.execute(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + Object[] arguments = invocation.getArguments(); + Object[] parameters = + arguments.length == 2 && arguments[1] instanceof Object[] bindings + ? bindings + : java.util.Arrays.copyOfRange(arguments, 1, arguments.length); + executedStatements.add(sql); + if (sql.contains("UPDATE account_jwt_signer_promotion_operations")) { + if (sql.contains( + "private_promotion_dispatched_at = readiness_clock.checked_at")) { + if (readinessExpiresAtDispatchCas) { + return 0; + } + promotionDispatchCasCount++; + preparedPromotionValues.put("private_promotion_dispatched", true); + } else if (sql.contains("SET status = 'COMMITTED'")) { + preparedPromotionValues.put("status", "COMMITTED"); + } + } + if (sql.contains("account_jwt_signer_generation_operations")) { + operationInsert = parameters.clone(); + } else if (sql.contains("account_jwt_signer_secret_observations")) { + observationInsert = parameters.clone(); + } else if (sql.contains("account_jwt_signer_generation_results")) { + resultInsert = parameters.clone(); + } + return 1; + }); + when(dsl.fetchOne(anyString(), any(Object[].class))) + .thenAnswer( + invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("account_jwt_signer_promotion_operations")) { + return preparedPromotionValues == null ? null : record(preparedPromotionValues); + } + if (sql.contains("account_jwt_readiness_probe_plans")) { + return preparedPromotionValues == null ? null : readinessPlanRow(); + } + if (sql.contains("account_jwt_readiness_probe_entries")) { + return record(Map.of("total", 1L, "verified", 1L)); + } + if (sql.contains("account_jwt_signer_desired_states")) { + stateReadCount++; + if (preparedPromotionId != null) { + if ("COMMITTED".equals(preparedPromotionValues.get("status"))) { + long activeGeneration = + ((Number) preparedPromotionValues.get("target_generation")).longValue(); + return stateRow( + BINDING, + 4, + activeGeneration, + (String) preparedPromotionValues.get("target_kid"), + activeGeneration, + (String) preparedPromotionValues.get("target_kid"), + null, + null); + } + if (preparedStateChangedForCommit) { + return stateRow( + BINDING, 4, null, null, null, null, null, preparedPromotionId); + } + return stateRow(BINDING, 3, null, null, null, null, null, preparedPromotionId); + } + return stateReadCount == 1 + ? stateRow(BINDING, 1, null, null, null, null, null) + : stateRow( + BINDING, + 2, + null, + null, + null, + null, + operationInsert == null ? null : (UUID) operationInsert[0]); + } + if (sql.contains("COALESCE(MAX(target_generation), 0)")) { + return scalarLongRecord(historicalGenerationHighWater); + } + if (sql.contains("account_jwt_signer_generation_operations")) { + return operationInsert == null ? null : generationOperationRow(operationInsert); + } + if (sql.contains("account_jwt_signer_generation_results")) { + return resultInsert == null ? null : generationResultRow(resultInsert); + } + if (sql.contains("account_jwt_signer_secret_observations")) { + return observationInsert == null ? null : secretObservationRow(observationInsert); + } + return null; + }); + } + + private GenerationRequest ensureRequest() { + return repository.ensureCurrentGenerationRequest(BINDING, TRUST); + } + + private void expireReadinessPlan() { + readinessPlanExpired = true; + } + + private void changePreparedStateForCommit() { + preparedStateChangedForCommit = true; + } + + private void restorePreparedStateForCommit() { + preparedStateChangedForCommit = false; + } + + private void expireReadinessAtDispatchCas() { + readinessExpiresAtDispatchCas = true; + } + + private Record readinessPlanRow() { + Map values = new HashMap<>(); + values.put("plan_digest", preparedPromotionValues.get("readiness_plan_digest")); + values.put("operation_digest", resultInsert[5]); + values.put("generation_request_digest", resultInsert[6]); + values.put("generation_receipt_digest", resultInsert[19]); + values.put("desired_state_version", resultInsert[7]); + values.put("target_generation", Long.parseLong(String.valueOf(resultInsert[15]))); + values.put("target_kid", resultInsert[16]); + values.put("target_public_key_fingerprint", resultInsert[17]); + values.put( + "publication_intent_digest", preparedPromotionValues.get("prepublication_intent_digest")); + values.put( + "publication_receipt_digest", + preparedPromotionValues.get("prepublication_receipt_digest")); + values.put( + "mounted_observation_digest", preparedPromotionValues.get("mounted_observation_digest")); + values.put("validator_inventory_complete", true); + values.put("not_before_epoch_seconds", 100L); + values.put("expires_at_epoch_seconds", readinessPlanExpired ? 149L : 200L); + values.put("checked_epoch", 150L); + return record(values); + } + + private ReadinessPromotionProof readinessProof(GenerationResult result, byte[] preimage) + throws Exception { + var plan = mock(AccountJwtReadinessProbeRepository.ReadinessProbePlan.class); + when(plan.operationId()).thenReturn(result.operationId()); + when(plan.binding()).thenReturn(BINDING); + when(plan.trustFence()).thenReturn(TRUST); + when(plan.planDigest()) + .thenReturn((String) preparedPromotionValues.get("readiness_plan_digest")); + when(plan.operationDigest()).thenReturn(result.operationDigest()); + when(plan.generationRequestDigest()).thenReturn(result.generationRequestDigest()); + when(plan.generationReceiptDigest()).thenReturn(result.receiptDigest()); + when(plan.publicationIntentDigest()) + .thenReturn((String) preparedPromotionValues.get("prepublication_intent_digest")); + when(plan.publicationReceiptDigest()) + .thenReturn((String) preparedPromotionValues.get("prepublication_receipt_digest")); + when(plan.mountedObservationDigest()) + .thenReturn((String) preparedPromotionValues.get("mounted_observation_digest")); + when(plan.desiredStateVersion()).thenReturn(result.desiredStateVersion()); + when(plan.targetGeneration()).thenReturn(result.targetGeneration()); + when(plan.targetKid()).thenReturn(result.targetKid()); + when(plan.targetPublicKeyFingerprint()).thenReturn(result.publicKeyFingerprint()); + when(plan.validatorInventoryComplete()).thenReturn(true); + + var intent = mock(AccountJwtJwksPublicationRepository.PrepublicationIntent.class); + when(intent.operationId()).thenReturn(result.operationId()); + when(intent.intentDigest()) + .thenReturn((String) preparedPromotionValues.get("prepublication_intent_digest")); + when(intent.configMapUid()).thenReturn(ENROLLMENT.publicConfigMapUid()); + when(intent.apiBindingDigest()).thenReturn(ENROLLMENT.apiBindingDigest()); + when(intent.apiConfigRevision()).thenReturn(ENROLLMENT.apiConfigRevision()); + when(intent.jwksJson()) + .thenReturn((String) preparedPromotionValues.get("expected_public_jwks_json")); + + var receipt = mock(AccountJwtJwksPublicationRepository.PublicationReceipt.class); + when(receipt.operationId()).thenReturn(result.operationId()); + when(receipt.receiptDigest()) + .thenReturn((String) preparedPromotionValues.get("prepublication_receipt_digest")); + when(receipt.observedResourceVersion()).thenReturn("14"); + + var mount = mock(AccountJwtJwksPublicationRepository.MountObservation.class); + when(mount.operationId()).thenReturn(result.operationId()); + when(mount.observationDigest()) + .thenReturn((String) preparedPromotionValues.get("mounted_observation_digest")); + + var publication = + mock(AccountJwtJwksPublicationRepository.PromotionPublicationEvidence.class); + when(publication.intent()).thenReturn(intent); + when(publication.receipt()).thenReturn(receipt); + when(publication.mountedCorrespondence()).thenReturn(mount); + + var proof = mock(ReadinessPromotionProof.class); + when(proof.plan()).thenReturn(plan); + when(proof.generationResult()).thenReturn(result); + when(proof.publication()).thenReturn(publication); + when(proof.inventoryEvidenceReference()) + .thenReturn("protected-validator-inventory:" + "9".repeat(64)); + when(proof.inventoryEvidenceDigest()).thenReturn("9".repeat(64)); + when(proof.verifiedProbes()) + .thenReturn( + List.of(mock(AccountJwtReadinessProbeRepository.VerifiedProbeEvidence.class))); + when(proof.readinessEvidenceDigest()) + .thenReturn((String) preparedPromotionValues.get("readiness_evidence_digest")); + when(proof.readinessEvidencePreimage()).thenReturn(preimage.clone()); + return proof; + } + + private void recordPromotionReceipts(GenerationResult result) throws Exception { + String promotionId = preparedPromotionId.toString(); + String operationDigest = (String) preparedPromotionValues.get("request_digest"); + String privateObservedVersion = "15"; + Map privateReceipt = new HashMap<>(); + privateReceipt.put("receiptVersion", 1); + privateReceipt.put("promotionOperationId", promotionId); + privateReceipt.put("promotionRequestDigest", operationDigest); + privateReceipt.put("generationOperationId", result.operationId().toString()); + privateReceipt.put("generationOperationDigest", result.operationDigest()); + privateReceipt.put("generationReceiptDigest", result.receiptDigest()); + privateReceipt.put("secretResource", Map.of("kind", "Secret", "name", "jwt-signing-keys")); + privateReceipt.put("secretUid", result.secretUid()); + privateReceipt.put("expectedPriorResourceVersion", result.observedResourceVersion()); + privateReceipt.put("observedResourceVersion", privateObservedVersion); + privateReceipt.put("action", "PROMOTE_PENDING"); + privateReceipt.put("resultingSlots", List.of("current")); + privateReceipt.put( + "current", + Map.of( + "generation", result.targetGeneration(), + "kid", result.targetKid(), + "publicKeyFingerprint", result.publicKeyFingerprint())); + privateReceipt.put("previous", Map.of("present", false)); + preparedPromotionValues.put( + "private_promotion_observed_resource_version", privateObservedVersion); + preparedPromotionValues.put( + "private_promotion_receipt_digest", canonicalDigest(privateReceipt)); + + String activeObservedVersion = "15"; + String jwksJson = (String) preparedPromotionValues.get("expected_public_jwks_json"); + String markerJson = + (String) preparedPromotionValues.get("expected_active_generation_marker_json"); + String publicDataDigest = + AccountJwtJwksPublicationRepository.publicDataDigest(jwksJson, markerJson); + Map activeReceipt = new HashMap<>(); + activeReceipt.put("receiptVersion", "account-jwt-active-jwks-promotion-receipt/v1"); + activeReceipt.put("promotionOperationId", promotionId); + activeReceipt.put("promotionRequestDigest", operationDigest); + activeReceipt.put("generationOperationId", result.operationId().toString()); + activeReceipt.put("generationOperationDigest", result.operationDigest()); + activeReceipt.put("generationReceiptDigest", result.receiptDigest()); + activeReceipt.put("configMapName", "jwt-jwks"); + activeReceipt.put("configMapUid", ENROLLMENT.publicConfigMapUid()); + activeReceipt.put("priorResourceVersion", "14"); + activeReceipt.put("observedResourceVersion", activeObservedVersion); + activeReceipt.put("action", "MARK_ACTIVE"); + activeReceipt.put("publicDataDigest", publicDataDigest); + preparedPromotionValues.put("active_jwks_observed_resource_version", activeObservedVersion); + preparedPromotionValues.put("active_jwks_public_data_digest", publicDataDigest); + preparedPromotionValues.put("active_jwks_receipt_digest", canonicalDigest(activeReceipt)); + } + + private String canonicalDigest(Map value) throws Exception { + byte[] canonical = + Rfc8785CanonicalJson.canonicalizeUtf8( + JsonMapper.builder().build().writeValueAsString(value)); + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical)); + } + + private void preparePromotionForDispatch(GenerationRequest generation, GenerationResult result) + throws Exception { + preparedPromotionId = UUID.fromString("66666666-6666-4666-8666-666666666666"); + String publicJwksJson = "{\"keys\":[" + result.publicJwkJson() + "]}"; + String requestDigest = + promotionRequestDigest(preparedPromotionId, generation, result, publicJwksJson); + preparedPromotionValues = new HashMap<>(); + preparedPromotionValues.put("operation_id", preparedPromotionId); + preparedPromotionValues.put("environment_id", BINDING.environmentId()); + preparedPromotionValues.put("cluster_id", BINDING.clusterId()); + preparedPromotionValues.put("kubernetes_namespace", BINDING.namespace()); + preparedPromotionValues.put("custody_mode", BINDING.mode().value()); + preparedPromotionValues.put("request_digest_version", (short) 1); + preparedPromotionValues.put("request_digest", requestDigest); + preparedPromotionValues.put("expected_record_version", 2L); + preparedPromotionValues.put("expected_previous_generation", null); + preparedPromotionValues.put("expected_previous_kid", null); + preparedPromotionValues.put("target_generation", Long.parseLong(result.targetGeneration())); + preparedPromotionValues.put("target_kid", result.targetKid()); + preparedPromotionValues.put("target_algorithm", result.targetAlgorithm()); + preparedPromotionValues.put("target_public_key_fingerprint", result.publicKeyFingerprint()); + preparedPromotionValues.put( + "expected_private_secret_resource_version", result.observedResourceVersion()); + preparedPromotionValues.put("expected_public_jwks_resource_version", "14"); + preparedPromotionValues.put("expected_public_active_generation", null); + preparedPromotionValues.put("expected_public_active_kid", null); + preparedPromotionValues.put("operation_action", "PROMOTE_PENDING"); + preparedPromotionValues.put( + "allowed_private_slots_canonical_bytes", + "[\"current\",\"pending\",\"previous\"]".getBytes(StandardCharsets.UTF_8)); + preparedPromotionValues.put("status", "PREPARED"); + preparedPromotionValues.put("generation_operation_id", generation.operationId()); + preparedPromotionValues.put( + "expected_cluster_incarnation_uid", + UUID.fromString(TRUST.expectedClusterIncarnationUid())); + preparedPromotionValues.put( + "expected_namespace_uid", UUID.fromString(TRUST.expectedNamespaceUid())); + preparedPromotionValues.put("materializer_trust_binding_digest", TRUST.bindingDigest()); + preparedPromotionValues.put("materializer_trust_config_revision", TRUST.configRevision()); + preparedPromotionValues.put("api_binding_digest", ENROLLMENT.apiBindingDigest()); + preparedPromotionValues.put("api_config_revision", ENROLLMENT.apiConfigRevision()); + preparedPromotionValues.put("expected_private_secret_uid", SECRET_UID); + preparedPromotionValues.put( + "expected_public_config_map_uid", UUID.fromString(ENROLLMENT.publicConfigMapUid())); + preparedPromotionValues.put("prepublication_intent_digest", "d".repeat(64)); + preparedPromotionValues.put("prepublication_receipt_digest", "e".repeat(64)); + preparedPromotionValues.put("mounted_observation_digest", "f".repeat(64)); + preparedPromotionValues.put("readiness_plan_digest", "1".repeat(64)); + preparedPromotionValues.put("readiness_evidence_digest", sha256(READINESS_EVIDENCE_PREIMAGE)); + preparedPromotionValues.put( + "readiness_evidence_preimage", + READINESS_EVIDENCE_PREIMAGE.getBytes(StandardCharsets.UTF_8)); + preparedPromotionValues.put("expected_public_jwks_json", publicJwksJson); + preparedPromotionValues.put("expected_active_generation_marker_json", "{}"); + preparedPromotionValues.put("private_promotion_dispatched", false); + preparedPromotionValues.put("private_promotion_observed_resource_version", null); + preparedPromotionValues.put("private_promotion_receipt_digest", null); + preparedPromotionValues.put("active_jwks_observed_resource_version", null); + preparedPromotionValues.put("active_jwks_public_data_digest", null); + preparedPromotionValues.put("active_jwks_receipt_digest", null); + preparedPromotionValues.put("generation_operation_digest", generation.operationDigest()); + preparedPromotionValues.put("generation_receipt_digest", result.receiptDigest()); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java new file mode 100644 index 0000000000..2f871c591b --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java @@ -0,0 +1,184 @@ +package net.firedevops.firemud.accountservice.repository; + +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.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Instant; +import java.util.HexFormat; +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.service.session.AccountJwtValidatorInventorySource.InventorySnapshot; +import org.jooq.DSLContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountJwtValidatorInventoryRepositoryTest { + 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"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsUseOutsideAnOwningAccountTransactionWithoutDatabaseAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(dsl); + + assertThatThrownBy(() -> repository.persistOrReadback(snapshot("good"), BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("owning Account transaction"); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsReadOnlyTransactionBeforeAnyInsert() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy(() -> repository.persistOrReadback(snapshot("good"), BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsRequiredSnapshotReadFromReadOnlyOwnerTransactionBeforeDatabaseAccess() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + + assertThatThrownBy(() -> repository.readRequired("a".repeat(64), BINDING, TRUST)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("A writable Account transaction is required"); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsWrongClusterNamespaceOrIncarnationBeforeInsert() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + + assertThatThrownBy( + () -> repository.persistOrReadback(snapshot("other-cluster"), BINDING, TRUST)) + .isInstanceOf( + AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) + .hasNoCause(); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsCanonicalSnapshotBytesWhoseDigestDoesNotMatchBeforeInsert() { + DSLContext dsl = mock(DSLContext.class); + AccountJwtValidatorInventoryRepository repository = + new AccountJwtValidatorInventoryRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + InventorySnapshot candidate = snapshot("cluster-a"); + when(candidate.canonicalBytes()) + .thenReturn("{\"tampered\":true}".getBytes(StandardCharsets.UTF_8)); + + assertThatThrownBy(() -> repository.persistOrReadback(candidate, BINDING, TRUST)) + .isInstanceOf( + AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) + .hasNoCause(); + + verifyNoInteractions(dsl); + } + + @Test + void rejectsSnapshotDigestMismatchAndReturnsDefensiveByteCopies() { + byte[] bytes = "{\"domain\":\"test\"}".getBytes(StandardCharsets.UTF_8); + String digest = sha256(bytes); + AccountJwtValidatorInventoryRepository.StoredSnapshot snapshot = + new AccountJwtValidatorInventoryRepository.StoredSnapshot( + digest, + "staging", + "cluster-a", + TRUST.expectedClusterIncarnationUid(), + "firemud", + TRUST.expectedNamespaceUid(), + "api-r1", + "b".repeat(64), + "inventory-r1", + "c".repeat(64), + Instant.parse("2026-10-05T00:00:00Z"), + bytes); + byte[] returned = snapshot.canonicalBytes(); + returned[2] = 'x'; + + assertThat(snapshot.canonicalBytes()).isEqualTo(bytes); + assertThatThrownBy( + () -> + new AccountJwtValidatorInventoryRepository.StoredSnapshot( + "d".repeat(64), + "staging", + "cluster-a", + TRUST.expectedClusterIncarnationUid(), + "firemud", + TRUST.expectedNamespaceUid(), + "api-r1", + "b".repeat(64), + "inventory-r1", + "c".repeat(64), + Instant.parse("2026-10-05T00:00:00Z"), + bytes)) + .isInstanceOf( + AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) + .hasNoCause(); + } + + private static InventorySnapshot snapshot(String clusterId) { + byte[] bytes = "{\"domain\":\"inventory\"}".getBytes(StandardCharsets.UTF_8); + InventorySnapshot snapshot = mock(InventorySnapshot.class); + when(snapshot.observedAt()).thenReturn(Instant.parse("2026-10-05T00:00:00Z")); + when(snapshot.environmentId()).thenReturn("staging"); + when(snapshot.clusterId()).thenReturn(clusterId); + when(snapshot.clusterIncarnationUid()).thenReturn(TRUST.expectedClusterIncarnationUid()); + when(snapshot.namespace()).thenReturn("firemud"); + when(snapshot.namespaceUid()).thenReturn(TRUST.expectedNamespaceUid()); + when(snapshot.apiBindingRevision()).thenReturn("api-r1"); + when(snapshot.apiBindingDigest()).thenReturn("b".repeat(64)); + when(snapshot.inventoryBindingRevision()).thenReturn("inventory-r1"); + when(snapshot.inventoryBindingDigest()).thenReturn("c".repeat(64)); + when(snapshot.canonicalBytes()).thenReturn(bytes); + when(snapshot.digest()).thenReturn(sha256(bytes)); + return snapshot; + } + + private static String sha256(byte[] value) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } catch (Exception failure) { + throw new AssertionError(failure); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java new file mode 100644 index 0000000000..0bd4f21164 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeSigningSpecTest.java @@ -0,0 +1,101 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.UUID; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind; +import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec; +import org.junit.jupiter.api.Test; + +class AccountJwtReadinessProbeSigningSpecTest { + @Test + void acceptsAccountCanaryAndEveryProtectedProductionProfile() { + assertValid( + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + ProbeKind.CANARY, + AccountMountedJwtSignerBundle.READINESS_CANARY_PROFILE, + AccountMountedJwtSignerBundle.READINESS_CANARY_AUDIENCE); + assertValid( + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + "control-ui", + "control-ui"); + assertValid( + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + "player-bootstrap", + "player-bootstrap"); + assertValid( + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_AUDIENCE); + } + + @Test + void permitsCanonicalProfilesForGameSessionInapplicableRejectionProbes() { + assertValid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.CANARY, + AccountMountedJwtSignerBundle.READINESS_CANARY_PROFILE, + AccountMountedJwtSignerBundle.READINESS_CANARY_AUDIENCE); + assertValid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + "control-ui", + "control-ui"); + assertValid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + "player-bootstrap", + "player-bootstrap"); + assertValid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_AUDIENCE); + } + + @Test + void rejectsUnknownValidatorAndMismatchedProfileAudienceCombinations() { + assertInvalid( + "unknown-service", + ProbeKind.CANARY, + AccountMountedJwtSignerBundle.READINESS_CANARY_PROFILE, + AccountMountedJwtSignerBundle.READINESS_CANARY_AUDIENCE); + assertInvalid( + AccountMountedJwtSignerBundle.READINESS_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + "control-ui"); + assertInvalid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.REPRESENTATIVE, + "player-bootstrap", + "control-ui"); + assertInvalid( + AccountMountedJwtSignerBundle.GAME_SESSION_VALIDATOR_ID, + ProbeKind.CANARY, + AccountMountedJwtSignerBundle.READINESS_CANARY_PROFILE, + "account-service"); + } + + private static void assertValid( + String validatorId, ProbeKind kind, String profile, String audience) { + assertThatCode(() -> signingSpec(validatorId, kind, profile, audience)) + .doesNotThrowAnyException(); + } + + private static void assertInvalid( + String validatorId, ProbeKind kind, String profile, String audience) { + assertThatThrownBy(() -> signingSpec(validatorId, kind, profile, audience)) + .isInstanceOf(AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class); + } + + private static ReadinessProbeSigningSpec signingSpec( + String validatorId, ProbeKind kind, String profile, String audience) { + return new ReadinessProbeSigningSpec( + validatorId, kind, profile, audience, UUID.randomUUID(), "1", "key-1", 20_300, 20_480); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundleTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundleTest.java new file mode 100644 index 0000000000..41ac237f85 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountMountedJwtSignerBundleTest.java @@ -0,0 +1,1169 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +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.PrivateKey; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPrivateKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.RSAKeyGenParameterSpec; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.accountservice.repository.AccountGameplayCredentialRequestBindingFixture; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationPendingIdentity; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class AccountMountedJwtSignerBundleTest { + private static final String ENVIRONMENT = "staging"; + private static final String CLUSTER = "cluster-a"; + private static final String NAMESPACE = "firemud"; + private static final String OPERATION = "7af097ea-b1d1-42ea-9f24-46aeb211a779"; + private static final String GENERATION = "42"; + private static final String KID = "account-key-42"; + private static KeyPair rsa3072; + + @TempDir Path tempDirectory; + private Path privateMount; + private Path publicMount; + + @BeforeAll + static void generateEphemeralRsa3072Only() throws Exception { + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(new RSAKeyGenParameterSpec(3_072, RSAKeyGenParameterSpec.F4)); + rsa3072 = generator.generateKeyPair(); + } + + @BeforeEach + void writeValidMountedPair() throws Exception { + privateMount = Files.createDirectory(tempDirectory.resolve("private-mount")); + publicMount = Files.createDirectory(tempDirectory.resolve("public-mount")); + Files.writeString(privateMount.resolve("current.key"), bundleJson(identity(), rsa3072)); + Files.writeString(publicMount.resolve("jwks.json"), jwksJson(identity(), rsa3072)); + } + + @Test + void observesCorrespondingMountedKeyWithoutReturningSigningAuthority() throws Exception { + AccountMountedJwtSignerBundle.LocalObservation observation = observe(identity()); + + assertEquals(identity(), observation.expectedIdentity()); + assertEquals(identity().publicKeyFingerprint(), observation.publicKeyFingerprint()); + assertTrue(observation.localPrivatePublicCorrespondenceObserved()); + assertTrue(observation.toString().contains("authorization=none")); + assertTrue(observation.toString().contains("provisioning=unproved")); + assertFalse(observation.toString().contains(privateKeyText(rsa3072))); + assertThrows( + NoSuchMethodException.class, () -> observation.getClass().getMethod("sign", byte[].class)); + assertThrows( + NoSuchFieldException.class, () -> observation.getClass().getDeclaredField("privateKey")); + + byte[] nonce = new byte[32]; + Arrays.fill(nonce, (byte) 7); + byte[] originalNonce = nonce.clone(); + byte[] challenge = AccountMountedJwtSignerBundle.correspondenceChallenge(nonce); + assertEquals(0, challenge[0]); + assertFalse(isAscii(challenge)); + assertFalse(new String(challenge, StandardCharsets.ISO_8859_1).contains(".")); + assertArrayEquals(originalNonce, nonce); + } + + @Test + void signsOnlyFixedReadinessShapesAndDeliversCompactBytesTransiently() throws Exception { + long issuedAt = 1_800_000_000L; + AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec spec = + new AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec( + "account-service", + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_AUDIENCE, + UUID.fromString("6f512d65-06ce-4d6c-9cf0-c2734185e1d8"), + GENERATION, + KID, + issuedAt, + issuedAt + 180); + + String[] deliveredHash = new String[1]; + byte[][] deliveredBytes = new byte[1][]; + AccountMountedJwtSignerBundle.SignedProbeDigest first = + AccountMountedJwtSignerBundle.signReadinessProbeDigest( + privateMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity(), + spec, + (digest, compactJwt) -> { + deliveredBytes[0] = compactJwt; + assertTrue(compactJwt.length > 0); + assertTrue(compactJwt.length < 16 * 1024); + String compact = new String(compactJwt, StandardCharsets.US_ASCII); + String[] parts = compact.split("\\.", -1); + assertEquals(3, parts.length); + byte[] signingInput = (parts[0] + "." + parts[1]).getBytes(StandardCharsets.US_ASCII); + byte[] signature = Base64.getUrlDecoder().decode(parts[2]); + try { + try { + java.security.Signature verifier = + java.security.Signature.getInstance("SHA256withRSA"); + verifier.initVerify((RSAPublicKey) rsa3072.getPublic()); + verifier.update(signingInput); + assertTrue(verifier.verify(signature)); + } catch (java.security.GeneralSecurityException exception) { + org.junit.jupiter.api.Assertions.fail( + "Expected readiness probe signature to verify with the mounted public key", + exception); + } + assertTrue( + new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8) + .contains("\"tokenGeneration\":\"1\"")); + String claims = + new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); + assertTrue(claims.contains("\"tenantAuthorityGeneration\":{}")); + assertTrue(claims.contains("\"membershipAuthorityGeneration\":{}")); + assertTrue(claims.contains("\"membershipVersion\":{}")); + assertFalse(claims.contains("scopedRoles")); + assertFalse(claims.contains("globalRoles")); + deliveredHash[0] = sha256(compactJwt); + assertEquals(digest.compactTokenSha256(), deliveredHash[0]); + } finally { + Arrays.fill(signingInput, (byte) 0); + Arrays.fill(signature, (byte) 0); + } + }); + assertTrue(Arrays.equals(new byte[deliveredBytes[0].length], deliveredBytes[0])); + + AccountMountedJwtSignerBundle.SignedProbeDigest retry = + AccountMountedJwtSignerBundle.signReadinessProbeDigest( + privateMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity(), + spec, + (digest, compactJwt) -> { + deliveredBytes[0] = compactJwt; + String hash = sha256(compactJwt); + assertEquals(digest.compactTokenSha256(), hash); + assertEquals(deliveredHash[0], hash); + }); + assertTrue(Arrays.equals(new byte[deliveredBytes[0].length], deliveredBytes[0])); + + assertEquals(first.compactTokenSha256(), retry.compactTokenSha256()); + assertEquals(spec.jti(), first.jti()); + assertEquals(GENERATION, first.targetGeneration()); + assertFalse(first.toString().contains("compactJwt")); + assertThrows(NoSuchMethodException.class, () -> first.getClass().getMethod("compactJwt")); + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> + new AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec( + "account-service", + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + "another-audience", + UUID.randomUUID(), + GENERATION, + KID, + issuedAt, + issuedAt + 180)); + } + + @Test + void signsOnlyTheThreeExactAccountRepresentativeProfileShapes() throws Exception { + long issuedAt = 1_800_000_000L; + Map audiences = + Map.of( + "control-ui", + "control-ui", + "player-bootstrap", + "player-bootstrap", + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_AUDIENCE); + + for (Map.Entry profile : audiences.entrySet()) { + AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec spec = + new AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec( + "account-service", + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + profile.getKey(), + profile.getValue(), + UUID.randomUUID(), + GENERATION, + KID, + issuedAt, + issuedAt + 180); + AccountMountedJwtSignerBundle.signReadinessProbeDigest( + privateMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity(), + spec, + (digest, compactJwt) -> { + String[] parts = new String(compactJwt, StandardCharsets.US_ASCII).split("\\.", -1); + assertEquals(3, parts.length); + String claims = + new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); + assertTrue(claims.contains("\"aud\":\"" + profile.getValue() + "\"")); + assertTrue(claims.contains("\"accountId\":\"00000000-0000-4000-8000-000000000001\"")); + assertTrue( + claims.contains("\"scopedRoles\":{}") + == !profile + .getKey() + .equals(AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE)); + assertFalse(claims.contains("\"globalRoles\"")); + assertTrue(claims.contains("\"privateRealmGrantVersions\":[]")); + if (GameSessionAccountDelegationProfile.PROFILE.equals(profile.getKey())) { + assertTrue(claims.contains("\"tokenGeneration\":\"1\"")); + assertTrue(claims.contains("\"issuerAuthGeneration\":\"1\"")); + assertTrue(claims.contains("\"accountAuthorityGeneration\":\"1\"")); + assertTrue(claims.contains("\"issuanceFence\":\"1\"")); + } else { + assertTrue(claims.contains("\"tokenGeneration\":1")); + assertTrue(claims.contains("\"issuanceFence\":1")); + } + assertEquals(digest.compactTokenSha256(), sha256(compactJwt)); + }); + } + } + + @Test + void signsClosedAccountDelegationClaimsFromPersistedIdentityAndWipesTransientBytes() + throws Exception { + long issuedAt = 1_800_000_000L; + UUID accountId = UUID.fromString("a6a2af33-2e50-4092-934b-43c5bce12f7b"); + UUID operationId = UUID.fromString("c5c31332-e560-41c8-a55a-97674e7a317c"); + UUID requestId = UUID.fromString("f14ca47a-2316-47b7-a38f-f9b693ff8afc"); + UUID contextId = UUID.fromString("e16fdce5-96eb-49e9-a1bd-3f429816cbf0"); + UUID jti = UUID.fromString("1a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"); + String requestDigest = "ab".repeat(32); + AccountAuthoritySnapshot authority = + new AccountAuthoritySnapshot(accountId, 7, 7, 1, 1, 1, 1, Optional.empty()); + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + operationId, + requestId, + accountId, + "spiffe://firemud/ns/firemud/sa/game-session-service", + contextId, + AccountGameplayCredentialRequestBindingFixture.binding(), + requestDigest, + jti, + issuedAt, + issuedAt, + issuedAt + 120); + + byte[][] transientBytes = new byte[1][]; + String[] observedHash = new String[1]; + String[] transientHash = new String[1]; + AccountMountedJwtSignerBundle.SignedDelegationDigest signed = + AccountMountedJwtSignerBundle.signCommittedGameplayDelegationDigest( + privateMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity(), + new AccountMountedJwtSignerBundle.DelegationSigningSpec(identity, authority), + (digest, compactJwt) -> { + transientBytes[0] = compactJwt; + assertEquals(operationId, digest.issuanceOperationId()); + assertEquals(requestId, digest.requestId()); + assertEquals(jti, digest.jti()); + assertEquals(identity().operationId(), digest.signerOperationId()); + assertEquals(GENERATION, digest.signerGeneration()); + assertEquals(KID, digest.kid()); + + String compact = new String(compactJwt, StandardCharsets.US_ASCII); + String claims = + new String( + Base64.getUrlDecoder().decode(compact.split("\\.", -1)[1]), + StandardCharsets.UTF_8); + assertTrue(claims.contains("\"tokenGeneration\":\"1\"")); + assertTrue(claims.contains("\"issuanceFence\":\"1\"")); + assertTrue(claims.contains("\"issuerAuthGeneration\":\"7\"")); + assertTrue(claims.contains("\"accountAuthorityGeneration\":\"1\"")); + transientHash[0] = sha256(compactJwt); + String[] parts = compact.split("\\.", -1); + assertEquals(3, parts.length); + byte[] signingInput = (parts[0] + "." + parts[1]).getBytes(StandardCharsets.US_ASCII); + byte[] signature = Base64.getUrlDecoder().decode(parts[2]); + try { + java.security.Signature verifier = + java.security.Signature.getInstance("SHA256withRSA"); + verifier.initVerify((RSAPublicKey) rsa3072.getPublic()); + verifier.update(signingInput); + assertTrue(verifier.verify(signature)); + } catch (java.security.GeneralSecurityException exception) { + org.junit.jupiter.api.Assertions.fail( + "Expected Account delegation signature to verify with its mounted public key", + exception); + } finally { + Arrays.fill(signingInput, (byte) 0); + Arrays.fill(signature, (byte) 0); + } + + GameSessionAccountDelegationRegistryRecord pending = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact, + GENERATION, + new IssuanceBinding( + operationId.toString(), + requestId.toString(), + requestDigest, + accountId.toString()), + authority, + new EvidenceBundleReference("1", "11", "9", "3", "d".repeat(64)), + issuedAt, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + assertEquals(jti.toString(), pending.jti()); + assertEquals("d".repeat(64), pending.evidenceBundleReference().canonicalSha256()); + assertEquals(operationId.toString(), pending.operationId()); + assertEquals(requestId.toString(), pending.requestId()); + assertEquals(sha256(compactJwt), pending.tokenHash()); + observedHash[0] = pending.tokenHash(); + assertFalse(compact.contains("tokenProfile")); + assertFalse(compact.contains("tokenType")); + }); + + assertEquals(observedHash[0], signed.compactTokenSha256()); + assertEquals(transientHash[0], signed.compactTokenSha256()); + assertTrue(Arrays.equals(new byte[transientBytes[0].length], transientBytes[0])); + assertFalse(signed.toString().contains(signed.compactTokenSha256())); + } + + @Test + void mountedSignerCreatesDistinctBoundPendingClaimsWithRealSignatureAndNoInitialAdoption() + throws Exception { + long issued = 1_800_000_000L; + UUID account = UUID.fromString("a6a2af33-2e50-4092-934b-43c5bce12f7b"); + String tenant = "22222222-2222-4222-8222-222222222222"; + var pending = + new AccountGameplayDelegationPendingIdentity( + UUID.randomUUID(), + UUID.randomUUID(), + account, + "spiffe://firemud/ns/firemud/sa/game-session-service", + UUID.randomUUID(), + AccountGameplayCredentialRequestBindingFixture.binding(), + "a".repeat(64), + UUID.randomUUID(), + issued, + issued, + issued + 120); + var authority = new AccountAuthoritySnapshot(account, 7, 7, 1, 1, 1, 1, Optional.empty()); + var tuple = + new java.util.LinkedHashMap( + GameSessionAccountDelegationProfile.authorityTuple(7, 1)); + tuple.put("tenantAuthorityGeneration", Map.of(tenant, "5")); + tuple.put("membershipAuthorityGeneration", Map.of(tenant, "7")); + byte[][] captured = new byte[1][]; + AccountMountedJwtSignerBundle.signCommittedGameplayDelegationDigest( + privateMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity(), + new AccountMountedJwtSignerBundle.DelegationSigningSpec( + pending, + authority, + Optional.of( + new AccountMountedJwtSignerBundle.BoundDelegationClaims( + tenant, tuple, Map.of(tenant, "3")))), + (digest, bytes) -> { + captured[0] = bytes; + String jwt = new String(bytes, StandardCharsets.US_ASCII); + String[] parts = jwt.split("\\."); + try { + var verifier = java.security.Signature.getInstance("SHA256withRSA"); + verifier.initVerify(rsa3072.getPublic()); + verifier.update((parts[0] + "." + parts[1]).getBytes(StandardCharsets.US_ASCII)); + assertTrue(verifier.verify(Base64.getUrlDecoder().decode(parts[2]))); + } catch (java.security.GeneralSecurityException failure) { + throw new AssertionError(failure); + } + var binding = + new IssuanceBinding( + pending.operationId().toString(), + pending.requestId().toString(), + pending.requestDigest(), + account.toString()); + var evidence = new EvidenceBundleReference("1", "1", "1", "1", "b".repeat(64)); + var registry = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedBoundCompactJwt( + jwt, + GENERATION, + binding, + authority, + evidence, + tenant, + tuple, + Map.of(tenant, "3"), + issued, + 16384); + assertEquals("pending", registry.state()); + assertEquals(tenant, registry.fields().get("tenantId")); + assertEquals(Map.of(tenant, "3"), registry.fields().get("membershipVersion")); + byte[] canonicalRegistry = registry.toCanonicalJsonBytes(16384); + assertArrayEquals( + canonicalRegistry, + GameSessionAccountDelegationRegistryRecord.decode(canonicalRegistry, 16384) + .toCanonicalJsonBytes(16384)); + assertThrows( + IllegalArgumentException.class, + () -> + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + jwt, GENERATION, binding, authority, evidence, issued, 16384)); + }); + assertArrayEquals(new byte[captured[0].length], captured[0]); + } + + @Test + void rejectsBoundAccountAuthorityMismatchesBeforeCallingOwner() { + UUID account = UUID.fromString("a6a2af33-2e50-4092-934b-43c5bce12f7b"); + UUID otherAccount = UUID.fromString("b7b3bf44-3f61-41a3-a145-54d6cdf23e8c"); + String tenant = "22222222-2222-4222-8222-222222222222"; + var noCutoff = Optional.empty(); + + assertBoundTupleRejected( + authoritySnapshot(account, 7, 1), tenantTuple(8, 1, noCutoff, tenant), tenant); + assertBoundTupleRejected( + authoritySnapshot(account, 7, 1), + tenantTuple(7, 2, Optional.of(accountCutoff(account, 2)), tenant), + tenant); + assertBoundTupleRejected( + authoritySnapshot(account, 7, 2), + tenantTuple(7, 2, Optional.of(accountCutoff(otherAccount, 2)), tenant), + tenant); + assertBoundTupleRejected( + authoritySnapshot(account, 7, 2), tenantTuple(7, 1, noCutoff, tenant), tenant); + } + + @Test + void boundClaimsRecursivelyCopyNestedAuthorityMapsBeforeSigning() { + UUID account = UUID.fromString("a6a2af33-2e50-4092-934b-43c5bce12f7b"); + String tenant = "22222222-2222-4222-8222-222222222222"; + long issued = 1_800_000_000L; + Map mutableTuple = + new LinkedHashMap<>(GameSessionAccountDelegationProfile.authorityTuple(7, 1)); + Map mutableTenantGenerations = new LinkedHashMap<>(); + mutableTenantGenerations.put(tenant, "5"); + Map mutableMembershipGenerations = new LinkedHashMap<>(); + mutableMembershipGenerations.put(tenant, "7"); + mutableTuple.put("tenantAuthorityGeneration", mutableTenantGenerations); + mutableTuple.put("membershipAuthorityGeneration", mutableMembershipGenerations); + + var bound = + new AccountMountedJwtSignerBundle.BoundDelegationClaims( + tenant, mutableTuple, Map.of(tenant, "3")); + mutableTenantGenerations.put(tenant, "99"); + mutableMembershipGenerations.put(tenant, "99"); + mutableTuple.put("issuerAuthGeneration", "99"); + + byte[][] delivered = new byte[1][]; + AccountMountedJwtSignerBundle.signCommittedGameplayDelegationDigest( + privateMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity(), + new AccountMountedJwtSignerBundle.DelegationSigningSpec( + delegationIdentity(account, issued), + authoritySnapshot(account, 7, 1), + Optional.of(bound)), + (digest, compactJwt) -> { + delivered[0] = compactJwt; + String[] parts = new String(compactJwt, StandardCharsets.US_ASCII).split("\\.", -1); + String claims = + new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); + assertTrue(claims.contains("\"issuerAuthGeneration\":\"7\"")); + assertTrue(claims.contains("\"tenantAuthorityGeneration\":{\"" + tenant + "\":\"5\"}")); + assertTrue( + claims.contains("\"membershipAuthorityGeneration\":{\"" + tenant + "\":\"7\"}")); + assertFalse(claims.contains("\"tenantAuthorityGeneration\":{\"" + tenant + "\":\"99\"}")); + assertFalse( + claims.contains("\"membershipAuthorityGeneration\":{\"" + tenant + "\":\"99\"}")); + }); + + assertTrue(Arrays.equals(new byte[delivered[0].length], delivered[0])); + } + + @Test + void rejectsCyclicBoundAuthorityTuple() { + String tenant = "22222222-2222-4222-8222-222222222222"; + Map tuple = + new LinkedHashMap<>(GameSessionAccountDelegationProfile.authorityTuple(7, 1)); + tuple.put("tenantAuthorityGeneration", tuple); + + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> + new AccountMountedJwtSignerBundle.BoundDelegationClaims( + tenant, tuple, Map.of(tenant, "3"))); + } + + @Test + void callbackFailureDoesNotRetainTransientCredentialAndWipesCallbackBytes() { + long issuedAt = 1_800_000_000L; + UUID accountId = UUID.fromString("a6a2af33-2e50-4092-934b-43c5bce12f7b"); + AccountGameplayDelegationPendingIdentity identity = + new AccountGameplayDelegationPendingIdentity( + UUID.fromString("c5c31332-e560-41c8-a55a-97674e7a317c"), + UUID.fromString("f14ca47a-2316-47b7-a38f-f9b693ff8afc"), + accountId, + "spiffe://firemud/ns/firemud/sa/game-session-service", + UUID.fromString("e16fdce5-96eb-49e9-a1bd-3f429816cbf0"), + AccountGameplayCredentialRequestBindingFixture.binding(), + "ab".repeat(32), + UUID.fromString("1a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"), + issuedAt, + issuedAt, + issuedAt + 120); + AccountAuthoritySnapshot authority = + new AccountAuthoritySnapshot(accountId, 7, 7, 1, 1, 1, 1, Optional.empty()); + byte[][] callbackBytes = new byte[1][]; + String[] transientJwt = new String[1]; + + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException failure = + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> + AccountMountedJwtSignerBundle.signCommittedGameplayDelegationDigest( + privateMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity(), + new AccountMountedJwtSignerBundle.DelegationSigningSpec(identity, authority), + (digest, compactJwt) -> { + callbackBytes[0] = compactJwt; + transientJwt[0] = new String(compactJwt, StandardCharsets.US_ASCII); + throw new IllegalStateException( + "transient callback failure: " + transientJwt[0]); + })); + + assertNull(failure.getCause()); + assertFalse(failure.getMessage().contains(transientJwt[0])); + assertFalse(failure.toString().contains(transientJwt[0])); + assertTrue(Arrays.equals(new byte[callbackBytes[0].length], callbackBytes[0])); + } + + @Test + void readinessCallbackFailureDoesNotRetainTransientJwtAndWipesCallbackBytes() { + long issuedAt = 1_800_000_000L; + AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec spec = + new AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec( + "account-service", + AccountMountedJwtSignerBundle.ProbeKind.REPRESENTATIVE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_PROFILE, + AccountMountedJwtSignerBundle.REPRESENTATIVE_AUDIENCE, + UUID.randomUUID(), + GENERATION, + KID, + issuedAt, + issuedAt + 180); + byte[][] callbackBytes = new byte[1][]; + String[] transientJwt = new String[1]; + + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException failure = + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> + AccountMountedJwtSignerBundle.signReadinessProbeDigest( + privateMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity(), + spec, + (digest, compactJwt) -> { + callbackBytes[0] = compactJwt; + transientJwt[0] = new String(compactJwt, StandardCharsets.US_ASCII); + throw new IllegalStateException("callback failed: " + transientJwt[0]); + })); + + assertNull(failure.getCause()); + assertFalse(failure.getMessage().contains(transientJwt[0])); + assertFalse(failure.toString().contains(transientJwt[0])); + assertTrue(Arrays.equals(new byte[callbackBytes[0].length], callbackBytes[0])); + } + + @Test + void rejectsEveryExpectedIdentityMismatch() { + AccountMountedJwtSignerBundle.ExpectedIdentity valid = identity(); + AccountMountedJwtSignerBundle.ExpectedIdentity[] mismatches = { + new AccountMountedJwtSignerBundle.ExpectedIdentity( + "production", + valid.clusterId(), + valid.namespace(), + valid.operationId(), + valid.generation(), + valid.kid(), + valid.publicKeyFingerprint()), + new AccountMountedJwtSignerBundle.ExpectedIdentity( + valid.environmentId(), + "cluster-b", + valid.namespace(), + valid.operationId(), + valid.generation(), + valid.kid(), + valid.publicKeyFingerprint()), + new AccountMountedJwtSignerBundle.ExpectedIdentity( + valid.environmentId(), + valid.clusterId(), + "other", + valid.operationId(), + valid.generation(), + valid.kid(), + valid.publicKeyFingerprint()), + new AccountMountedJwtSignerBundle.ExpectedIdentity( + valid.environmentId(), + valid.clusterId(), + valid.namespace(), + "1f1ce3e0-29f4-45a8-a5ed-b1a9e2dc087a", + valid.generation(), + valid.kid(), + valid.publicKeyFingerprint()), + new AccountMountedJwtSignerBundle.ExpectedIdentity( + valid.environmentId(), + valid.clusterId(), + valid.namespace(), + valid.operationId(), + "43", + valid.kid(), + valid.publicKeyFingerprint()), + new AccountMountedJwtSignerBundle.ExpectedIdentity( + valid.environmentId(), + valid.clusterId(), + valid.namespace(), + valid.operationId(), + valid.generation(), + "another-kid", + valid.publicKeyFingerprint()), + new AccountMountedJwtSignerBundle.ExpectedIdentity( + valid.environmentId(), + valid.clusterId(), + valid.namespace(), + valid.operationId(), + valid.generation(), + valid.kid(), + "0".repeat(64)) + }; + + for (AccountMountedJwtSignerBundle.ExpectedIdentity mismatch : mismatches) { + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException failure = + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> observe(mismatch)); + assertFalse(failure.getMessage().contains(privateMount.toString())); + assertFalse(failure.getMessage().contains(privateKeyText(rsa3072))); + } + } + + @Test + void rejectsUnknownNullDuplicateAndUnsupportedPrivateBundleFields() throws Exception { + String valid = bundleJson(identity(), rsa3072); + assertInvalidPrivateJson(valid.substring(0, valid.length() - 1) + ",\"unexpected\":true}"); + assertInvalidPrivateJson(valid.replace("\"namespace\":\"firemud\"", "\"namespace\":null")); + assertInvalidPrivateJson(valid.replace("\"algorithm\":\"RS256\"", "\"algorithm\":\"HS256\"")); + assertInvalidPrivateJson( + valid.replace( + "\"algorithm\":\"RS256\"", "\"algorithm\":\"RS256\",\"algorithm\":\"RS256\"")); + assertInvalidPrivateJson(valid.replace("\"privateKeyPkcs8\":\"", "\"privateKeyPkcs8\":\"%%%")); + String encodedPrivateKey = privateKeyText(rsa3072); + assertInvalidPrivateJson( + valid.replace( + "\"privateKeyPkcs8\":\"" + encodedPrivateKey + "\"", + "\"privateKeyPkcs8\":\"" + encodedPrivateKey + "=\"")); + assertInvalidPrivateJson(valid.substring(0, valid.length() - 2)); + + byte[] malformedUtf8 = {(byte) 0xc3, (byte) 0x28}; + Files.write(privateMount.resolve("current.key"), malformedUtf8); + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> observe(identity())); + } + + @Test + void rejectsMalformedMissingAlteredDuplicateAndPrivateJwksEntries() throws Exception { + String validJwk = jwk(identity().kid(), (RSAPublicKey) rsa3072.getPublic()); + Files.writeString(publicMount.resolve("jwks.json"), "{\"keys\":[]}"); + assertInvalidMountedPair(); + + Files.writeString( + publicMount.resolve("jwks.json"), + "{\"keys\":[" + jwk("other-kid", (RSAPublicKey) rsa3072.getPublic()) + "]}"); + assertInvalidMountedPair(); + + RSAPublicKey publicKey = (RSAPublicKey) rsa3072.getPublic(); + String changedModulus = base64Url(unsigned(publicKey.getModulus().subtract(BigInteger.TWO))); + String altered = + jwk(identity().kid(), publicKey) + .replace( + "\"n\":\"" + base64Url(unsigned(publicKey.getModulus())) + "\"", + "\"n\":\"" + changedModulus + "\""); + Files.writeString(publicMount.resolve("jwks.json"), "{\"keys\":[" + altered + "]}"); + assertInvalidMountedPair(); + + Files.writeString( + publicMount.resolve("jwks.json"), "{\"keys\":[" + validJwk + "," + validJwk + "]}"); + assertInvalidMountedPair(); + + Files.writeString( + publicMount.resolve("jwks.json"), + "{\"keys\":[" + validJwk.replace("}", ",\"d\":\"AQAB\"}") + "]}"); + assertInvalidMountedPair(); + + Files.delete(publicMount.resolve("jwks.json")); + assertInvalidMountedPair(); + } + + @Test + void rejectsWeakNonCrtAndNonRsaPrivateKeys() { + WeakRsaCrtPrivateKey weakKey = new WeakRsaCrtPrivateKey(); + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> AccountMountedJwtSignerBundle.validateStrongRsaCrtPrivateKey(weakKey)); + + NonCrtRsaPrivateKey nonCrtKey = new NonCrtRsaPrivateKey(); + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> AccountMountedJwtSignerBundle.validateStrongRsaCrtPrivateKey(nonCrtKey)); + + PrivateKey nonRsaKey = + new PrivateKey() { + @Override + public String getAlgorithm() { + return "EC"; + } + + @Override + public String getFormat() { + return "PKCS#8"; + } + + @Override + public byte[] getEncoded() { + return new byte[0]; + } + }; + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> AccountMountedJwtSignerBundle.validateStrongRsaCrtPrivateKey(nonRsaKey)); + } + + @Test + void acceptsProjectedSymlinksOnlyInsideTheExplicitPrivateMountRoot() throws Exception { + Path projectedMount = Files.createDirectory(tempDirectory.resolve("projected-private")); + Path versionDirectory = Files.createDirectory(projectedMount.resolve("..2026_10_05_00_00_00")); + Files.writeString(versionDirectory.resolve("current.key"), bundleJson(identity(), rsa3072)); + try { + Files.createSymbolicLink(projectedMount.resolve("..data"), versionDirectory.getFileName()); + Files.createSymbolicLink( + projectedMount.resolve("current.key"), Path.of("..data", "current.key")); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support projected-volume symlinks"); + } + + AccountMountedJwtSignerBundle.LocalObservation observation = + AccountMountedJwtSignerBundle.observeMounted( + projectedMount, Path.of("current.key"), publicMount, Path.of("jwks.json"), identity()); + assertTrue(observation.localPrivatePublicCorrespondenceObserved()); + + Path outside = Files.createDirectory(tempDirectory.resolve("outside-private")); + Files.writeString(outside.resolve("current.key"), bundleJson(identity(), rsa3072)); + Path escapingMount = Files.createDirectory(tempDirectory.resolve("escaping-private")); + try { + Files.createSymbolicLink( + escapingMount.resolve("current.key"), outside.resolve("current.key")); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support symlink validation"); + } + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> + AccountMountedJwtSignerBundle.observeMounted( + escapingMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity())); + + Path outsideJwks = outside.resolve("jwks.json"); + Files.writeString(outsideJwks, jwksJson(identity(), rsa3072)); + Files.delete(publicMount.resolve("jwks.json")); + try { + Files.createSymbolicLink(publicMount.resolve("jwks.json"), outsideJwks); + } catch (UnsupportedOperationException | java.io.IOException ex) { + Assumptions.assumeTrue(false, "Filesystem does not support public-projection symlink checks"); + } + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> observe(identity())); + } + + @Test + void rejectsInvalidCanonicalIdentityEncodingsAndPartialProjectionFiles() throws Exception { + AccountMountedJwtSignerBundle.ExpectedIdentity malformedIdentity = + new AccountMountedJwtSignerBundle.ExpectedIdentity( + ENVIRONMENT, + CLUSTER, + NAMESPACE, + "7AF097EA-B1D1-42EA-9F24-46AEB211A779", + GENERATION, + KID, + identity().publicKeyFingerprint()); + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> observe(malformedIdentity)); + + Files.writeString( + privateMount.resolve("current.key"), + bundleJson(identity(), rsa3072).replace("\"generation\":\"42\"", "\"generation\":\"042\"")); + assertInvalidMountedPair(); + + Files.writeString(publicMount.resolve("jwks.json"), "{\"keys\":["); + assertInvalidMountedPair(); + } + + @Test + void rejectsOversizedPrivateAndPublicProjectionFiles() throws Exception { + Files.write( + privateMount.resolve("current.key"), + new byte[AccountMountedJwtSignerBundle.MAX_PRIVATE_BUNDLE_BYTES + 1]); + assertInvalidMountedPair(); + + Files.writeString(privateMount.resolve("current.key"), bundleJson(identity(), rsa3072)); + Files.write( + publicMount.resolve("jwks.json"), + new byte[AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES + 1]); + assertInvalidMountedPair(); + } + + private AccountMountedJwtSignerBundle.LocalObservation observe( + AccountMountedJwtSignerBundle.ExpectedIdentity expected) { + return AccountMountedJwtSignerBundle.observeMounted( + privateMount, Path.of("current.key"), publicMount, Path.of("jwks.json"), expected); + } + + private void assertBoundTupleRejected( + AccountAuthoritySnapshot authority, Map tuple, String tenant) { + long issued = 1_800_000_000L; + var bound = + new AccountMountedJwtSignerBundle.BoundDelegationClaims(tenant, tuple, Map.of(tenant, "3")); + AtomicBoolean callbackInvoked = new AtomicBoolean(); + + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> + AccountMountedJwtSignerBundle.signCommittedGameplayDelegationDigest( + privateMount, + Path.of("current.key"), + publicMount, + Path.of("jwks.json"), + identity(), + new AccountMountedJwtSignerBundle.DelegationSigningSpec( + delegationIdentity(authority.accountId(), issued), + authority, + Optional.of(bound)), + (digest, compactJwt) -> callbackInvoked.set(true))); + + assertFalse(callbackInvoked.get()); + } + + private static AccountGameplayDelegationPendingIdentity delegationIdentity( + UUID accountId, long issuedAtEpochSecond) { + return new AccountGameplayDelegationPendingIdentity( + UUID.randomUUID(), + UUID.randomUUID(), + accountId, + "spiffe://firemud/ns/firemud/sa/game-session-service", + UUID.randomUUID(), + AccountGameplayCredentialRequestBindingFixture.binding(), + "ab".repeat(32), + UUID.randomUUID(), + issuedAtEpochSecond, + issuedAtEpochSecond, + issuedAtEpochSecond + 120); + } + + private static AccountAuthoritySnapshot authoritySnapshot( + UUID accountId, long issuerGeneration, long accountGeneration) { + Optional cutoff = + accountGeneration == 1 + ? Optional.empty() + : Optional.of(accountCutoff(accountId, accountGeneration)); + return new AccountAuthoritySnapshot( + accountId, + issuerGeneration, + issuerGeneration, + accountGeneration, + accountGeneration, + accountGeneration, + accountGeneration, + cutoff); + } + + private static GameSessionAccountDelegationProfile.AccountSecurityCutoff accountCutoff( + UUID accountId, long accountGeneration) { + return new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + Long.toString(accountGeneration), + "account:auth-authority:v1:account/" + accountId, + Long.toString(accountGeneration - 1)); + } + + private static Map tenantTuple( + long issuerGeneration, + long accountGeneration, + Optional cutoff, + String tenant) { + Map tuple = + new LinkedHashMap<>( + GameSessionAccountDelegationProfile.authorityTuple( + issuerGeneration, accountGeneration, cutoff)); + tuple.put("tenantAuthorityGeneration", Map.of(tenant, "5")); + tuple.put("membershipAuthorityGeneration", Map.of(tenant, "7")); + return tuple; + } + + private void assertInvalidPrivateJson(String json) throws Exception { + Files.writeString(privateMount.resolve("current.key"), json); + assertInvalidMountedPair(); + } + + private void assertInvalidMountedPair() { + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException failure = + assertThrows( + AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class, + () -> observe(identity())); + assertFalse(failure.getMessage().contains(privateMount.toString())); + assertFalse(failure.getMessage().contains(privateKeyText(rsa3072))); + } + + private static AccountMountedJwtSignerBundle.ExpectedIdentity identity() { + return new AccountMountedJwtSignerBundle.ExpectedIdentity( + ENVIRONMENT, CLUSTER, NAMESPACE, OPERATION, GENERATION, KID, fingerprint(rsa3072)); + } + + private static String bundleJson( + AccountMountedJwtSignerBundle.ExpectedIdentity identity, KeyPair pair) { + return "{" + + "\"version\":1," + + "\"environmentId\":\"" + + identity.environmentId() + + "\"," + + "\"clusterId\":\"" + + identity.clusterId() + + "\"," + + "\"namespace\":\"" + + identity.namespace() + + "\"," + + "\"operationId\":\"" + + identity.operationId() + + "\"," + + "\"generation\":\"" + + identity.generation() + + "\"," + + "\"kid\":\"" + + identity.kid() + + "\"," + + "\"algorithm\":\"RS256\"," + + "\"privateKeyPkcs8\":\"" + + privateKeyText(pair) + + "\"," + + "\"publicKeyFingerprint\":\"" + + identity.publicKeyFingerprint() + + "\"" + + "}"; + } + + private static String jwksJson( + AccountMountedJwtSignerBundle.ExpectedIdentity identity, KeyPair pair) { + return "{\"keys\":[" + jwk(identity.kid(), (RSAPublicKey) pair.getPublic()) + "]}"; + } + + private static String jwk(String kid, RSAPublicKey key) { + return "{" + + "\"kty\":\"RSA\"," + + "\"use\":\"sig\"," + + "\"alg\":\"RS256\"," + + "\"kid\":\"" + + kid + + "\"," + + "\"n\":\"" + + base64Url(unsigned(key.getModulus())) + + "\"," + + "\"e\":\"" + + base64Url(unsigned(key.getPublicExponent())) + + "\"" + + "}"; + } + + private static String fingerprint(KeyPair pair) { + RSAPublicKey key = (RSAPublicKey) pair.getPublic(); + String canonicalJwk = + "{\"e\":\"" + + base64Url(unsigned(key.getPublicExponent())) + + "\",\"kty\":\"RSA\",\"n\":\"" + + base64Url(unsigned(key.getModulus())) + + "\"}"; + try { + byte[] digest = + java.security.MessageDigest.getInstance("SHA-256") + .digest(canonicalJwk.getBytes(StandardCharsets.US_ASCII)); + return HexFormat.of().formatHex(digest); + } catch (java.security.GeneralSecurityException ex) { + throw new IllegalStateException(ex); + } + } + + private static String sha256(byte[] bytes) { + try { + return HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (java.security.GeneralSecurityException ex) { + throw new IllegalStateException(ex); + } + } + + private static String privateKeyText(KeyPair pair) { + byte[] encoded = pair.getPrivate().getEncoded(); + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(encoded); + } finally { + Arrays.fill(encoded, (byte) 0); + } + } + + private static byte[] unsigned(BigInteger value) { + byte[] encoded = value.toByteArray(); + return encoded.length > 1 && encoded[0] == 0 + ? Arrays.copyOfRange(encoded, 1, encoded.length) + : encoded; + } + + private static String base64Url(byte[] value) { + try { + return Base64.getUrlEncoder().withoutPadding().encodeToString(value); + } finally { + Arrays.fill(value, (byte) 0); + } + } + + private static boolean isAscii(byte[] value) { + for (byte octet : value) { + if (octet < 0x21 || octet > 0x7e) { + return false; + } + } + return true; + } + + private static final class WeakRsaCrtPrivateKey implements RSAPrivateCrtKey { + @Override + public BigInteger getModulus() { + return BigInteger.ONE.shiftLeft(2_047).setBit(0); + } + + @Override + public BigInteger getPublicExponent() { + return BigInteger.valueOf(65_537); + } + + @Override + public BigInteger getPrivateExponent() { + return BigInteger.valueOf(3); + } + + @Override + public BigInteger getPrimeP() { + return BigInteger.valueOf(3); + } + + @Override + public BigInteger getPrimeQ() { + return BigInteger.valueOf(5); + } + + @Override + public BigInteger getPrimeExponentP() { + return BigInteger.ONE; + } + + @Override + public BigInteger getPrimeExponentQ() { + return BigInteger.ONE; + } + + @Override + public BigInteger getCrtCoefficient() { + return BigInteger.ONE; + } + + @Override + public String getAlgorithm() { + return "RSA"; + } + + @Override + public String getFormat() { + return "PKCS#8"; + } + + @Override + public byte[] getEncoded() { + return new byte[0]; + } + } + + private static final class NonCrtRsaPrivateKey implements RSAPrivateKey { + @Override + public BigInteger getModulus() { + return BigInteger.ONE.shiftLeft(3_071).setBit(0); + } + + @Override + public BigInteger getPrivateExponent() { + return BigInteger.valueOf(3); + } + + @Override + public String getAlgorithm() { + return "RSA"; + } + + @Override + public String getFormat() { + return "PKCS#8"; + } + + @Override + public byte[] getEncoded() { + return new byte[0]; + } + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingFixture.java new file mode 100644 index 0000000000..7123f0a367 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/repository/AccountGameplayCredentialRequestBindingFixture.java @@ -0,0 +1,11 @@ +package net.firedevops.firemud.accountservice.repository; + +/** Deterministic, non-production keyed-binding fixture shared by the Account owner proofs. */ +public final class AccountGameplayCredentialRequestBindingFixture { + private AccountGameplayCredentialRequestBindingFixture() {} + + public static AccountGameplayCredentialRequestBinding binding() { + return new AccountGameplayCredentialRequestBinding( + 1, "test-account-login-key", "ab".repeat(32)); + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java new file mode 100644 index 0000000000..051e4009be --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java @@ -0,0 +1,101 @@ +package net.firedevops.firemud.common.security; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** Validates the canonical claim shape of the registry-backed control-ui JWT profile. */ +public final class ControlUiJwtProfileValidator { + public static final String PROFILE = "control-ui"; + public static final String AUDIENCE = "control-ui"; + public static final String TOKEN_TYPE = "control-ui"; + private static final String ISSUER = "firemud-account-service"; + public static final Set REQUIRED_CLAIMS; + public static final Set OPTIONAL_CLAIMS = Set.of("globalRoles"); + + static { + Set required = + new java.util.HashSet<>(AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS); + required.add("scopedRoles"); + REQUIRED_CLAIMS = Set.copyOf(required); + } + + private ControlUiJwtProfileValidator() {} + + /** + * Checks claim shape only; it does not validate a registry record or current Account authority. + * + * @param claims immutable verified claims + * @param maxControlUiTenantScopes explicit finite profile cap for every applicable tenant map + */ + public static void validateClaims(Map claims, int maxControlUiTenantScopes) { + if (maxControlUiTenantScopes <= 0 + || maxControlUiTenantScopes + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw AccountJwtProfileClaimSupport.invalid(); + } + AccountJwtProfileClaimSupport.requireClaimFields(claims, REQUIRED_CLAIMS, OPTIONAL_CLAIMS); + AccountJwtProfileClaimSupport.requireCommonIdentity(claims, ISSUER, AUDIENCE); + + Map tuple = + AccountJwtProfileClaimSupport.requireAuthorityTuple( + claims.get("authorityTuple"), true, false, false); + if (!(tuple.get("privateRealmGrantVersions") instanceof List grants) || !grants.isEmpty()) { + throw AccountJwtProfileClaimSupport.invalid(); + } + Map tenantGenerations = + AccountJwtProfileClaimSupport.requireGenerationMap(tuple.get("tenantAuthorityGeneration")); + Map membershipGenerations = + AccountJwtProfileClaimSupport.requireGenerationMap( + tuple.get("membershipAuthorityGeneration")); + Map membershipVersions = + AccountJwtProfileClaimSupport.requireVersionMap(claims.get("membershipVersion")); + String accountId = (String) claims.get("accountId"); + // The canonical profile forbids an accountId as a tenant-map key; this is shape rejection, + // not evidence about tenant ownership or an authorization predicate. + if (!membershipGenerations.keySet().equals(membershipVersions.keySet()) + || tenantGenerations.containsKey(accountId) + || membershipGenerations.containsKey(accountId) + || membershipVersions.containsKey(accountId)) { + throw AccountJwtProfileClaimSupport.invalid(); + } + + Map scopedRoles = + AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles")); + scopedRoles.forEach( + (tenantId, roles) -> { + AccountJwtProfileClaimSupport.requireUuid(tenantId); + AccountJwtProfileClaimSupport.requireRoleList(roles); + if (((List) roles).isEmpty() || tenantId.equals(claims.get("accountId"))) { + throw AccountJwtProfileClaimSupport.invalid(); + } + }); + if (!scopedRoles.keySet().containsAll(tenantGenerations.keySet())) { + throw AccountJwtProfileClaimSupport.invalid(); + } + + requireAtMost(scopedRoles.size(), maxControlUiTenantScopes); + requireAtMost(tenantGenerations.size(), maxControlUiTenantScopes); + requireAtMost(membershipGenerations.size(), maxControlUiTenantScopes); + requireAtMost(membershipVersions.size(), maxControlUiTenantScopes); + + Object billingCutoff = tuple.get("tenantBillingCutoff"); + if (billingCutoff != null) { + Map billingCutoffs = + AccountJwtProfileClaimSupport.requireObjectMap(billingCutoff); + requireAtMost(billingCutoffs.size(), maxControlUiTenantScopes); + if (!scopedRoles.keySet().containsAll(billingCutoffs.keySet())) { + throw AccountJwtProfileClaimSupport.invalid(); + } + } + if (claims.containsKey("globalRoles")) { + AccountJwtProfileClaimSupport.requireRoleList(claims.get("globalRoles")); + } + } + + private static void requireAtMost(int entries, int maximum) { + if (entries > maximum) { + throw AccountJwtProfileClaimSupport.invalid(); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java new file mode 100644 index 0000000000..17584d3171 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java @@ -0,0 +1,890 @@ +package net.firedevops.firemud.common.security; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.Base64; +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.common.json.Rfc8785CanonicalJson; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.type.TypeReference; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Strict finite-bounded codec for initial and distinct public-production bound delegation + * candidates. + * + *

Pending records are non-authorizing. This codec checks JOSE/claim shape and exact Account + * snapshot equality, but does not verify the JWS signature or establish signer/currentness proof. + * The signing and Account evidence owners must do that before any active transition is usable. + */ +public final class GameSessionAccountDelegationRegistryRecord { + private static final int SCHEMA_VERSION = 2; + private static final int PENDING_REGISTRY_VERSION = 1; + private static final int ACTIVE_REGISTRY_VERSION = 2; + private static final String PENDING = "pending"; + private static final String ACTIVE = "active"; + private static final Pattern HASH = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Pattern POSITIVE_LINEARIZATION = Pattern.compile("[1-9][0-9]{0,19}"); + private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); + private static final Set TOKEN_CLAIMS = + Set.of( + "iss", + "sub", + "jti", + "accountId", + "aud", + "iat", + "nbf", + "exp", + "tokenGeneration", + "authorityTuple", + "membershipVersion", + "issuanceFence"); + private static final Set HEADER_REQUIRED = Set.of("alg", "kid"); + private static final Set HEADER_ALLOWED = Set.of("alg", "kid", "typ"); + private static final Set RECORD_FIELDS = + Set.of( + "schemaVersion", + "registryVersion", + "tokenHash", + "kid", + "signerGeneration", + "accountId", + "issuer", + "profile", + "type", + "audience", + "jti", + "iat", + "nbf", + "exp", + "tokenGeneration", + "operationId", + "requestId", + "requestDigest", + "state", + "authorityTuple", + "membershipVersion", + "issuanceFence", + "authoritySourceVersions", + "authEvidenceBundle"); + private static final Set AUTHORITY_TUPLE_FIELDS = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions"); + private static final Set AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF = + Set.of( + "issuerAuthGeneration", + "accountAuthorityGeneration", + "tenantAuthorityGeneration", + "membershipAuthorityGeneration", + "privateRealmGrantVersions", + "accountSecurityCutoff"); + private static final Set ACCOUNT_SECURITY_CUTOFF_FIELDS = + Set.of("accountAuthorityGeneration", "outboxStreamKey", "outboxSequence"); + private static final Set SOURCE_VERSION_FIELDS = + Set.of("issuerSourceVersion", "accountSourceVersion", "issuanceFenceSourceVersion"); + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final Map fields; + + private GameSessionAccountDelegationRegistryRecord(Map fields) { + this.fields = immutableMap(fields); + } + + /** Creates the distinct first public-production tenant-bound pending record. */ + public static GameSessionAccountDelegationRegistryRecord fromAccountSignedBoundCompactJwt( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot account, + EvidenceBundleReference evidence, + String tenantId, + Map exactTuple, + Map exactMembershipVersion, + long now, + long maxBytes) { + GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority( + tenantId, exactTuple, exactMembershipVersion); + return fromCandidate( + compactJwt, + signerGeneration, + binding, + account, + evidence, + now, + maxBytes, + new BoundShape(tenantId, exactTuple, exactMembershipVersion)); + } + + private record BoundShape( + String tenantId, Map tuple, Map membershipVersion) {} + + /** Validates the exact signed-token candidate and creates only its pending registry record. */ + public static GameSessionAccountDelegationRegistryRecord fromAccountSignedCompactJwt( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot snapshot, + EvidenceBundleReference evidenceBundleReference, + long nowEpochSecond, + long maxRecordBytes) { + return fromCandidate( + compactJwt, + signerGeneration, + binding, + snapshot, + evidenceBundleReference, + nowEpochSecond, + maxRecordBytes, + null); + } + + private static GameSessionAccountDelegationRegistryRecord fromCandidate( + String compactJwt, + String signerGeneration, + IssuanceBinding binding, + AccountAuthoritySnapshot snapshot, + EvidenceBundleReference evidenceBundleReference, + long nowEpochSecond, + long maxRecordBytes, + BoundShape bound) { + Objects.requireNonNull(compactJwt, "Compact Account JWT is required"); + Objects.requireNonNull(binding, "Durable issuance binding is required"); + Objects.requireNonNull(snapshot, "Locked Account authority snapshot is required"); + Objects.requireNonNull( + evidenceBundleReference, "Persisted Account evidence bundle is required"); + requirePositiveDecimal(signerGeneration, "signerGeneration"); + requirePositive(nowEpochSecond, "nowEpochSecond"); + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + + CompactToken compact = parseCompactJwt(compactJwt); + Map claims = compact.claims(); + requireExactFields(claims, fieldsFor(TOKEN_CLAIMS, bound != null), "JWT claims"); + String issuer = requireText(claims.get("iss"), "iss", 256); + String subject = requireCanonicalUuid(claims.get("sub"), "sub"); + String accountId = requireCanonicalUuid(claims.get("accountId"), "accountId"); + String jti = requireCanonicalUuid(claims.get("jti"), "jti"); + String audience = requireText(claims.get("aud"), "aud", 128); + long issuedAt = requirePositiveInteger(claims.get("iat"), "iat"); + long notBefore = requirePositiveInteger(claims.get("nbf"), "nbf"); + long expiresAt = requirePositiveInteger(claims.get("exp"), "exp"); + String tokenGeneration = + requirePositiveDecimal(claims.get("tokenGeneration"), "tokenGeneration"); + String issuanceFence = requirePositiveDecimal(claims.get("issuanceFence"), "issuanceFence"); + + requireEqual(GameSessionAccountDelegationProfile.ISSUER, issuer, "Account issuer mismatch"); + requireEqual(GameSessionAccountDelegationProfile.AUDIENCE, audience, "audience mismatch"); + requireEqual(snapshot.accountId().toString(), accountId, "Account UUID mismatch"); + requireEqual(subject, accountId, "sub and accountId mismatch"); + requireEqual(binding.accountId(), accountId, "durable operation account mismatch"); + requireEqual("1", tokenGeneration, "initial delegation tokenGeneration must be one"); + requireEqual( + Long.toString(snapshot.issuanceFence()), issuanceFence, "Account issuance fence mismatch"); + validateTimeWindow(issuedAt, notBefore, expiresAt, nowEpochSecond); + if (bound == null) { + validateAuthorityTuple( + claims.get("authorityTuple"), claims.get("membershipVersion"), snapshot); + } else { + GameSessionAccountDelegationJwtProfileValidator.validatePublicTenantBoundClaims(claims); + requireEqual(bound.tenantId(), claims.get("tenantId"), "bound tenant mismatch"); + requireEqual(bound.tuple(), claims.get("authorityTuple"), "bound tuple mismatch"); + requireEqual( + bound.membershipVersion(), + claims.get("membershipVersion"), + "independent membership version mismatch"); + requireEqual( + Long.toString(snapshot.issuerGeneration()), + bound.tuple().get("issuerAuthGeneration"), + "issuer mismatch"); + requireEqual( + Long.toString(snapshot.accountGeneration()), + bound.tuple().get("accountAuthorityGeneration"), + "account mismatch"); + if (!Objects.equals( + snapshot.accountSecurityCutoff().map(value -> value.toMap()).orElse(null), + bound.tuple().get("accountSecurityCutoff"))) throw invalid("Account cutoff mismatch"); + } + + Map record = new LinkedHashMap<>(); + record.put("schemaVersion", SCHEMA_VERSION); + record.put("registryVersion", PENDING_REGISTRY_VERSION); + record.put("tokenHash", sha256(compactJwt.getBytes(StandardCharsets.US_ASCII))); + record.put("kid", compact.keyId()); + record.put("signerGeneration", signerGeneration); + record.put("accountId", accountId); + if (bound != null) record.put("tenantId", bound.tenantId()); + record.put("issuer", issuer); + record.put("profile", GameSessionAccountDelegationProfile.PROFILE); + record.put("type", GameSessionAccountDelegationProfile.TYPE); + record.put("audience", audience); + record.put("jti", jti); + record.put("iat", issuedAt); + record.put("nbf", notBefore); + record.put("exp", expiresAt); + record.put("tokenGeneration", tokenGeneration); + record.put("operationId", binding.operationId()); + record.put("requestId", binding.requestId()); + record.put("requestDigest", binding.requestDigest()); + record.put("state", PENDING); + record.put("authorityTuple", claims.get("authorityTuple")); + record.put("membershipVersion", claims.get("membershipVersion")); + record.put("issuanceFence", issuanceFence); + record.put("authoritySourceVersions", snapshot.sourceVersions()); + record.put("authEvidenceBundle", evidenceBundleReference.toMap()); + + GameSessionAccountDelegationRegistryRecord result = + new GameSessionAccountDelegationRegistryRecord(record); + result.toCanonicalJsonBytes(maxRecordBytes); + return result; + } + + /** Decodes a supported canonical registry value without granting it authority. */ + public static GameSessionAccountDelegationRegistryRecord decode( + byte[] canonicalUtf8, long maxRecordBytes) { + Objects.requireNonNull(canonicalUtf8, "Registry bytes are required"); + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + if (canonicalUtf8.length == 0 || canonicalUtf8.length > maxRecordBytes) { + throw invalid("Registry record exceeds its byte bound"); + } + String json = strictUtf8(canonicalUtf8); + byte[] canonical = canonicalize(json); + if (!Arrays.equals(canonicalUtf8, canonical)) { + throw invalid("Registry value is not canonical RFC 8785 UTF-8"); + } + Map decoded = parseObject(json, "registry record"); + requireExactFields( + decoded, fieldsFor(RECORD_FIELDS, decoded.containsKey("tenantId")), "registry record"); + validateRecord(decoded); + return new GameSessionAccountDelegationRegistryRecord(decoded); + } + + /** Returns canonical RFC 8785 record bytes, subject to both the caller and profile ceilings. */ + public byte[] toCanonicalJsonBytes(long maxRecordBytes) { + requireBound( + maxRecordBytes, + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, + "maxRecordBytes"); + byte[] canonical = canonicalize(serialize(fields)); + if (canonical.length == 0 || canonical.length > maxRecordBytes) { + throw invalid("Registry record exceeds its byte bound"); + } + return canonical; + } + + public String tokenHash() { + return textField("tokenHash"); + } + + public String kid() { + return textField("kid"); + } + + public String signerGeneration() { + return textField("signerGeneration"); + } + + public String accountId() { + return textField("accountId"); + } + + public String jti() { + return textField("jti"); + } + + public String operationId() { + return textField("operationId"); + } + + public String requestId() { + return textField("requestId"); + } + + public String requestDigest() { + return textField("requestDigest"); + } + + public String state() { + return textField("state"); + } + + public long issuedAtEpochSecond() { + return requirePositiveInteger(fields.get("iat"), "iat"); + } + + public long notBeforeEpochSecond() { + return requirePositiveInteger(fields.get("nbf"), "nbf"); + } + + public long issuanceFence() { + return requirePositiveDecimalLong(fields.get("issuanceFence"), "issuanceFence"); + } + + public long registryVersion() { + return requirePositiveInteger(fields.get("registryVersion"), "registryVersion"); + } + + public EvidenceBundleReference evidenceBundleReference() { + Map value = + requireObject(fields.get("authEvidenceBundle"), "authEvidenceBundle"); + return new EvidenceBundleReference( + requirePositiveDecimal(value.get("bundleVersion"), "bundleVersion"), + requirePositiveDecimal(value.get("sourceVersion"), "sourceVersion"), + requirePositiveDecimal(value.get("sourceFence"), "sourceFence"), + requirePositiveLinearization(value.get("linearization")), + requireMatchValue(HASH, value.get("canonicalSha256"), "canonicalSha256")); + } + + public long expiresAtEpochSecond() { + return requirePositiveInteger(fields.get("exp"), "exp"); + } + + public Map fields() { + return immutableMap(fields); + } + + private String textField(String field) { + return requireText(fields.get(field), field, 256); + } + + private static Set fieldsFor(Set initial, boolean bound) { + if (!bound) return initial; + var fields = new java.util.HashSet<>(initial); + fields.add("tenantId"); + return Set.copyOf(fields); + } + + private static void validateRecord(Map record) { + requireExactInteger(record.get("schemaVersion"), SCHEMA_VERSION, "schemaVersion"); + long registryVersion = requirePositiveInteger(record.get("registryVersion"), "registryVersion"); + String state = requireText(record.get("state"), "state", 16); + if (PENDING.equals(state)) { + if (registryVersion != PENDING_REGISTRY_VERSION) { + throw invalid("pending registry version mismatch"); + } + } else if (ACTIVE.equals(state)) { + if (registryVersion != ACTIVE_REGISTRY_VERSION) { + throw invalid("active registry version mismatch"); + } + } else { + throw invalid("Unsupported registry lifecycle state"); + } + requireMatch(HASH, record.get("tokenHash"), "tokenHash"); + requireMatch(HASH, record.get("requestDigest"), "requestDigest"); + requireCanonicalUuid(record.get("jti"), "jti"); + requireCanonicalUuid(record.get("operationId"), "operationId"); + requireCanonicalUuid(record.get("requestId"), "requestId"); + requireMatch(KID, record.get("kid"), "kid"); + requirePositiveDecimal(record.get("signerGeneration"), "signerGeneration"); + requireEqual(GameSessionAccountDelegationProfile.ISSUER, record.get("issuer"), "issuer"); + requireEqual(GameSessionAccountDelegationProfile.PROFILE, record.get("profile"), "profile"); + requireEqual(GameSessionAccountDelegationProfile.TYPE, record.get("type"), "type"); + requireEqual(GameSessionAccountDelegationProfile.AUDIENCE, record.get("audience"), "audience"); + String accountId = requireCanonicalUuid(record.get("accountId"), "accountId"); + long issuedAt = requirePositiveInteger(record.get("iat"), "iat"); + long notBefore = requirePositiveInteger(record.get("nbf"), "nbf"); + long expiresAt = requirePositiveInteger(record.get("exp"), "exp"); + requireEqual( + "1", + requirePositiveDecimal(record.get("tokenGeneration"), "tokenGeneration"), + "initial token generation mismatch"); + validateTimeWindow(issuedAt, notBefore, expiresAt, 0L); + Map tuple = requireObject(record.get("authorityTuple"), "authorityTuple"); + String accountGeneration = + requirePositiveDecimal( + tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"); + boolean hasCutoff = tuple.containsKey("accountSecurityCutoff"); + if (hasCutoff != !"1".equals(accountGeneration)) { + throw invalid("Account security cutoff presence does not match the source generation"); + } + Set tupleFields = + new java.util.HashSet<>( + hasCutoff ? AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF : AUTHORITY_TUPLE_FIELDS); + if (record.containsKey("tenantId") && tuple.containsKey("tenantBillingCutoff")) + tupleFields.add("tenantBillingCutoff"); + requireExactFields(tuple, tupleFields, "authorityTuple"); + requirePositiveDecimal(tuple.get("issuerAuthGeneration"), "issuerAuthGeneration"); + if (record.containsKey("tenantId")) { + GameSessionAccountDelegationProfile.requirePublicTenantBoundAuthority( + requireCanonicalUuid(record.get("tenantId"), "tenantId"), + tuple, + requireObject(record.get("membershipVersion"), "membershipVersion")); + } else { + requireEmptyObject(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + requireEmptyObject( + tuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + } + requireEmptyList(tuple.get("privateRealmGrantVersions"), "privateRealmGrantVersions"); + if (hasCutoff) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_SECURITY_CUTOFF_FIELDS, "accountSecurityCutoff"); + String cutoffGeneration = + requirePositiveDecimal(cutoff.get("accountAuthorityGeneration"), "cutoff generation"); + String cutoffSequence = + requirePositiveDecimal(cutoff.get("outboxSequence"), "cutoff outbox sequence"); + String cutoffStream = requireText(cutoff.get("outboxStreamKey"), "cutoff stream", 2048); + long accountGenerationValue = + requirePositiveDecimalLong(accountGeneration, "account generation"); + if (!accountGeneration.equals(cutoffGeneration) + || !Long.toString(accountGenerationValue - 1L).equals(cutoffSequence) + || !("account:auth-authority:v1:account/" + accountId).equals(cutoffStream)) { + throw invalid("Account security cutoff scope or sequence is invalid"); + } + } + if (!record.containsKey("tenantId")) + requireEmptyObject(record.get("membershipVersion"), "membershipVersion"); + requirePositiveDecimal(record.get("issuanceFence"), "issuanceFence"); + Map versions = + requireObject(record.get("authoritySourceVersions"), "authoritySourceVersions"); + requireExactFields(versions, SOURCE_VERSION_FIELDS, "authoritySourceVersions"); + for (String field : SOURCE_VERSION_FIELDS) { + requirePositiveDecimal(versions.get(field), field); + } + Map bundle = + requireObject(record.get("authEvidenceBundle"), "authEvidenceBundle"); + requireExactFields( + bundle, + Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization", "canonicalSha256"), + "authEvidenceBundle"); + requirePositiveDecimal(bundle.get("bundleVersion"), "bundleVersion"); + requirePositiveDecimal(bundle.get("sourceVersion"), "sourceVersion"); + requirePositiveDecimal(bundle.get("sourceFence"), "sourceFence"); + requirePositiveLinearization(bundle.get("linearization")); + requireMatch(HASH, bundle.get("canonicalSha256"), "canonicalSha256"); + } + + private static void validateAuthorityTuple( + Object tupleValue, Object membershipVersionValue, AccountAuthoritySnapshot snapshot) { + Map tuple = requireObject(tupleValue, "authorityTuple"); + Set expectedFields = + snapshot.accountSecurityCutoff().isPresent() + ? AUTHORITY_TUPLE_FIELDS_WITH_ACCOUNT_CUTOFF + : AUTHORITY_TUPLE_FIELDS; + requireExactFields(tuple, expectedFields, "authorityTuple"); + if (canonicalize(serialize(tuple)).length + > GameSessionAccountDelegationProfile.MAX_AUTHORITY_TUPLE_BYTES) { + throw invalid("authorityTuple exceeds its finite profile byte bound"); + } + requireEqual( + Long.toString(snapshot.issuerGeneration()), + requirePositiveDecimal(tuple.get("issuerAuthGeneration"), "issuerAuthGeneration"), + "issuer authority generation mismatch"); + requireEqual( + Long.toString(snapshot.accountGeneration()), + requirePositiveDecimal( + tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration"), + "Account authority generation mismatch"); + requireEmptyObject(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + requireEmptyObject(tuple.get("membershipAuthorityGeneration"), "membershipAuthorityGeneration"); + requireEmptyList(tuple.get("privateRealmGrantVersions"), "privateRealmGrantVersions"); + if (snapshot.accountSecurityCutoff().isPresent()) { + Map cutoff = + requireObject(tuple.get("accountSecurityCutoff"), "accountSecurityCutoff"); + requireExactFields(cutoff, ACCOUNT_SECURITY_CUTOFF_FIELDS, "accountSecurityCutoff"); + requirePositiveDecimal(cutoff.get("accountAuthorityGeneration"), "cutoff generation"); + requirePositiveDecimal(cutoff.get("outboxSequence"), "cutoff outbox sequence"); + requireText(cutoff.get("outboxStreamKey"), "cutoff outboxStreamKey", 2048); + if (!snapshot.accountSecurityCutoff().orElseThrow().toMap().equals(cutoff)) { + throw invalid("Account security cutoff does not match the source snapshot"); + } + } + requireEmptyObject(membershipVersionValue, "membershipVersion"); + } + + private static CompactToken parseCompactJwt(String compactJwt) { + byte[] compactBytes = compactJwt.getBytes(StandardCharsets.US_ASCII); + if (compactJwt.length() == 0 + || compactJwt.length() > GameSessionAccountDelegationProfile.MAX_COMPACT_JWT_BYTES + || compactBytes.length != compactJwt.length()) { + throw invalid("Compact JWT is absent or exceeds its profile byte bound"); + } + String[] parts = compactJwt.split("\\.", -1); + if (parts.length != 3 || Arrays.stream(parts).anyMatch(String::isEmpty)) { + throw invalid("Compact JWT is malformed"); + } + byte[] headerBytes = decodeBase64Url(parts[0]); + byte[] claimsBytes = decodeBase64Url(parts[1]); + decodeBase64Url(parts[2]); + Map header = parseObject(strictUtf8(headerBytes), "JOSE header"); + Set headerFields = header.keySet(); + if (!HEADER_ALLOWED.containsAll(headerFields) || !headerFields.containsAll(HEADER_REQUIRED)) { + throw invalid("JOSE header fields are not the exact supported set"); + } + requireEqual("RS256", header.get("alg"), "Account delegation must use RS256"); + String kid = requireText(header.get("kid"), "kid", 64); + requireMatch(KID, kid, "kid"); + if (header.containsKey("typ")) requireEqual("JWT", header.get("typ"), "typ"); + Map claims = parseObject(strictUtf8(claimsBytes), "JWT claims"); + return new CompactToken(kid, claims); + } + + private static void validateTimeWindow(long issuedAt, long notBefore, long expiresAt, long now) { + long lifetime; + try { + lifetime = Math.subtractExact(expiresAt, issuedAt); + } catch (ArithmeticException ex) { + throw invalid("JWT time bounds are invalid or expired"); + } + long latestAllowedIssuedAt = now; + if (now > 0L) { + try { + latestAllowedIssuedAt = Math.addExact(now, 5L); + } catch (ArithmeticException ex) { + latestAllowedIssuedAt = Long.MAX_VALUE; + } + } + if (notBefore > issuedAt + || lifetime <= 0L + || lifetime > GameSessionAccountDelegationProfile.MAX_TOKEN_LIFETIME_SECONDS + || (now > 0L && (issuedAt > latestAllowedIssuedAt || expiresAt <= now))) { + throw invalid("JWT time bounds are invalid or expired"); + } + } + + private static byte[] decodeBase64Url(String value) { + try { + if (value.indexOf('=') >= 0 || !value.matches("[A-Za-z0-9_-]+")) + throw invalid("JWT segment is not base64url"); + byte[] decoded = Base64.getUrlDecoder().decode(value); + if (!Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(value)) { + throw invalid("JWT segment has a non-canonical base64url encoding"); + } + return decoded; + } catch (IllegalArgumentException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid("JWT segment is malformed"); + } + } + + private static Map parseObject(String json, String field) { + try { + Map parsed = JSON.readValue(json, new TypeReference<>() {}); + if (parsed == null || parsed.isEmpty()) throw invalid(field + " must be a non-empty object"); + return parsed; + } catch (RuntimeException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid(field + " is malformed"); + } + } + + private static Map requireObject(Object value, String field) { + if (!(value instanceof Map map)) throw invalid(field + " must be an object"); + Map result = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String name) || item == null || result.put(name, item) != null) { + throw invalid(field + " contains an invalid member"); + } + }); + return result; + } + + private static Map immutableMap(Map input) { + Map copy = new LinkedHashMap<>(); + input.forEach( + (key, value) -> { + if (key == null || value == null) throw invalid("Null registry field is forbidden"); + copy.put(key, deepImmutable(value)); + }); + return Map.copyOf(copy); + } + + private static Object deepImmutable(Object value) { + if (value instanceof Map map) { + Map nested = new LinkedHashMap<>(); + map.forEach( + (key, item) -> { + if (!(key instanceof String name) || item == null) { + throw invalid("Null or invalid nested registry field is forbidden"); + } + nested.put(name, deepImmutable(item)); + }); + return Map.copyOf(nested); + } + if (value instanceof List list) { + return list.stream().map(GameSessionAccountDelegationRegistryRecord::deepImmutable).toList(); + } + return value; + } + + private static void requireExactFields( + Map value, Set expected, String field) { + if (!value.keySet().equals(expected)) throw invalid(field + " has missing or unknown fields"); + if (value.values().stream().anyMatch(Objects::isNull)) throw invalid(field + " contains null"); + } + + private static void requireEmptyObject(Object value, String field) { + if (!(value instanceof Map map) || !map.isEmpty()) + throw invalid(field + " must be an empty object"); + } + + private static void requireEmptyList(Object value, String field) { + if (!(value instanceof List list) || !list.isEmpty()) + throw invalid(field + " must be an empty list"); + } + + private static long requirePositiveInteger(Object value, String field) { + if (!(value instanceof Number number)) throw invalid(field + " must be a JSON integer"); + String encoded = number.toString(); + if (!POSITIVE_DECIMAL.matcher(encoded).matches()) { + throw invalid(field + " must be a bounded positive integer"); + } + try { + return Long.parseLong(encoded); + } catch (NumberFormatException ex) { + throw invalid(field + " must be a bounded positive integer"); + } + } + + private static long requirePositiveDecimalLong(Object value, String field) { + String decimal = requirePositiveDecimal(value, field); + try { + return Long.parseLong(decimal); + } catch (NumberFormatException ex) { + throw invalid(field + " exceeds the supported range"); + } + } + + private static long requirePositive(long value, String field) { + if (value <= 0L) throw invalid(field + " must be positive"); + return value; + } + + private static String requirePositiveDecimal(Object value, String field) { + if (!(value instanceof String string) || !POSITIVE_DECIMAL.matcher(string).matches()) { + throw invalid(field + " must be a canonical positive decimal string"); + } + try { + Long.parseLong(string); + return string; + } catch (NumberFormatException ex) { + throw invalid(field + " exceeds the supported range"); + } + } + + private static String requireCanonicalUuid(Object value, String field) { + String text = requireText(value, field, 36); + try { + UUID parsed = UUID.fromString(text); + if (!parsed.toString().equals(text) || parsed.equals(new UUID(0L, 0L))) + throw invalid(field + " is not a canonical UUID"); + return text; + } catch (IllegalArgumentException ex) { + if (ex instanceof InvalidRecordException invalid) throw invalid; + throw invalid(field + " is not a canonical UUID"); + } + } + + private static String requireText(Object value, String field, int maxLength) { + if (!(value instanceof String text) || text.isEmpty() || text.length() > maxLength) { + throw invalid(field + " must be a bounded non-empty string"); + } + for (int i = 0; i < text.length(); i++) { + if (Character.isISOControl(text.charAt(i))) + throw invalid(field + " contains a control character"); + } + return text; + } + + private static void requireMatch(Pattern pattern, Object value, String field) { + if (!(value instanceof String text) || !pattern.matcher(text).matches()) + throw invalid(field + " has an invalid format"); + } + + private static String requireMatchValue(Pattern pattern, Object value, String field) { + requireMatch(pattern, value, field); + return (String) value; + } + + private static String requirePositiveLinearization(Object value) { + if (!(value instanceof String text) || !POSITIVE_LINEARIZATION.matcher(text).matches()) { + throw invalid("bundle linearization is malformed"); + } + return text; + } + + private static void requireExactInteger(Object value, long expected, String field) { + if (!(value instanceof Number number)) throw invalid(field + " must be an integer"); + String encoded = number.toString(); + if (!encoded.matches("0|[1-9][0-9]{0,18}")) { + throw invalid(field + " is unsupported"); + } + try { + if (Long.parseLong(encoded) != expected) throw invalid(field + " is unsupported"); + } catch (NumberFormatException ex) { + throw invalid(field + " is unsupported"); + } + } + + private static void requireEqual(Object expected, Object actual, String message) { + if (!Objects.equals(expected, actual)) throw invalid(message); + } + + private static void requireBound(long value, long maximum, String field) { + if (value <= 0L || value > maximum) + throw invalid(field + " is outside the finite profile bound"); + } + + 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 invalid("JWT/registry JSON is not valid UTF-8"); + } + } + + private static String serialize(Object value) { + try { + return JSON.writeValueAsString(value); + } catch (RuntimeException ex) { + throw invalid("Registry JSON could not be serialized"); + } + } + + private static byte[] canonicalize(String value) { + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(value); + } catch (IOException | RuntimeException ex) { + throw invalid("RFC 8785 canonicalization failed"); + } + } + + private static String sha256(byte[] bytes) { + try { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException("SHA-256 is unavailable", ex); + } + } + + private static InvalidRecordException invalid(String message) { + return new InvalidRecordException(message); + } + + private record CompactToken(String keyId, Map claims) {} + + public record AccountAuthoritySnapshot( + UUID accountId, + long issuerGeneration, + long issuerSourceVersion, + long accountGeneration, + long accountSourceVersion, + long issuanceFence, + long issuanceFenceSourceVersion, + Optional accountSecurityCutoff) { + public AccountAuthoritySnapshot { + Objects.requireNonNull(accountId, "Canonical Account UUID is required"); + Objects.requireNonNull(accountSecurityCutoff, "Account cutoff applicability is required"); + if (accountId.equals(new UUID(0L, 0L)) + || issuerGeneration <= 0L + || issuerSourceVersion <= 0L + || accountGeneration <= 0L + || accountSourceVersion <= 0L + || issuanceFence <= 0L + || issuanceFenceSourceVersion <= 0L + || issuerGeneration != issuerSourceVersion + || accountGeneration != accountSourceVersion + || accountGeneration != issuanceFence + || accountGeneration != issuanceFenceSourceVersion) { + throw invalid("Durable Account authority snapshot is malformed"); + } + String expectedStream = "account:auth-authority:v1:account/" + accountId; + if (accountGeneration == 1L) { + if (accountSecurityCutoff.isPresent()) { + throw invalid("Fresh sequence-zero Account authority cannot carry a cutoff"); + } + } else { + GameSessionAccountDelegationProfile.AccountSecurityCutoff cutoff = + accountSecurityCutoff.orElseThrow( + () -> invalid("Advanced Account authority requires its source cutoff")); + if (!Long.toString(accountGeneration).equals(cutoff.accountAuthorityGeneration()) + || !expectedStream.equals(cutoff.outboxStreamKey()) + || !Long.toString(accountGeneration - 1L).equals(cutoff.outboxSequence())) { + throw invalid("Account security cutoff scope or sequence is stale"); + } + } + } + + public Map sourceVersions() { + return Map.of( + "issuerSourceVersion", Long.toString(issuerSourceVersion), + "accountSourceVersion", Long.toString(accountSourceVersion), + "issuanceFenceSourceVersion", Long.toString(issuanceFenceSourceVersion)); + } + } + + public record IssuanceBinding( + String operationId, String requestId, String requestDigest, String accountId) { + public IssuanceBinding { + requireCanonicalUuid(operationId, "operationId"); + requireCanonicalUuid(requestId, "requestId"); + requireMatch(HASH, requestDigest, "requestDigest"); + requireCanonicalUuid(accountId, "accountId"); + } + } + + /** Exact immutable V46 bundle reference and digest bound into the registry projection. */ + public record EvidenceBundleReference( + String bundleVersion, + String sourceVersion, + String sourceFence, + String linearization, + String canonicalSha256) { + public EvidenceBundleReference { + requirePositiveDecimal(bundleVersion, "bundleVersion"); + requirePositiveDecimal(sourceVersion, "sourceVersion"); + requirePositiveDecimal(sourceFence, "sourceFence"); + requirePositiveLinearization(linearization); + requireMatch(HASH, canonicalSha256, "canonicalSha256"); + } + + public Map toMap() { + return Map.of( + "bundleVersion", bundleVersion, + "sourceVersion", sourceVersion, + "sourceFence", sourceFence, + "linearization", linearization, + "canonicalSha256", canonicalSha256); + } + } + + public static final class InvalidRecordException extends IllegalArgumentException { + public InvalidRecordException(String message) { + super(message); + } + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java new file mode 100644 index 0000000000..86d11650b4 --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidator.java @@ -0,0 +1,38 @@ +package net.firedevops.firemud.common.security; + +import java.util.Map; +import java.util.Set; + +/** Validates the canonical, tenant-free player-bootstrap JWT claim shape. */ +public final class PlayerBootstrapJwtProfileValidator { + public static final String PROFILE = "player-bootstrap"; + public static final String AUDIENCE = "player-bootstrap"; + public static final String TOKEN_TYPE = "player-bootstrap"; + private static final String ISSUER = "firemud-account-service"; + public static final Set REQUIRED_CLAIMS; + public static final Set OPTIONAL_CLAIMS = Set.of("globalRoles"); + + static { + Set required = + new java.util.HashSet<>(AccountJwtProfileClaimSupport.REQUIRED_BASE_CLAIMS); + required.add("scopedRoles"); + REQUIRED_CLAIMS = Set.copyOf(required); + } + + private PlayerBootstrapJwtProfileValidator() {} + + /** Checks profile shape only; it does not validate current membership or authorize a route. */ + public static void validateClaims(Map claims) { + AccountJwtProfileClaimSupport.requireClaimFields(claims, REQUIRED_CLAIMS, OPTIONAL_CLAIMS); + AccountJwtProfileClaimSupport.requireCommonIdentity(claims, ISSUER, AUDIENCE); + AccountJwtProfileClaimSupport.requireAuthorityTuple( + claims.get("authorityTuple"), false, true, false); + if (!AccountJwtProfileClaimSupport.requireVersionMap(claims.get("membershipVersion")).isEmpty() + || !AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles")).isEmpty()) { + throw AccountJwtProfileClaimSupport.invalid(); + } + if (claims.containsKey("globalRoles")) { + AccountJwtProfileClaimSupport.requireRoleList(claims.get("globalRoles")); + } + } +} diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java new file mode 100644 index 0000000000..b721526a86 --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/ControlUiJwtProfileValidatorTest.java @@ -0,0 +1,218 @@ +package net.firedevops.firemud.common.security; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class ControlUiJwtProfileValidatorTest { + private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111"; + private static final String TENANT_A = "22222222-2222-4222-8222-222222222222"; + private static final String TENANT_B = "33333333-3333-4333-8333-333333333333"; + + @Test + void acceptsSeparateTargetAndMembershipApplicabilityAndOptionalGlobalRoles() { + Map claims = baseClaims(); + claims.put( + "authorityTuple", authorityTuple(Map.of(TENANT_A, 2L), Map.of(TENANT_B, 3L), List.of())); + claims.put("membershipVersion", Map.of(TENANT_B, 8L)); + claims.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + claims.put("globalRoles", List.of()); + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void preservesProfileSpecificOptionalAccountCutoffOmission() { + Map claims = validClaims(); + Map tuple = object(claims.get("authorityTuple")); + tuple.put("accountAuthorityGeneration", 2L); + claims.put("authorityTuple", tuple); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void rejectsMismatchedMembershipPairMalformedScopeAndEmptyPresentOptionalObject() { + Map mismatch = validClaims(); + mismatch.put("membershipVersion", Map.of(TENANT_A, 8L)); + assertInvalid(mismatch); + + Map badScope = validClaims(); + badScope.put("scopedRoles", Map.of(ACCOUNT, List.of("tenantAdmin"))); + assertInvalid(badScope); + + Map emptyBillingObject = validClaims(); + Map tuple = object(emptyBillingObject.get("authorityTuple")); + tuple.put("tenantBillingCutoff", Map.of()); + emptyBillingObject.put("authorityTuple", tuple); + assertInvalid(emptyBillingObject); + + Map nullBillingObject = validClaims(); + tuple = object(nullBillingObject.get("authorityTuple")); + tuple.put("tenantBillingCutoff", null); + nullBillingObject.put("authorityTuple", tuple); + assertInvalid(nullBillingObject); + + Map malformedRole = validClaims(); + malformedRole.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin", "tenantAdmin"))); + assertInvalid(malformedRole); + assertInvalid(Map.of("unexpected", true)); + } + + @Test + void sharedConfiguredScopeCapBoundsEveryControlUiApplicabilityMap() { + Map tooManyScopedRoles = validClaims(); + tooManyScopedRoles.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyScopedRoles, 1); + + Map tooManyTenantGenerations = validClaims(); + Map tenantTuple = object(tooManyTenantGenerations.get("authorityTuple")); + tenantTuple.put("tenantAuthorityGeneration", Map.of(TENANT_A, 2L, TENANT_B, 3L)); + tooManyTenantGenerations.put("authorityTuple", tenantTuple); + tooManyTenantGenerations.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyTenantGenerations, 1); + + Map tooManyMembershipGenerations = validClaims(); + Map membershipTuple = + object(tooManyMembershipGenerations.get("authorityTuple")); + membershipTuple.put("membershipAuthorityGeneration", Map.of(TENANT_A, 2L, TENANT_B, 3L)); + tooManyMembershipGenerations.put("authorityTuple", membershipTuple); + tooManyMembershipGenerations.put("membershipVersion", Map.of(TENANT_A, 7L, TENANT_B, 8L)); + tooManyMembershipGenerations.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + assertInvalidAtCap(tooManyMembershipGenerations, 1); + + Map tooManyBillingCutoffs = validClaims(); + Map billingTuple = object(tooManyBillingCutoffs.get("authorityTuple")); + Map cutoff = + Map.of( + "tenantAuthorityGeneration", 2L, + "tenantBillingSequence", 3L, + "outboxStreamKey", "account:tenant-billing:v1:tenant/" + TENANT_A, + "outboxSequence", 4L); + billingTuple.put("tenantBillingCutoff", Map.of(TENANT_A, cutoff, TENANT_B, cutoff)); + tooManyBillingCutoffs.put("authorityTuple", billingTuple); + tooManyBillingCutoffs.put( + "scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"), TENANT_B, List.of("reader"))); + assertInvalidAtCap(tooManyBillingCutoffs, 1); + } + + @Test + void eachControlUiApplicabilityMapAcceptsTheExactConfiguredCap() { + Map claims = validClaims(); + Map tuple = object(claims.get("authorityTuple")); + tuple.put( + "tenantBillingCutoff", + Map.of( + TENANT_A, + Map.of( + "tenantAuthorityGeneration", + 2L, + "tenantBillingSequence", + 3L, + "outboxStreamKey", + "account:tenant-billing:v1:tenant/" + TENANT_A, + "outboxSequence", + 4L))); + claims.put("authorityTuple", tuple); + + assertThatCode(() -> ControlUiJwtProfileValidator.validateClaims(claims, 1)) + .doesNotThrowAnyException(); + } + + @Test + void nilAndAccountIdTenantKeysAreRejectedAsMalformedProfileKeys() { + Map nilAccount = validClaims(); + nilAccount.put("sub", "00000000-0000-0000-0000-000000000000"); + nilAccount.put("accountId", "00000000-0000-0000-0000-000000000000"); + assertInvalid(nilAccount); + + Map accountKey = validClaims(); + Map tuple = object(accountKey.get("authorityTuple")); + tuple.put("tenantAuthorityGeneration", Map.of(ACCOUNT, 2L)); + accountKey.put("authorityTuple", tuple); + accountKey.put("scopedRoles", Map.of(ACCOUNT, List.of("tenantAdmin"))); + assertInvalid(accountKey); + } + + @Test + void canonicalAuthorityTupleByteCeilingIsEnforcedAfterTheFiniteCountCap() { + Map tenantGenerations = new LinkedHashMap<>(); + Map> scopedRoles = new LinkedHashMap<>(); + for (int index = 0; index < 100; index++) { + String tenantId = UUID.randomUUID().toString(); + tenantGenerations.put(tenantId, 1L); + scopedRoles.put(tenantId, List.of("reader")); + } + Map claims = baseClaims(); + claims.put("authorityTuple", authorityTuple(tenantGenerations, Map.of(), List.of())); + claims.put("membershipVersion", Map.of()); + claims.put("scopedRoles", scopedRoles); + + assertInvalidAtCap(claims, 128); + } + + private static Map validClaims() { + Map claims = baseClaims(); + claims.put( + "authorityTuple", authorityTuple(Map.of(TENANT_A, 2L), Map.of(TENANT_B, 3L), List.of())); + claims.put("membershipVersion", Map.of(TENANT_B, 8L)); + claims.put("scopedRoles", Map.of(TENANT_A, List.of("tenantAdmin"))); + return claims; + } + + private static Map baseClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", ACCOUNT); + claims.put("accountId", ACCOUNT); + claims.put("jti", UUID.randomUUID().toString()); + claims.put("aud", ControlUiJwtProfileValidator.AUDIENCE); + claims.put("iat", 1L); + claims.put("nbf", 1L); + claims.put("exp", 300L); + claims.put("tokenGeneration", 1L); + claims.put("issuanceFence", 1L); + return claims; + } + + private static Map authorityTuple( + Map tenantGenerations, + Map membershipGenerations, + List privateGrants) { + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", 1L); + tuple.put("accountAuthorityGeneration", 1L); + tuple.put("tenantAuthorityGeneration", tenantGenerations); + tuple.put("membershipAuthorityGeneration", membershipGenerations); + tuple.put("privateRealmGrantVersions", privateGrants); + return tuple; + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return new LinkedHashMap<>((Map) value); + } + + private static void assertInvalid(Map claims) { + assertThatThrownBy(() -> ControlUiJwtProfileValidator.validateClaims(claims, 8)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } + + private static void assertInvalidAtCap(Map claims, int cap) { + assertThatThrownBy(() -> ControlUiJwtProfileValidator.validateClaims(claims, cap)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } +} diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java new file mode 100644 index 0000000000..075f9731d5 --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java @@ -0,0 +1,379 @@ +package unit.net.firedevops.firemud.common.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.EvidenceBundleReference; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.IssuanceBinding; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; + +class GameSessionAccountDelegationRegistryRecordTest { + private static final String ACCOUNT_ID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String JTI = "2921ba03-bf74-49ac-b24b-a9255f5de308"; + private static final String OPERATION_ID = "5414e55d-0393-4561-ac3d-cb916a08d3f0"; + private static final String REQUEST_ID = "1ee95a1e-83f2-4a63-a7ba-6288e246ac76"; + private static final long NOW = 1_800_000_000L; + private static final long MAX_RECORD_BYTES = 16_384L; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void boundRegistryRoundTripsEqualValuesInIndependentAccountAndTenantUuidDomains() + throws Exception { + var claims = new LinkedHashMap<>(claims()); + var tuple = new LinkedHashMap<>(authorityTuple(7L, 11L, 10L)); + tuple.put("tenantAuthorityGeneration", Map.of(ACCOUNT_ID, "5")); + tuple.put("membershipAuthorityGeneration", Map.of(ACCOUNT_ID, "7")); + claims.put("tenantId", ACCOUNT_ID); + claims.put("authorityTuple", tuple); + claims.put("membershipVersion", Map.of(ACCOUNT_ID, "3")); + String compact = compact(claims); + var bound = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedBoundCompactJwt( + compact, + "5", + binding(), + snapshot(), + bundleReference(), + ACCOUNT_ID, + tuple, + Map.of(ACCOUNT_ID, "3"), + NOW, + MAX_RECORD_BYTES); + var decoded = + GameSessionAccountDelegationRegistryRecord.decode( + bound.toCanonicalJsonBytes(MAX_RECORD_BYTES), MAX_RECORD_BYTES); + assertThat(decoded.fields()) + .containsEntry("accountId", ACCOUNT_ID) + .containsEntry("tenantId", ACCOUNT_ID); + assertThat(decoded.fields().get("membershipVersion")).isEqualTo(Map.of(ACCOUNT_ID, "3")); + assertThatThrownBy(() -> record(compact)) + .isInstanceOf(GameSessionAccountDelegationRegistryRecord.InvalidRecordException.class); + assertThatThrownBy( + () -> + GameSessionAccountDelegationRegistryRecord.fromAccountSignedBoundCompactJwt( + compact, + "5", + binding(), + snapshot(), + bundleReference(), + "22222222-2222-4222-8222-222222222222", + tuple, + Map.of(ACCOUNT_ID, "3"), + NOW, + MAX_RECORD_BYTES)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); + } + + @Test + void buildsStrictPendingRecordForTheMinimalCredentialLoginProfile() throws Exception { + String compact = compact(claims()); + GameSessionAccountDelegationRegistryRecord record = record(compact); + + assertThat(record.state()).isEqualTo("pending"); + assertThat(record.accountId()).isEqualTo(ACCOUNT_ID); + assertThat(record.jti()).isEqualTo(JTI); + assertThat(record.operationId()).isEqualTo(OPERATION_ID); + assertThat(record.requestId()).isEqualTo(REQUEST_ID); + assertThat(record.issuanceFence()).isEqualTo(11L); + assertThat(record.evidenceBundleReference()).isEqualTo(bundleReference()); + byte[] encoded = record.toCanonicalJsonBytes(MAX_RECORD_BYTES); + assertThat(new String(encoded, StandardCharsets.UTF_8)).doesNotContain(compact); + assertThat( + GameSessionAccountDelegationRegistryRecord.decode(encoded, MAX_RECORD_BYTES).fields()) + .containsEntry("state", "pending") + .containsEntry("tokenHash", sha256(compact)); + } + + @Test + void roundTripsSmallAndLargestOwnerLongAuthorityCountersAsDecimalStrings() throws Exception { + long large = Long.MAX_VALUE; + AccountAuthoritySnapshot largeSnapshot = + new AccountAuthoritySnapshot( + UUID.fromString(ACCOUNT_ID), + large, + large, + large, + large, + large, + large, + Optional.of(cutoff(large, large - 1L))); + Map largeClaims = new LinkedHashMap<>(claims()); + largeClaims.put("authorityTuple", authorityTuple(large, large, large - 1L)); + largeClaims.put("issuanceFence", Long.toString(large)); + String compact = compact(largeClaims); + GameSessionAccountDelegationRegistryRecord decoded = + GameSessionAccountDelegationRegistryRecord.decode( + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact, + "5", + binding(), + largeSnapshot, + bundleReference(), + NOW, + MAX_RECORD_BYTES) + .toCanonicalJsonBytes(MAX_RECORD_BYTES), + MAX_RECORD_BYTES); + + assertThat(decoded.issuanceFence()).isEqualTo(large); + Map authorityTuple = (Map) decoded.fields().get("authorityTuple"); + assertThat(decoded.fields().get("tokenGeneration")).isEqualTo("1"); + assertThat(decoded.fields().get("issuanceFence")).isEqualTo(Long.toString(large)); + assertThat(authorityTuple.get("issuerAuthGeneration")).isEqualTo(Long.toString(large)); + assertThat(authorityTuple.get("accountAuthorityGeneration")).isEqualTo(Long.toString(large)); + Map sourceVersions = (Map) decoded.fields().get("authoritySourceVersions"); + assertThat(sourceVersions.get("issuerSourceVersion")).isEqualTo(Long.toString(large)); + assertThat(sourceVersions.get("accountSourceVersion")).isEqualTo(Long.toString(large)); + assertThat(sourceVersions.get("issuanceFenceSourceVersion")).isEqualTo(Long.toString(large)); + assertThat(record(compact(claims())).issuanceFence()).isEqualTo(11L); + } + + @Test + void rejectsWrongAudienceTenantScopedOrExpandedClaimCandidates() throws Exception { + Map wrongAudience = new LinkedHashMap<>(claims()); + wrongAudience.put("aud", "social-groups-service"); + assertInvalid(wrongAudience); + + Map tenantScoped = new LinkedHashMap<>(claims()); + Map tuple = new LinkedHashMap<>(); + ((Map) tenantScoped.get("authorityTuple")) + .forEach((key, value) -> tuple.put((String) key, value)); + tuple.put("tenantAuthorityGeneration", Map.of("tenant", 1L)); + tenantScoped.put("authorityTuple", tuple); + assertInvalid(tenantScoped); + + Map expanded = new LinkedHashMap<>(claims()); + expanded.put("backendJWT", "forbidden"); + assertInvalid(expanded); + } + + @Test + void advancedAccountRequiresTheExactCurrentCutoffAndSequenceZeroOmitsIt() throws Exception { + Map missingCutoff = new LinkedHashMap<>(claims()); + Map missingCutoffTuple = new LinkedHashMap<>(); + ((Map) claims().get("authorityTuple")) + .forEach((key, value) -> missingCutoffTuple.put((String) key, value)); + missingCutoffTuple.remove("accountSecurityCutoff"); + missingCutoff.put("authorityTuple", missingCutoffTuple); + assertInvalid(missingCutoff); + + Map wrongCutoff = new LinkedHashMap<>(claims()); + Map wrongTuple = new LinkedHashMap<>(); + ((Map) wrongCutoff.get("authorityTuple")) + .forEach((key, value) -> wrongTuple.put((String) key, value)); + wrongTuple.put("accountSecurityCutoff", cutoff(11L, 9L).toMap()); + wrongCutoff.put("authorityTuple", wrongTuple); + assertInvalid(wrongCutoff); + + Map baseline = new LinkedHashMap<>(claims()); + baseline.put("authorityTuple", GameSessionAccountDelegationProfile.authorityTuple(1L, 1L)); + baseline.put("issuanceFence", "1"); + GameSessionAccountDelegationRegistryRecord baselineRecord = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact(baseline), + "5", + binding(), + baselineSnapshot(), + bundleReference(), + NOW, + MAX_RECORD_BYTES); + assertThat( + ((Map) baselineRecord.fields().get("authorityTuple")) + .containsKey("accountSecurityCutoff")) + .isFalse(); + + Map fabricatedBaseline = new LinkedHashMap<>(baseline); + Map fabricatedTuple = new LinkedHashMap<>(); + ((Map) baseline.get("authorityTuple")) + .forEach((key, value) -> fabricatedTuple.put((String) key, value)); + fabricatedTuple.put("accountSecurityCutoff", cutoff(1L, 1L).toMap()); + fabricatedBaseline.put("authorityTuple", fabricatedTuple); + assertThatThrownBy( + () -> + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact(fabricatedBaseline), + "5", + binding(), + baselineSnapshot(), + bundleReference(), + NOW, + MAX_RECORD_BYTES)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void enforcesShortLifetimeCanonicalJwtAndExactRequestIdentity() throws Exception { + Map tooLong = new LinkedHashMap<>(claims()); + tooLong.put("exp", NOW + 301L); + assertInvalid(tooLong); + + String compact = compact(claims()); + assertThatThrownBy( + () -> + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact + "=", + "5", + binding(), + snapshot(), + bundleReference(), + NOW, + MAX_RECORD_BYTES)) + .isInstanceOf(IllegalArgumentException.class); + + GameSessionAccountDelegationRegistryRecord record = record(compact); + byte[] bytes = record.toCanonicalJsonBytes(MAX_RECORD_BYTES); + String nonCanonical = "{ \"state\": \"pending\" }"; + assertThatThrownBy( + () -> + GameSessionAccountDelegationRegistryRecord.decode( + nonCanonical.getBytes(StandardCharsets.UTF_8), MAX_RECORD_BYTES)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(bytes).isNotEmpty(); + } + + @Test + void requiresDecimalCountersAndCompleteFiveFieldBundleReference() throws Exception { + Map numericGeneration = new LinkedHashMap<>(claims()); + numericGeneration.put("tokenGeneration", 1L); + assertInvalid(numericGeneration); + + Map numericFence = new LinkedHashMap<>(claims()); + numericFence.put("issuanceFence", 11L); + assertInvalid(numericFence); + + Map numericAuthority = new LinkedHashMap<>(claims()); + Map tuple = new LinkedHashMap<>(); + ((Map) numericAuthority.get("authorityTuple")) + .forEach((key, value) -> tuple.put((String) key, value)); + tuple.put("issuerAuthGeneration", 7L); + numericAuthority.put("authorityTuple", tuple); + assertInvalid(numericAuthority); + + Map leadingZeroGeneration = new LinkedHashMap<>(claims()); + Map leadingZeroTuple = new LinkedHashMap<>(); + ((Map) leadingZeroGeneration.get("authorityTuple")) + .forEach((key, value) -> leadingZeroTuple.put((String) key, value)); + leadingZeroTuple.put("accountAuthorityGeneration", "011"); + leadingZeroGeneration.put("authorityTuple", leadingZeroTuple); + assertInvalid(leadingZeroGeneration); + + Map overflowFence = new LinkedHashMap<>(claims()); + overflowFence.put("issuanceFence", "9223372036854775808"); + assertInvalid(overflowFence); + + GameSessionAccountDelegationRegistryRecord record = record(compact(claims())); + Map reference = (Map) record.fields().get("authEvidenceBundle"); + assertThat(reference.keySet()) + .isEqualTo( + Set.of( + "bundleVersion", + "sourceVersion", + "sourceFence", + "linearization", + "canonicalSha256")); + assertThat(reference.get("sourceFence")).isEqualTo("9"); + + Map incompleteFields = new LinkedHashMap<>(record.fields()); + Map incompleteReference = new LinkedHashMap<>(); + reference.forEach((key, value) -> incompleteReference.put((String) key, value)); + incompleteReference.remove("sourceFence"); + incompleteFields.put("authEvidenceBundle", incompleteReference); + byte[] incompleteBytes = + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(incompleteFields)); + assertThatThrownBy( + () -> + GameSessionAccountDelegationRegistryRecord.decode( + incompleteBytes, MAX_RECORD_BYTES)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static void assertInvalid(Map claims) throws Exception { + assertThatThrownBy(() -> record(compact(claims))).isInstanceOf(IllegalArgumentException.class); + } + + private static GameSessionAccountDelegationRegistryRecord record(String compact) { + return GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact, "5", binding(), snapshot(), bundleReference(), NOW, MAX_RECORD_BYTES); + } + + private static Map claims() { + return Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("sub", ACCOUNT_ID), + Map.entry("accountId", ACCOUNT_ID), + Map.entry("jti", JTI), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("iat", NOW), + Map.entry("nbf", NOW), + Map.entry("exp", NOW + 120L), + Map.entry("tokenGeneration", "1"), + Map.entry("authorityTuple", authorityTuple(7L, 11L, 10L)), + Map.entry("membershipVersion", Map.of()), + Map.entry("issuanceFence", "11")); + } + + private static String compact(Map claims) throws Exception { + String header = + JSON.writeValueAsString(Map.of("alg", "RS256", "kid", "test-key", "typ", "JWT")); + String payload = JSON.writeValueAsString(claims); + Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); + return encoder.encodeToString(header.getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString("signature-bytes".getBytes(StandardCharsets.UTF_8)); + } + + private static IssuanceBinding binding() { + return new IssuanceBinding(OPERATION_ID, REQUEST_ID, "a".repeat(64), ACCOUNT_ID); + } + + private static EvidenceBundleReference bundleReference() { + return new EvidenceBundleReference("1", "11", "9", "3", "d".repeat(64)); + } + + private static AccountAuthoritySnapshot snapshot() { + return new AccountAuthoritySnapshot( + UUID.fromString(ACCOUNT_ID), 7L, 7L, 11L, 11L, 11L, 11L, Optional.of(cutoff(11L, 10L))); + } + + private static AccountAuthoritySnapshot baselineSnapshot() { + return new AccountAuthoritySnapshot( + UUID.fromString(ACCOUNT_ID), 1L, 1L, 1L, 1L, 1L, 1L, Optional.empty()); + } + + private static Map authorityTuple( + long issuerGeneration, long accountGeneration, long cutoffSequence) { + return GameSessionAccountDelegationProfile.authorityTuple( + issuerGeneration, + accountGeneration, + Optional.of(cutoff(accountGeneration, cutoffSequence))); + } + + private static AccountSecurityCutoff cutoff(long generation, long sequence) { + return new AccountSecurityCutoff( + Long.toString(generation), + "account:auth-authority:v1:account/" + ACCOUNT_ID, + Long.toString(sequence)); + } + + private static String sha256(String value) throws Exception { + return java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(value.getBytes(StandardCharsets.US_ASCII))); + } +} diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidatorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidatorTest.java new file mode 100644 index 0000000000..b3fa5371db --- /dev/null +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/PlayerBootstrapJwtProfileValidatorTest.java @@ -0,0 +1,93 @@ +package net.firedevops.firemud.common.security; + +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class PlayerBootstrapJwtProfileValidatorTest { + private static final String ACCOUNT = "11111111-1111-4111-8111-111111111111"; + + @Test + void requiresDeclaredEmptyTenantAndRoleShapesButAllowsOptionalGlobalRoles() { + Map claims = validClaims(); + + assertThatCode(() -> PlayerBootstrapJwtProfileValidator.validateClaims(claims)) + .doesNotThrowAnyException(); + claims.put("globalRoles", List.of()); + assertThatCode(() -> PlayerBootstrapJwtProfileValidator.validateClaims(claims)) + .doesNotThrowAnyException(); + } + + @Test + void rejectsAnyTenantScopeBillingCutoffOrPrivateGrant() { + Map scoped = validClaims(); + scoped.put("scopedRoles", Map.of("22222222-2222-4222-8222-222222222222", List.of("reader"))); + assertInvalid(scoped); + + Map billing = validClaims(); + Map tuple = object(billing.get("authorityTuple")); + String tenant = "22222222-2222-4222-8222-222222222222"; + tuple.put( + "tenantBillingCutoff", + Map.of( + tenant, + Map.of( + "tenantAuthorityGeneration", + 2L, + "tenantBillingSequence", + 3L, + "outboxStreamKey", + "account:tenant-billing:v1:tenant/" + tenant, + "outboxSequence", + 4L))); + billing.put("authorityTuple", tuple); + assertInvalid(billing); + + Map grants = validClaims(); + tuple = object(grants.get("authorityTuple")); + tuple.put("privateRealmGrantVersions", List.of(Map.of("tenantId", "bad"))); + grants.put("authorityTuple", tuple); + assertInvalid(grants); + } + + private static Map validClaims() { + Map claims = new LinkedHashMap<>(); + claims.put("iss", "firemud-account-service"); + claims.put("sub", ACCOUNT); + claims.put("accountId", ACCOUNT); + claims.put("jti", UUID.randomUUID().toString()); + claims.put("aud", PlayerBootstrapJwtProfileValidator.AUDIENCE); + claims.put("iat", 1L); + claims.put("nbf", 1L); + claims.put("exp", 300L); + claims.put("tokenGeneration", 1L); + claims.put("issuanceFence", 1L); + claims.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 1L, + "tenantAuthorityGeneration", Map.of(), + "membershipAuthorityGeneration", Map.of(), + "privateRealmGrantVersions", List.of())); + claims.put("membershipVersion", Map.of()); + claims.put("scopedRoles", Map.of()); + return claims; + } + + @SuppressWarnings("unchecked") + private static Map object(Object value) { + return new LinkedHashMap<>((Map) value); + } + + private static void assertInvalid(Map claims) { + assertThatThrownBy(() -> PlayerBootstrapJwtProfileValidator.validateClaims(claims)) + .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class) + .hasNoCause(); + } +}