From 236485e3c0b14a415b645294bbd84996b064862c Mon Sep 17 00:00:00 2001
From: Ben Hook <5009589+benhook1013@users.noreply.github.com>
Date: Sun, 11 Oct 2026 02:18:45 +1300
Subject: [PATCH 01/21] Add inactive Account owner source cut
---
.../account-service/api-contracts.md | 6 +-
.../account-service/configuration.md | 2 +
.../account-service/runtime-and-data.md | 2 +
.../player-access-and-session.md | 4 +
.../v1/jwt_signer_materialization.proto | 206 +++
services/account-service/build.gradle.kts | 26 +
...StartSessionReservationEvidenceClient.java | 205 +++
...ountJwtSignerMaterializerTrustBinding.java | 404 +++++
...ionOperatorAuthorizationConfiguration.java | 132 ++
...tControlUiCommittedIssuanceRepository.java | 280 ++++
...essionOperatorAuthorizationRepository.java | 803 ++++++++++
...ntJwtSignerMaterializerTlsInterceptor.java | 73 +
...ccountJwtSignerMaterializationService.java | 739 ++++++++++
.../service/impl/AccountServiceImpl.java | 41 +
...ssionOperatorAuthorizationGrpcService.java | 601 ++++++++
.../session/AccountControlUiActorService.java | 370 +++++
.../session/AccountControlUiCoordination.java | 267 ++++
.../AccountControlUiCurrentActorVerifier.java | 848 +++++++++++
.../AccountControlUiIssuanceRepository.java | 589 ++++++++
.../AccountControlUiIssuanceService.java | 422 ++++++
.../session/AccountControlUiKeyring.java | 47 +
.../AccountControlUiRegistryContract.java | 45 +
.../AccountControlUiRegistryReader.java | 212 +++
.../AccountControlUiResponseCryptography.java | 76 +
.../session/AccountControlUiSignerOwner.java | 201 +++
...tCoordinationPinnedConnectionProvider.java | 28 +
.../AccountJwtJwksConfigMapClient.java | 704 +++++++++
.../AccountJwtJwksPrepublicationService.java | 935 ++++++++++++
.../session/AccountJwtJwksTrustedSource.java | 761 ++++++++++
.../AccountJwtReadinessProbeService.java | 554 +++++++
.../AccountJwtSignerBootstrapCoordinator.java | 1122 ++++++++++++++
...eratorAuthorizationFingerprintKeyring.java | 221 +++
...atorAuthorizationReferenceFingerprint.java | 102 ++
.../AccountResponseEnvelopeCryptography.java | 403 +++++
.../AccountResponseEnvelopeKeyring.java | 291 ++++
...ntStartSessionOperatorAuthorityBundle.java | 501 +++++++
...rtSessionOperatorAuthorizationService.java | 1296 +++++++++++++++++
...tCoordinationPinnedConnectionProvider.java | 58 +
.../src/main/resources/application-prod.yml | 4 +
.../src/main/resources/application.yml | 6 +
...__start_session_operator_authorization.sql | 142 ++
.../lua/account-control-ui-registry-cas.lua | 52 +
...lUiSourceGuardPostgresIntegrationTest.java | 353 +++++
...ttedIssuanceRepositoryIntegrationTest.java | 595 ++++++++
...uthorizationRepositoryIntegrationTest.java | 698 +++++++++
...trolUiIssuancePostgresIntegrationTest.java | 398 +++++
...iOwnerWorkflowPostgresIntegrationTest.java | 180 +++
...iPositiveOwnerPostgresIntegrationTest.java | 1152 +++++++++++++++
...AuthenticationPostgresIntegrationTest.java | 394 +++++
...ControlUiRegistryRedisIntegrationTest.java | 428 ++++++
...tSessionReservationEvidenceClientTest.java | 478 ++++++
.../AccountJwtJwksApiTransportTest.java | 785 ++++++++++
...peratorAuthorizationConfigurationTest.java | 249 ++++
.../repository/AccountRepositoryTest.java | 103 ++
...onOperatorAuthorizationRepositoryTest.java | 753 ++++++++++
...timeAccountIdentityGrpcAuthWiringTest.java | 14 +
...nOperatorAuthorizationGrpcServiceTest.java | 556 +++++++
.../AccountControlUiCoordinationTest.java | 256 ++++
...ountControlUiCurrentActorVerifierTest.java | 895 ++++++++++++
.../AccountControlUiIssuanceWorkflowTest.java | 556 +++++++
...untControlUiPrimaryAuthenticationTest.java | 151 ++
.../AccountControlUiRegistryReaderTest.java | 160 ++
...ountControlUiResponseCryptographyTest.java | 102 ++
.../AccountControlUiSigningAndActorTest.java | 469 ++++++
.../AccountJwtJwksConfigMapClientTest.java | 596 ++++++++
.../AccountJwtJwksTrustedSourceTest.java | 673 +++++++++
.../AccountJwtReadinessProbeServiceTest.java | 274 ++++
...orAuthorizationFingerprintKeyringTest.java | 173 +++
...AuthorizationReferenceFingerprintTest.java | 119 ++
...countResponseEnvelopeCryptographyTest.java | 212 +++
.../AccountResponseEnvelopeKeyringTest.java | 136 ++
...artSessionOperatorAuthorityBundleTest.java | 311 ++++
...ssionOperatorAuthorizationServiceTest.java | 787 ++++++++++
...rdinationPinnedConnectionProviderTest.java | 75 +
.../AccountControlUiOwnerSourcesFixture.java | 534 +++++++
.../AccountControlUiSignerFixture.java | 791 ++++++++++
.../common-redis-contracts/build.gradle.kts | 9 +
.../redis/contracts/RedisScriptCatalog.java | 80 +
.../contracts/RedisScriptContribution.java | 11 +
.../contracts/RedisScriptDescriptor.java | 264 ++++
.../contracts/RedisScriptCatalogTest.java | 143 ++
.../contracts/RedisScriptDescriptorTest.java | 151 ++
82 files changed, 28843 insertions(+), 2 deletions(-)
create mode 100644 protos/account/v1/jwt_signer_materialization.proto
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java
create mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProvider.java
create mode 100644 services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql
create mode 100644 services/account-service/src/main/resources/redis/lua/account-control-ui-registry-cas.lua
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerWorkflowPostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java
create mode 100644 services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryRedisIntegrationTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptographyTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeServiceTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprintTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java
create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java
create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java
create mode 100644 services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java
create mode 100644 services/common-redis-contracts/build.gradle.kts
create mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalog.java
create mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptContribution.java
create mode 100644 services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java
create mode 100644 services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java
create mode 100644 services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java
diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md
index 3980a1dadd..9f0fc81cb8 100644
--- a/design/architecture/microservices/account-service/api-contracts.md
+++ b/design/architecture/microservices/account-service/api-contracts.md
@@ -157,7 +157,7 @@ The handler returns `PERMISSION_DENIED` for a caller that is not the exact verif
### Operator Authorization References
-`IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, and the immutable `authorityEvidenceBundle/v1`; Account never exposes that evidence through an external route, logs, audit text, or client-visible response.
+`IssueHumanOperatorAuthorizationReferenceRequest` contains the forwarded `control-ui` evidence, target owner service, typed target scope, action family, action-family schema identifier/version, the applicable mutation identity, correlation-only `controlPlaneRequestId`, and canonical digest. Its branch selector is `action_category_or_absence`: published moderation schemas must validate a closed `action_category` before branch selection, while published non-moderation schemas must explicitly omit `action_category` and select `non_moderation`; omission cannot downgrade a moderation family. For moderation action families, the typed request carries exactly one dedicated identity: `policyIntentRequestId` with the local policy-intent digest, or `ownerEnforcementRequestId` with the owner-enforcement digest. Neither dedicated identity may be omitted, replaced, or aliased by `controlPlaneRequestId`; the separate appeal-submission identity is not carried by operator issuance. For non-moderation families, the typed mutation identity remains `controlPlaneRequestId` with `mutationDigest/v1`. The typed scope is branch-specific: `non_moderation` and `tenant_restriction` require `tenant_scope`, while `platform_access_ban` requires explicit `target_account_id` and has no tenant scope or membership fields. Actor identity is not a request field: Account derives it from the validated token forwarded by the exact Logging & Admin mTLS workload. Account chooses a short expiry, stores a keyed hash for lookup, and retains the original high-entropy opaque reference only in protected encrypted authority storage or a bounded encrypted response envelope for the reference lifetime plus the documented retry and read-only recovery window. The exact authenticated internal response contains `operatorAuthorizationReference`, Account-calculated `authorizationReferenceFingerprint`, `expiresAt`, the immutable `authorityEvidenceBundle/v1`, and `authenticatedLoggingWorkloadIdentity`, which is copied from the verified same-namespace Logging/Admin TLS peer after successful issue or recovery; Logging checks the returned identity against the action target namespace before accepting the response. Account never exposes that evidence through an external route, logs, audit text, or client-visible response.
`IssueAutomationOperatorAuthorizationReferenceRequest` contains no workload identity field: Account derives `workloadIdentity` from the authenticated mTLS transport peer and rejects any serialized or caller-supplied substitute. It contains `automation_policy_id`, `automation_policy_version`, target owner service, typed target scope, action family, action-family schema identifier/version, `controlPlaneRequestId`, and canonical `mutationDigest`, with no account, end-user token, or human identity. The target request is `non_moderation`-only: published schema pairs must select the branch with `action_category` absent, moderation schema pairs are rejected before issuance, and no concrete schema pairs are published while the route remains target-not-routable. For the supported tenant-scoped branch, Account binds the exact `tenant_generation`; global-role or `privileged_control` authority is rejected rather than inferred. The exact authenticated internal response has the same opaque reference, fingerprint, expiry, and immutable authority-evidence shape; its stored binding includes the authenticated workload and policy evidence plus the applicable generation predicate. `controlPlaneRequestId` and `mutationDigest/v1` cannot be reused for moderation; any future moderation automation contract must declare dedicated request identity, digest, and idempotency semantics with `controlPlaneRequestId` correlation-only.
Both issuance requests are typed by the published action-family schema pair and contain the target owner, typed scope, action family, typed target, typed expected version, typed mutation, typed audit reason, the applicable mutation identity, correlation-only `controlPlaneRequestId`, canonical digest, the exact authenticated workload binding, the validated actor or automation-policy input, `reservationOwnerId`, and positive `reservationClaimFence`, including every schema-declared bound presence/absence value. `preAuthorizationReservationTuple` is limited to those request, target, mutation, identity, digest, and reservation-claim inputs; it explicitly excludes `issuanceKind`, `authorityTuple`, `membershipVersion`, and `issuanceFence`. For non-moderation families, the mutation identity is `controlPlaneRequestId`; for moderation, the tuple contains exactly `policyIntentRequestId` or `ownerEnforcementRequestId` according to the action-family contract, while `controlPlaneRequestId` remains correlation-only. The appeal-submission identity is not added to this operator tuple. Human actor identity is not a request assertion: Account derives it from the validated `control-ui` evidence forwarded by the exact Logging & Admin mTLS workload. Automation carries no user identity and is authorized only by the exact workload plus versioned automation policy. Account rejects malformed, unsupported, over-limit, missing, aliased, or digest-mismatched identity input before authorization issuance. Account derives `issuanceKind`, the complete applicable `authorityTuple`, independent applicable `membershipVersion`, and positive `issuanceFence` after authorization issuance as post-issuance enrichment. If a transport carries copies of those fields, they are non-authoritative echoes and are excluded from `preAuthorizationReservationTuple` and its digest; Account verifies the current reservation owner and claim fence before issuing. The human and automation requests therefore share the typed pre-authorization tuple while retaining distinct actor-versus-policy authority paths.
@@ -177,7 +177,9 @@ Account-authenticated or reference-derived fields are not request authority asse
Error precedence is canonical: (1) Account authenticates the exact immediate mTLS caller as an allowed owner/redeemer workload; an unauthenticated or disallowed workload fails at the authentication/transport boundary with the canonical non-OK status and bounded details selected by the shared classifier, before opaque-reference lookup or disclosure; (2) for an authenticated caller, missing or malformed applicable mutation identity, correlation-only `controlPlaneRequestId` when required by the transport, or `reservationClaimFence` is a request-validation failure at that boundary and uses canonical non-OK status with bounded details before durable lookup; (3) a malformed, undecodable, unsupported, or wrong-kind opaque reference is likewise a request-validation/shape failure using canonical non-OK status with bounded details, while a recognized reference whose stored redeemer/workload binding differs returns the typed `OPERATOR_AUTH_REFERENCE_CALLER_MISMATCH` before tuple or evidence disclosure; (4) only after the request is authenticated and validated, the reference is recognized, and the caller binding matches, the applicable mutation identity that identifies a durable record but carries any changed complete-tuple field returns the typed `IDEMPOTENCY_CONFLICT`; for moderation, this is the dedicated `policyIntentRequestId` or `ownerEnforcementRequestId`, never correlation-only `controlPlaneRequestId`; (5) only for an otherwise exact tuple with a supplied syntactically valid `reservationClaimFence` whose durable claim is stale, missing, lower, reused, or no longer held does Account redemption return the typed `FENCE_REJECTED`. Account redemption does not use `FENCE_REJECTED` for a domain-owner or gameplay fence. A domain owner may use the shared wire code only as phase-qualified `OWNER_EXECUTION/FENCE_REJECTED` after atomically persisting no-accept/no-commit proof, and the response must distinguish its owner-execution phase and proof evidence; absent or inconsistent proof leaves `OWNER_EXECUTION/OWNER_EXECUTION_PENDING`, non-replayable and non-rearmable. Expiry returns the typed `OPERATOR_AUTH_REFERENCE_EXPIRED`, explicit revocation returns the typed `OPERATOR_AUTH_REFERENCE_REVOKED`, and changed current authority returns the typed `OPERATOR_AUTH_REFERENCE_AUTHORITY_STALE` when none of the higher-precedence conditions applies. These listed codes and precedence rules are Account-owned expected redemption outcomes only once an authenticated, validated request reaches Account's redemption decision boundary. Current handlers represent them with response-level `ErrorDetail`; the target response channel follows the [gRPC outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification), using a typed domain result when Account produces the declared redemption outcome and canonical non-OK status with bounded details when it cannot produce that result. This paragraph does not assign individual per-RPC mappings or exact gRPC status codes; the shared classifier owns that mapping. Transport uncertainty remains ambiguous: callers retry the same applicable mutation identity and tuple or use read-only recovery with the same identity, correlation, and claim fence, and never mint a replacement identity for the same mutation attempt. A pre-success same-tuple redemption retry may replay the durable redemption result; successful redemption consumes the reference, and the consumed reference cannot authorize a new owner attempt or owner rearm. Owner rearm after a terminal result requires a new explicit operator request, fresh Account authorization, and a new opaque reference. Raw references must not appear in logs, audit records, or mutation digests. Logging & Admin may retain durable intent and the Account-returned fingerprint, and may hold the opaque reference only as protected, bounded in-flight material while the current delivery or redemption attempt is active; it must not retain a second recovery envelope or competing authority record. The owner redeems the exact reference and does not persist it as an authority source.
-These RPCs and schemas are accepted target state but are not present in the current Account proto or implementation. Logging & Admin remains the external operator ingress and durable intent/audit coordinator, Account remains the authorization authority and owner of original-reference retention, and the domain service remains the mutation owner.
+The broader action-family RPC and schema set remains accepted target state and is not fully present in the current Account proto or implementation. StartSession Account ISSUE/RECOVER/REDEEM and the read-only original redeemed-operation projection are present at source level; source-level Logging & Admin durable handoff and Game Session claim/redemption/prepared-action slices are tracked in the [StartSession action-schema implementation status](../game-session-service/start-session-action-schema.md#implementation-status). Account's receiving adapter and owner service are composed only by the explicit `firemud.account.start-session-operator-authorization` configuration, disabled by default; enabling requires existing owner collaborators, explicit bounded timings, a workload namespace, an owner-supplied fingerprint-key source, and a distinct operator response-envelope mount. The positive owner fixture now constructs the service through this configuration and exercises the receiving methods, but its PostgreSQL proof is compile-only and the test context is not full-service boot or production key custody. The production hosted-terms environment producer plus pinned trusted-provider/key-custody composition remain absent. The Game Design prepared selector/current-Account-projection consumer and full physical cross-service smoke remain unproved. Logging & Admin remains the external operator ingress and durable intent/audit coordinator, Account remains the authorization authority and owner of original-reference retention, and the domain service remains the mutation owner.
+
+For the redeemed StartSession projection, `ReadRedeemedOperationProjection` accepts the exact canonical pre-authorization tuple bytes, Account-issued authorization-reference fingerprint, original reservation owner and claim fence, and actual Game Session owner-attempt ID and fence. Account authenticates the exact same-namespace Game Design workload over mTLS before parsing or lookup. Its read-only result returns the original request ID, tuple, digest, fingerprint, reservation and owner-attempt bindings, recorded redeemer workload identity, reference expiry and redemption time, issuance operation and fence, bundle reference, and unchanged authority-evidence bundle; it returns neither the forwarded `control-ui` token nor the opaque authorization reference. The normative applicability and authority boundary are owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md#redeemed-startsession-projection-read).
## REST APIs
diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md
index cfeb4f6035..53331105b6 100644
--- a/design/architecture/microservices/account-service/configuration.md
+++ b/design/architecture/microservices/account-service/configuration.md
@@ -26,6 +26,8 @@ The configurable cleanup margin controls issued-token registry retention only. G
The current runtime still uses the shared-HMAC compatibility profile for issuance and validation and has no asymmetric non-exportable signer delegation. Any Secret-backed asymmetric materialization is the explicit interim fallback/drift, not canonical target custody; the current preflight/manifests still treat signing paths and `jwt-signing-keys` mounts as shared workload configuration rather than enforcing Account as the sole private-material consumer, and the classpath fallback remains permitted when the configured JWKS file is absent. The runtime also retains the legacy creator-share percentage setting and provider-mutating code paths; they are unsupported implementation drift, not an accepted fee policy or product capability. These target-state requirements are not proof of current startup, custody, mount enforcement, or creator-commerce disablement; runtime, preflight, and manifest alignment is outside this documentation slice.
+The StartSession operator-authorization receiver and owner service use the explicit `firemud.account.start-session-operator-authorization` composition, disabled by default (`enabled=false`). Enabling it requires the existing Account actor/issuance/hosted-terms and transaction owners, reservation-evidence client, an explicit `OwnerKeySource`, bounded reference/recovery/retention durations, the workload namespace, and a separate absolute operator response-envelope keyring mount. The operator keyring is not the generic Account response-envelope mount. Missing inputs prevent composition; this does not create an external operator ingress or enable gameplay launch/activation. The production hosted-terms environment producer and trusted-provider/key-custody inputs remain absent.
+
## Service-Specific Variables
Additional variables configure outbound email delivery and payment behavior:
diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md
index f7589b6c55..8b290c238c 100644
--- a/design/architecture/microservices/account-service/runtime-and-data.md
+++ b/design/architecture/microservices/account-service/runtime-and-data.md
@@ -14,6 +14,8 @@ Proof qualification: the earlier `7a665c83e81f5cec85fcd7ec9a205c291bc0eba2` run
Account V99–V125 adds passive owner-storage foundations for signer desired state, mounted-material readback evidence, Account-owned JWKS publication, readiness/promotion receipts, and validator-inventory snapshots, together with strict bindings, typed evidence carriers, and focused repository/profile proof sources. The mounted-bundle signing and readiness-owner code in this source preparation is not registered to an RPC, coordinator, scheduler, or runtime consumer; promotion execution, receiver invocation, startup readiness, and validator currentness enforcement remain inactive. These storage and source-proof additions do not establish a runtime issuer/readiness path or close `PLAY`, admission, or activation. The canonical token and signer contract remains [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md); this document records only Account-local implementation consequences.
+The current Account owner-source preparation adds V126 storage, default-inactive StartSession operator authorization composition, Control-UI issuance and Redis coordination sources, Account-owned JWKS and signer-materialization adapters, and readiness-probe sources. StartSession composition defaults off; materializer trust defaults off, and missing trust or bootstrap composition denies its RPC operations. No runtime issuer, promotion coordinator, or consumer coordinator is registered. This source cut does not establish genuine PostgreSQL or mTLS proof, the complete Logging & Admin/Game Session/World flow, player-facing JWT readiness, or activation. Detailed current status and proof limits remain in the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-operation-and-signer-source-preparation); JWT and signer behavior remains canonical in [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md).
+
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.
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 d0889419c9..4524ea7568 100644
--- a/design/project-management/implementation-tracking/player-access-and-session.md
+++ b/design/project-management/implementation-tracking/player-access-and-session.md
@@ -14,6 +14,10 @@ Account V99–V125 and the associated owner repositories, typed evidence carrier
The added `AccountDraftSourceCompositionService`, `AccountControlUiAuthority`, and `AccountControlUiSigningSpec` remain unregistered and transaction-bound source preparation. They do not issue a JWT, authorize receiver execution, or establish runtime currentness/readiness.
+### Account operation and signer source preparation
+
+The current Account cut adds V126 operator-authorization storage, default-inactive StartSession authorization sources, Control-UI issuance and Redis coordination, Account-owned JWKS and signer-materialization adapters, and readiness-probe sources. StartSession composition is disabled by default; materializer trust is disabled by default, and absent trust or bootstrap composition denies the materializer RPC operations. No runtime issuer, signer-promotion coordinator, or consumer coordinator is registered. Independent Account build integration is incomplete: [root Gradle settings](../../../settings.gradle.kts) does not include the new `:common-redis-contracts` project declared by the [Account build](../../../services/account-service/build.gradle.kts). That build also declares `:logging-admin-service` and its test fixtures on Account test classpaths. The Account-owned [reservation-evidence client](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java) uses the existing Logging & Admin proto contract; completing the flow also depends on the out-of-cut Logging & Admin authorization coordinator/client and Game Session redemption composition. Genuine PostgreSQL and mTLS execution, the complete Logging & Admin/Game Session/World flow, player-facing JWT readiness, and activation remain unproved. The V99–V125 passive storage status above remains in force. Canonical JWT and signer behavior remains in [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md), with Account-local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status).
+
### Restricted original-claim evidence continuation preparation
This inactive owner continuation may read or replay the exact immutable association pin and create at most one immutable descriptor evidence pin under that same association and original `PENDING` claim, attempt, and fence. Authenticated Account and Game Design reads occur outside SQL; owner and association state is locked and rechecked before descriptor pinning. Initial association creation also requires the exact original Account authorization reference to remain unexpired at the PostgreSQL write, independently of the owner-claim lease. Existing association replay and historical reads retain their reconciliation semantics; this preparation does not renew or reissue authorization or create a replacement claim. Its classes remain unregistered; added proto/schema support does not activate a runtime route or grant mutation authorization or player admission. Descriptor evidence does not complete canonical launch, initial World-backed admission, or historical owner reconciliation. The canonical boundary is [Game Session restricted original-claim evidence continuation](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation) and [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md).
diff --git a/protos/account/v1/jwt_signer_materialization.proto b/protos/account/v1/jwt_signer_materialization.proto
new file mode 100644
index 0000000000..12d647a48a
--- /dev/null
+++ b/protos/account/v1/jwt_signer_materialization.proto
@@ -0,0 +1,206 @@
+syntax = "proto3";
+
+package account.v1;
+
+option java_package = "net.firedevops.firemud.account.v1";
+option java_multiple_files = true;
+
+// This exact authenticated peer performs only fixed-name Secret observation, pending-slot key
+// generation, and an operation-bound private-slot transition after Account durably authorizes a
+// PREPARED promotion. Account alone prepares/commits/promotes the lifecycle and publishes JWKS.
+service AccountJwtSignerMaterializationService {
+ rpc EnrollBootstrap(EnrollBootstrapRequest) returns (EnrollBootstrapResponse);
+ rpc GetCurrentGenerationRequest(GetCurrentGenerationRequestRequest)
+ returns (GetCurrentGenerationRequestResponse);
+ rpc RecordSecretObservation(RecordSecretObservationRequest)
+ returns (GetCurrentGenerationRequestResponse);
+ rpc RecordGenerationResult(RecordGenerationResultRequest)
+ returns (RecordGenerationResultResponse);
+ rpc GetCurrentPromotionRequest(GetCurrentPromotionRequestRequest)
+ returns (GetCurrentPromotionRequestResponse);
+ rpc RecordPrivatePromotionResult(RecordPrivatePromotionResultRequest)
+ returns (RecordPrivatePromotionResultResponse);
+}
+
+// Selector-free, authenticated bootstrap enrollment. The acknowledgment contains only pinned
+// identities and the fixed public ConfigMap observation; it carries no private material or
+// lifecycle selection authority.
+message EnrollBootstrapRequest {
+ int32 schema_version = 1;
+}
+
+message EnrollBootstrapResponse {
+ int32 schema_version = 1;
+ string environment_id = 2;
+ string cluster_id = 3;
+ string namespace = 4;
+ string expected_cluster_incarnation_uid = 5;
+ string expected_namespace_uid = 6;
+ string materializer_trust_binding_digest = 7;
+ string materializer_trust_config_revision = 8;
+ string api_binding_digest = 9;
+ string api_config_revision = 10;
+ string api_server_url = 11;
+ string api_tls_server_name = 12;
+ string api_serving_ca_sha256 = 13;
+ string api_expected_username = 14;
+ string private_secret_name = 15;
+ string public_config_map_name = 16;
+ string public_config_map_uid = 17;
+ string public_config_map_resource_version = 18;
+ string public_config_map_snapshot_digest = 19;
+}
+
+message ActiveSigner {
+ string generation = 1;
+ string kid = 2;
+}
+
+message GetCurrentGenerationRequestRequest {
+ int32 schema_version = 1;
+}
+
+message GetCurrentGenerationRequestResponse {
+ enum Phase {
+ PHASE_UNSPECIFIED = 0;
+ OBSERVE_PRIVATE_SECRET = 1;
+ GENERATE_PENDING = 2;
+ GENERATION_RECORDED = 3;
+ }
+
+ int32 schema_version = 1;
+ Phase phase = 2;
+ string operation_id = 3;
+ string operation_digest = 4;
+ string generation_request_digest = 5;
+ string desired_state_version = 6;
+ string environment_id = 7;
+ string cluster_id = 8;
+ string namespace = 9;
+ string expected_cluster_incarnation_uid = 10;
+ string expected_namespace_uid = 11;
+ string trust_binding_digest = 12;
+ string trust_config_revision = 13;
+ string private_secret_name = 14;
+ string target_generation = 15;
+ string target_kid = 16;
+ string target_algorithm = 17;
+ string operation_action = 18;
+ repeated string allowed_private_slots = 19;
+ ActiveSigner expected_active = 20;
+ string secret_uid = 21;
+ string expected_secret_resource_version = 22;
+ string generation_receipt_digest = 23;
+ string public_key_fingerprint = 24;
+ string public_jwk_json = 25;
+ string observed_secret_resource_version = 26;
+ ActiveSigner expected_published_active = 27;
+}
+
+message RecordSecretObservationRequest {
+ int32 schema_version = 1;
+ string operation_id = 2;
+ string operation_digest = 3;
+ string secret_uid = 4;
+ string observed_resource_version = 5;
+}
+
+message RecordGenerationResultRequest {
+ int32 schema_version = 1;
+ string operation_id = 2;
+ string generation_request_digest = 3;
+ string secret_uid = 4;
+ string expected_prior_resource_version = 5;
+ string observed_resource_version = 6;
+ // Exactly one bounded public RSA JWK; private RSA members and arbitrary resource names are not
+ // part of this schema. Account validates and canonicalizes the JWK and derives its fingerprint.
+ string public_jwk_json = 7;
+}
+
+message RecordGenerationResultResponse {
+ int32 schema_version = 1;
+ string operation_id = 2;
+ string operation_digest = 3;
+ string generation_request_digest = 4;
+ string generation_receipt_digest = 5;
+ string desired_state_version = 6;
+ string environment_id = 7;
+ string cluster_id = 8;
+ string namespace = 9;
+ string expected_cluster_incarnation_uid = 10;
+ string expected_namespace_uid = 11;
+ string trust_binding_digest = 12;
+ string trust_config_revision = 13;
+ string private_secret_name = 14;
+ string secret_uid = 15;
+ string expected_prior_resource_version = 16;
+ string observed_resource_version = 17;
+ string target_generation = 18;
+ string target_kid = 19;
+ string target_algorithm = 20;
+ string public_key_fingerprint = 21;
+ string public_jwk_json = 22;
+}
+
+// Account-authorized fixed-Secret slot transition. This peer response contains public identity
+// fences only; it never selects or publishes the Account-owned JWKS ConfigMap and never commits
+// the Account lifecycle.
+message GetCurrentPromotionRequestRequest {
+ int32 schema_version = 1;
+}
+
+message GetCurrentPromotionRequestResponse {
+ int32 schema_version = 1;
+ string promotion_operation_id = 2;
+ string promotion_request_digest = 3;
+ string generation_operation_id = 4;
+ string generation_operation_digest = 5;
+ string generation_receipt_digest = 6;
+ string environment_id = 7;
+ string cluster_id = 8;
+ string namespace = 9;
+ string expected_cluster_incarnation_uid = 10;
+ string expected_namespace_uid = 11;
+ string trust_binding_digest = 12;
+ string trust_config_revision = 13;
+ string private_secret_name = 14;
+ string target_generation = 15;
+ string target_kid = 16;
+ string target_algorithm = 17;
+ string target_public_key_fingerprint = 18;
+ string expected_secret_uid = 19;
+ string expected_secret_resource_version = 20;
+ string expected_previous_generation = 21;
+ string expected_previous_kid = 22;
+ string expected_previous_public_key_fingerprint = 23;
+ repeated string allowed_private_slots = 24;
+ string operation_action = 25;
+}
+
+message PromotionPublicKeyIdentity {
+ string generation = 1;
+ string kid = 2;
+ string public_key_fingerprint = 3;
+}
+
+message RecordPrivatePromotionResultRequest {
+ int32 schema_version = 1;
+ string promotion_operation_id = 2;
+ string promotion_request_digest = 3;
+ string generation_operation_id = 4;
+ string generation_operation_digest = 5;
+ string secret_uid = 6;
+ string expected_prior_resource_version = 7;
+ string observed_resource_version = 8;
+ PromotionPublicKeyIdentity current = 9;
+ PromotionPublicKeyIdentity previous = 10;
+ repeated string resulting_slots = 11;
+}
+
+message RecordPrivatePromotionResultResponse {
+ int32 schema_version = 1;
+ string promotion_operation_id = 2;
+ string generation_operation_id = 3;
+ string observed_resource_version = 4;
+ string public_receipt_digest = 5;
+}
diff --git a/services/account-service/build.gradle.kts b/services/account-service/build.gradle.kts
index 8a4964119e..f772f55d12 100644
--- a/services/account-service/build.gradle.kts
+++ b/services/account-service/build.gradle.kts
@@ -12,11 +12,37 @@ firemudJooq {
packageName.set("net.firedevops.firemud.accountservice.jooq")
}
+configurations.named("testFixturesImplementation") {
+ extendsFrom(configurations.implementation.get())
+}
+
dependencies {
+ implementation(project(":common-redis-contracts"))
implementation(libs.spring.boot.starter.mail)
implementation(libs.argon2)
implementation(libs.stripe.java)
+
+ testFixturesImplementation(platform(libs.spring.boot.dependencies))
+ testFixturesImplementation(project(":common-platform-core"))
+ testFixturesImplementation(project(":common-security"))
+ testFixturesImplementation(project(":common-data-runtime"))
+ testFixturesImplementation(libs.spring.boot.starter.test)
+ testFixturesImplementation(libs.spring.boot.starter.jdbc)
+ testFixturesImplementation(libs.spring.boot.starter.data.redis)
+ testFixturesImplementation(libs.spring.aop)
+ testFixturesImplementation(libs.mapstruct)
+ testFixturesImplementation(libs.jooq)
+ testFixturesImplementation(libs.flyway.core)
+ testFixturesImplementation("com.fasterxml.jackson.core:jackson-databind")
+ testFixturesImplementation("tools.jackson.core:jackson-databind")
+ testFixturesImplementation("com.google.protobuf:protobuf-java:${libs.versions.protobuf.get()}")
+ testFixturesImplementation("io.grpc:grpc-stub:${libs.versions.grpc.get()}")
+
+ testImplementation(libs.grpc.inprocess)
+ testImplementation(project(":logging-admin-service"))
testImplementation(testFixtures(project(":account-service")))
testCompileOnly(libs.spotbugs.annotations)
add("integrationTestCompileOnly", libs.spotbugs.annotations)
+ integrationTestImplementation(testFixtures(project(":account-service")))
+ integrationTestImplementation(testFixtures(project(":logging-admin-service")))
}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java
new file mode 100644
index 0000000000..5f57a577e3
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java
@@ -0,0 +1,205 @@
+package net.firedevops.firemud.accountservice.client;
+
+import com.google.protobuf.ByteString;
+import jakarta.annotation.PostConstruct;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.time.Clock;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.concurrent.TimeUnit;
+import javax.net.ssl.SSLException;
+import net.firedevops.firemud.common.config.ServiceEndpointsProperties;
+import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient;
+import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer;
+import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties;
+import net.firedevops.firemud.common.grpc.GrpcChannelFactory;
+import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple;
+import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest;
+import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse;
+import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose;
+import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/**
+ * Reads and validates Logging/Admin's current StartSession reservation claim snapshot.
+ *
+ *
The result is fresh read evidence only. It does not authorize a mutation and is not a
+ * commit-spanning compare-and-set proof.
+ */
+@Component
+public final class StartSessionReservationEvidenceClient
+ extends AbstractReloadingBlockingGrpcClient<
+ StartSessionReservationEvidenceServiceGrpc
+ .StartSessionReservationEvidenceServiceBlockingStub> {
+ private static final long CALL_DEADLINE_SECONDS = 5L;
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+
+ private final Clock clock;
+
+ @Autowired
+ public StartSessionReservationEvidenceClient(
+ ServiceEndpointsProperties endpoints,
+ CommonGrpcClientProperties tlsProperties,
+ GrpcChannelFactory channelFactory,
+ BlockingGrpcStubCustomizer stubCustomizer) {
+ this(endpoints, tlsProperties, channelFactory, stubCustomizer, Clock.systemUTC());
+ }
+
+ StartSessionReservationEvidenceClient(
+ ServiceEndpointsProperties endpoints,
+ CommonGrpcClientProperties tlsProperties,
+ GrpcChannelFactory channelFactory,
+ BlockingGrpcStubCustomizer stubCustomizer,
+ Clock clock) {
+ super(
+ endpoints,
+ tlsProperties,
+ channelFactory,
+ stubCustomizer,
+ StartSessionReservationEvidenceClient.class);
+ this.clock = Objects.requireNonNull(clock, "clock is required");
+ }
+
+ @PostConstruct
+ void init() throws SSLException, IOException {
+ initReloadingClient();
+ }
+
+ @Override
+ protected String configuredTarget(ServiceEndpointsProperties endpoints) {
+ return endpoints.getLoggingAdminService();
+ }
+
+ @Override
+ protected String defaultTarget() {
+ return "logging-admin-service:6565";
+ }
+
+ @Override
+ protected StartSessionReservationEvidenceServiceGrpc
+ .StartSessionReservationEvidenceServiceBlockingStub
+ buildStub(io.grpc.ManagedChannel channel) {
+ return applyStubCustomizer(
+ StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel)
+ .withCompression("gzip"));
+ }
+
+ /** Reads the exact active claim for ISSUE or RECOVER and validates every returned binding. */
+ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence(
+ StartSessionPreAuthorizationReservationTuple tuple,
+ UUID reservationOwnerId,
+ long reservationClaimFence,
+ UUID currentClaimOwnerId,
+ long currentClaimFence,
+ Purpose purpose) {
+ Objects.requireNonNull(tuple, "reservation tuple is required");
+ requireNonNilUuid(reservationOwnerId, "reservationOwnerId");
+ requireNonNilUuid(currentClaimOwnerId, "currentClaimOwnerId");
+ Objects.requireNonNull(purpose, "read purpose is required");
+ if (reservationClaimFence <= 0L || currentClaimFence <= 0L) {
+ throw new IllegalArgumentException("reservation claim fences must be positive");
+ }
+ requirePurposeOwnership(
+ purpose, reservationOwnerId, reservationClaimFence, currentClaimOwnerId, currentClaimFence);
+
+ byte[] tupleBytes = tuple.canonicalJson().getBytes(StandardCharsets.UTF_8);
+ ReadCurrentClaimEvidenceRequest request =
+ ReadCurrentClaimEvidenceRequest.newBuilder()
+ .setControlPlaneRequestId(tuple.controlPlaneRequestId())
+ .setPreAuthorizationTupleJson(ByteString.copyFrom(tupleBytes))
+ .setReservationOwnerId(reservationOwnerId.toString())
+ .setReservationClaimFence(reservationClaimFence)
+ .setClaimOwnerId(currentClaimOwnerId.toString())
+ .setClaimFence(currentClaimFence)
+ .setPurpose(toWirePurpose(purpose))
+ .build();
+
+ var currentStub = stub();
+ if (currentStub == null) {
+ throw new IllegalStateException("Logging/Admin reservation evidence client is unavailable");
+ }
+ ReadCurrentClaimEvidenceResponse response =
+ currentStub
+ .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS)
+ .readCurrentClaimEvidence(request);
+ validateResponse(
+ response,
+ tuple,
+ tupleBytes,
+ reservationOwnerId,
+ reservationClaimFence,
+ currentClaimOwnerId,
+ currentClaimFence,
+ purpose);
+ return response;
+ }
+
+ private void validateResponse(
+ ReadCurrentClaimEvidenceResponse response,
+ StartSessionPreAuthorizationReservationTuple tuple,
+ byte[] tupleBytes,
+ UUID reservationOwnerId,
+ long reservationClaimFence,
+ UUID currentClaimOwnerId,
+ long currentClaimFence,
+ Purpose purpose) {
+ long localNowEpochMillis = clock.millis();
+ if (!response.getUnknownFields().asMap().isEmpty()
+ || !tuple.controlPlaneRequestId().equals(response.getControlPlaneRequestId())
+ || !Arrays.equals(tupleBytes, response.getPreAuthorizationTupleJson().toByteArray())
+ || !tuple.mutationDigest().equals(response.getMutationDigest())
+ || !reservationOwnerId.toString().equals(response.getReservationOwnerId())
+ || response.getReservationClaimFence() != reservationClaimFence
+ || !currentClaimOwnerId.toString().equals(response.getClaimOwnerId())
+ || response.getClaimFence() != currentClaimFence
+ || response.getPurpose() != toWirePurpose(purpose)
+ || response.getObservedAtEpochMillis() <= 0L
+ || response.getObservedAtEpochMillis() > localNowEpochMillis
+ || response.getClaimExpiresAtEpochMillis() <= response.getObservedAtEpochMillis()
+ || response.getClaimExpiresAtEpochMillis() <= localNowEpochMillis) {
+ throw new IllegalStateException(
+ "Logging/Admin returned stale or mismatched StartSession reservation evidence");
+ }
+ }
+
+ private static void requirePurposeOwnership(
+ Purpose purpose,
+ UUID reservationOwnerId,
+ long reservationClaimFence,
+ UUID currentClaimOwnerId,
+ long currentClaimFence) {
+ if (purpose == Purpose.ISSUE
+ && (!reservationOwnerId.equals(currentClaimOwnerId)
+ || reservationClaimFence != currentClaimFence)) {
+ throw new IllegalArgumentException("ISSUE requires the original reservation owner and fence");
+ }
+ if (purpose == Purpose.RECOVER
+ && (reservationOwnerId.equals(currentClaimOwnerId)
+ || currentClaimFence <= reservationClaimFence)) {
+ throw new IllegalArgumentException("RECOVER requires a fresh recovery owner and fence");
+ }
+ }
+
+ private static void requireNonNilUuid(UUID value, String fieldName) {
+ if (value == null || NIL_UUID.equals(value)) {
+ throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID");
+ }
+ }
+
+ private static StartSessionReservationEvidencePurpose toWirePurpose(Purpose purpose) {
+ return switch (purpose) {
+ case ISSUE ->
+ StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_ISSUE;
+ case RECOVER ->
+ StartSessionReservationEvidencePurpose.START_SESSION_RESERVATION_EVIDENCE_PURPOSE_RECOVER;
+ };
+ }
+
+ public enum Purpose {
+ ISSUE,
+ RECOVER
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java
new file mode 100644
index 0000000000..71ba3c2455
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBinding.java
@@ -0,0 +1,404 @@
+package net.firedevops.firemud.accountservice.config;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.SeekableByteChannel;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.PosixFilePermission;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Reads the independently protected trust binding for Account's narrow JWT materializer RPCs. The
+ * file must be root-owned and non-writable by the Account/materializer workload. It is read again
+ * for every RPC so pin rotation or trust withdrawal takes effect without process restart.
+ */
+@Component
+public final class AccountJwtSignerMaterializerTrustBinding {
+ public static final int MAX_FILE_BYTES = 8 * 1024;
+ private static final String VERSION = "account-jwt-signer-materializer-binding/v1";
+ private static final Set REQUIRED_FIELDS =
+ Set.of(
+ "enabled",
+ "configRevision",
+ "environmentId",
+ "clusterId",
+ "namespace",
+ "expectedClusterIncarnationUid",
+ "expectedNamespaceUid",
+ "expectedPeerUri",
+ "peerSpkiSha256Pins",
+ "bindingDigest");
+ private static final Pattern ENVIRONMENT =
+ Pattern.compile("[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?");
+ private static final Pattern CLUSTER = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}");
+ private static final Pattern REVISION = Pattern.compile("[A-Za-z0-9][A-Za-z0-9._:-]{0,127}");
+ private static final Pattern SHA256 = Pattern.compile("[0-9a-f]{64}");
+ private static final JsonMapper JSON = JsonMapper.builder().build();
+
+ private final boolean enabled;
+ private final String protectedBindingPath;
+
+ public AccountJwtSignerMaterializerTrustBinding(
+ @Value("${firemud.account.jwt-signer.materialization.enabled:false}") boolean enabled,
+ @Value("${firemud.account.jwt-signer.materialization.protected-binding-path:}")
+ String protectedBindingPath) {
+ this.enabled = enabled;
+ this.protectedBindingPath = protectedBindingPath == null ? "" : protectedBindingPath.trim();
+ }
+
+ /** Missing, disabled, malformed, or mutable trust configuration always means no access. */
+ public Optional current() {
+ if (!enabled || protectedBindingPath.isBlank()) {
+ return Optional.empty();
+ }
+ try {
+ return Optional.of(readProtectedFile(Path.of(protectedBindingPath)));
+ } catch (Exception ex) {
+ // Never expose config contents, file paths, or certificate details through RPC errors.
+ return Optional.empty();
+ }
+ }
+
+ /** Testable parser boundary; production calls still require the protected-file checks above. */
+ static AccountJwtSignerMaterializerTrustBinding.Binding parseProtectedBytes(byte[] bytes) {
+ if (bytes == null || bytes.length == 0 || bytes.length > MAX_FILE_BYTES) {
+ throw new IllegalArgumentException("JWT materializer trust binding is unavailable");
+ }
+ String text = decodeUtf8(bytes);
+ String[] lines = text.split("\n", -1);
+ int count = lines.length;
+ if (count > 0 && lines[count - 1].isEmpty()) {
+ count--;
+ }
+ Map fields = new LinkedHashMap<>();
+ for (int index = 0; index < count; index++) {
+ String line = lines[index];
+ int separator = line.indexOf('=');
+ if (line.isEmpty() || separator <= 0 || separator == line.length() - 1) {
+ throw new IllegalArgumentException("JWT materializer trust binding is malformed");
+ }
+ String key = line.substring(0, separator);
+ String value = line.substring(separator + 1);
+ if (!REQUIRED_FIELDS.contains(key) || fields.putIfAbsent(key, value) != null) {
+ throw new IllegalArgumentException("JWT materializer trust binding is malformed");
+ }
+ }
+ if (!fields.keySet().equals(REQUIRED_FIELDS) || !"true".equals(fields.get("enabled"))) {
+ throw new IllegalArgumentException("JWT materializer trust binding is disabled");
+ }
+
+ String environmentId = fields.get("environmentId");
+ String clusterId = fields.get("clusterId");
+ String namespace = fields.get("namespace");
+ String clusterUid = canonicalUuid(fields.get("expectedClusterIncarnationUid"));
+ String namespaceUid = canonicalUuid(fields.get("expectedNamespaceUid"));
+ String revision = fields.get("configRevision");
+ if (!ENVIRONMENT.matcher(environmentId).matches()
+ || !CLUSTER.matcher(clusterId).matches()
+ || !ENVIRONMENT.matcher(namespace).matches()
+ || !REVISION.matcher(revision).matches()) {
+ throw new IllegalArgumentException("JWT materializer trust binding is malformed");
+ }
+ String expectedUri = fields.get("expectedPeerUri");
+ if (!validExpectedPeerUri(namespace, expectedUri)) {
+ throw new IllegalArgumentException("JWT materializer workload identity is not canonical");
+ }
+ List pins = parsePins(fields.get("peerSpkiSha256Pins"));
+ String digest =
+ computeBindingDigest(
+ revision,
+ environmentId,
+ clusterId,
+ namespace,
+ clusterUid,
+ namespaceUid,
+ expectedUri,
+ pins);
+ if (!digest.equals(fields.get("bindingDigest"))) {
+ throw new IllegalArgumentException("JWT materializer trust binding digest is invalid");
+ }
+ return new AccountJwtSignerMaterializerTrustBinding.Binding(
+ environmentId,
+ clusterId,
+ namespace,
+ clusterUid,
+ namespaceUid,
+ expectedUri,
+ pins,
+ revision,
+ digest);
+ }
+
+ private static Binding readProtectedFile(Path path) throws IOException {
+ Path absolute = path.toAbsolutePath().normalize();
+ if (Files.isSymbolicLink(absolute)) {
+ throw new IOException("Protected Account JWT materializer binding is not a regular file");
+ }
+ BasicFileAttributes before =
+ Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+ if (!before.isRegularFile()) {
+ throw new IOException("Protected Account JWT materializer binding is not a regular file");
+ }
+ verifyRootOwnedAndNonWritable(absolute);
+ if (before.size() <= 0 || before.size() > MAX_FILE_BYTES) {
+ throw new IOException("Protected Account JWT materializer binding size is invalid");
+ }
+ byte[] bytes = new byte[(int) before.size()];
+ try (SeekableByteChannel channel =
+ Files.newByteChannel(absolute, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+ while (buffer.hasRemaining()) {
+ int count = channel.read(buffer);
+ if (count < 0) {
+ throw new IOException("Protected Account JWT materializer binding changed while reading");
+ }
+ }
+ if (channel.read(ByteBuffer.allocate(1)) != -1) {
+ throw new IOException("Protected Account JWT materializer binding changed while reading");
+ }
+ }
+ BasicFileAttributes after =
+ Files.readAttributes(absolute, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+ if (!after.isRegularFile()
+ || !Objects.equals(before.fileKey(), after.fileKey())
+ || before.size() != after.size()
+ || !before.lastModifiedTime().equals(after.lastModifiedTime())) {
+ throw new IOException("Protected Account JWT materializer binding changed while reading");
+ }
+ verifyRootOwnedAndNonWritable(absolute);
+ return parseProtectedBytes(bytes);
+ }
+
+ private static void verifyRootOwnedAndNonWritable(Path file) throws IOException {
+ Path parent = file.getParent();
+ if (parent == null || Files.isSymbolicLink(file)) {
+ throw new IOException("Protected Account JWT materializer binding is unavailable");
+ }
+ Path realParent = parent.toRealPath();
+ Object fileOwner = Files.getAttribute(file, "unix:uid", LinkOption.NOFOLLOW_LINKS);
+ Object directoryOwner = Files.getAttribute(realParent, "unix:uid", LinkOption.NOFOLLOW_LINKS);
+ Set fileMode =
+ Files.getPosixFilePermissions(file, LinkOption.NOFOLLOW_LINKS);
+ Set directoryMode = Files.getPosixFilePermissions(realParent);
+ if (!(fileOwner instanceof Number fileUid)
+ || fileUid.longValue() != 0L
+ || !(directoryOwner instanceof Number directoryUid)
+ || directoryUid.longValue() != 0L
+ || writable(fileMode)
+ || writable(directoryMode)) {
+ throw new IOException("Protected Account JWT materializer binding ownership is invalid");
+ }
+ }
+
+ private static boolean writable(Set permissions) {
+ return permissions.contains(PosixFilePermission.OWNER_WRITE)
+ || permissions.contains(PosixFilePermission.GROUP_WRITE)
+ || permissions.contains(PosixFilePermission.OTHERS_WRITE);
+ }
+
+ private static String decodeUtf8(byte[] bytes) {
+ try {
+ return StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ } catch (CharacterCodingException ex) {
+ throw new IllegalArgumentException("JWT materializer trust binding is not UTF-8", ex);
+ }
+ }
+
+ private static List parsePins(String value) {
+ String[] parts = value.split(",", -1);
+ if (parts.length == 0 || parts.length > 8) {
+ throw new IllegalArgumentException("JWT materializer certificate pins are malformed");
+ }
+ List pins = new ArrayList<>(parts.length);
+ for (String pin : parts) {
+ if (!SHA256.matcher(pin).matches() || pins.contains(pin)) {
+ throw new IllegalArgumentException("JWT materializer certificate pins are malformed");
+ }
+ pins.add(pin);
+ }
+ return List.copyOf(pins);
+ }
+
+ private static boolean validExpectedPeerUri(String namespace, String uri) {
+ String prefix = "spiffe://firemud/ns/" + namespace + "/sa/";
+ return uri != null
+ && uri.startsWith(prefix)
+ && ENVIRONMENT.matcher(uri.substring(prefix.length())).matches();
+ }
+
+ private static String canonicalUuid(String value) {
+ UUID uuid = UUID.fromString(value);
+ if (!uuid.toString().equals(value) || new UUID(0L, 0L).equals(uuid)) {
+ throw new IllegalArgumentException("JWT materializer trust UID is malformed");
+ }
+ return uuid.toString();
+ }
+
+ public static String computeBindingDigest(
+ String configRevision,
+ String environmentId,
+ String clusterId,
+ String namespace,
+ String expectedClusterIncarnationUid,
+ String expectedNamespaceUid,
+ String expectedPeerUri,
+ List pins) {
+ try {
+ Map binding = new LinkedHashMap<>();
+ binding.put("digestVersion", VERSION);
+ binding.put("configRevision", configRevision);
+ binding.put("environmentId", environmentId);
+ binding.put("clusterId", clusterId);
+ binding.put("namespace", namespace);
+ binding.put("expectedClusterIncarnationUid", expectedClusterIncarnationUid);
+ binding.put("expectedNamespaceUid", expectedNamespaceUid);
+ binding.put("expectedPeerUri", expectedPeerUri);
+ binding.put("peerSpkiSha256Pins", List.copyOf(pins));
+ byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(binding));
+ return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(canonical));
+ } catch (Exception ex) {
+ throw new IllegalStateException("JWT materializer trust binding digest is unavailable", ex);
+ }
+ }
+
+ public static boolean matchesPeer(
+ java.security.cert.Certificate[] peerCertificates, Binding binding) {
+ if (peerCertificates == null || peerCertificates.length == 0 || binding == null) {
+ return false;
+ }
+ if (!(peerCertificates[0] instanceof X509Certificate certificate)) {
+ return false;
+ }
+ try {
+ certificate.checkValidity();
+ Collection> subjectAlternativeNames = certificate.getSubjectAlternativeNames();
+ if (subjectAlternativeNames == null) {
+ return false;
+ }
+ String foundUri = null;
+ int uriCount = 0;
+ for (List> entry : subjectAlternativeNames) {
+ if (entry.size() < 2 || !(entry.get(0) instanceof Integer type) || type != 6) {
+ continue;
+ }
+ uriCount++;
+ if (!(entry.get(1) instanceof String uri)) {
+ return false;
+ }
+ foundUri = uri;
+ }
+ if (uriCount != 1 || !binding.expectedPeerUri().equals(foundUri)) {
+ return false;
+ }
+ byte[] spkiDigest =
+ MessageDigest.getInstance("SHA-256").digest(certificate.getPublicKey().getEncoded());
+ byte[] configuredPin = HexFormat.of().parseHex(binding.peerSpkiSha256Pins().get(0));
+ boolean matched = MessageDigest.isEqual(spkiDigest, configuredPin);
+ for (int index = 1; index < binding.peerSpkiSha256Pins().size(); index++) {
+ byte[] pin = HexFormat.of().parseHex(binding.peerSpkiSha256Pins().get(index));
+ matched |= MessageDigest.isEqual(spkiDigest, pin);
+ }
+ return matched;
+ } catch (CertificateException | NoSuchAlgorithmException | RuntimeException ex) {
+ return false;
+ }
+ }
+
+ public record Binding(
+ String environmentId,
+ String clusterId,
+ String namespace,
+ String expectedClusterIncarnationUid,
+ String expectedNamespaceUid,
+ String expectedPeerUri,
+ List peerSpkiSha256Pins,
+ String configRevision,
+ String bindingDigest) {
+ public Binding {
+ Objects.requireNonNull(environmentId, "Environment identity is required");
+ Objects.requireNonNull(clusterId, "Cluster identity is required");
+ Objects.requireNonNull(namespace, "Namespace identity is required");
+ canonicalUuid(expectedClusterIncarnationUid);
+ canonicalUuid(expectedNamespaceUid);
+ Objects.requireNonNull(expectedPeerUri, "Materializer URI identity is required");
+ peerSpkiSha256Pins = List.copyOf(peerSpkiSha256Pins);
+ if (peerSpkiSha256Pins.isEmpty() || peerSpkiSha256Pins.size() > 8) {
+ throw new IllegalArgumentException("JWT materializer certificate pins are unavailable");
+ }
+ for (String pin : peerSpkiSha256Pins) {
+ if (!SHA256.matcher(pin).matches()) {
+ throw new IllegalArgumentException("JWT materializer certificate pins are malformed");
+ }
+ }
+ Objects.requireNonNull(configRevision, "Materializer trust revision is required");
+ if (!REVISION.matcher(configRevision).matches() || !SHA256.matcher(bindingDigest).matches()) {
+ throw new IllegalArgumentException("JWT materializer trust binding digest is malformed");
+ }
+ if (peerSpkiSha256Pins.stream().distinct().count() != peerSpkiSha256Pins.size()) {
+ throw new IllegalArgumentException("JWT materializer certificate pins are duplicated");
+ }
+ AccountJwtSignerDesiredStateRepository.Binding stateBinding =
+ new AccountJwtSignerDesiredStateRepository.Binding(
+ environmentId,
+ clusterId,
+ namespace,
+ AccountJwtSignerDesiredStateRepository.CustodyMode
+ .INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK);
+ if (!validExpectedPeerUri(stateBinding.namespace(), expectedPeerUri)) {
+ throw new IllegalArgumentException("JWT materializer workload identity is not canonical");
+ }
+ String expectedDigest =
+ computeBindingDigest(
+ configRevision,
+ environmentId,
+ clusterId,
+ namespace,
+ expectedClusterIncarnationUid,
+ expectedNamespaceUid,
+ expectedPeerUri,
+ peerSpkiSha256Pins);
+ if (!expectedDigest.equals(bindingDigest)) {
+ throw new IllegalArgumentException("JWT materializer trust binding digest is invalid");
+ }
+ }
+
+ public AccountJwtSignerDesiredStateRepository.Binding accountBinding() {
+ return new AccountJwtSignerDesiredStateRepository.Binding(
+ environmentId,
+ clusterId,
+ namespace,
+ AccountJwtSignerDesiredStateRepository.CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java
new file mode 100644
index 0000000000..8b6a275528
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfiguration.java
@@ -0,0 +1,132 @@
+package net.firedevops.firemud.accountservice.config;
+
+import java.nio.file.Path;
+import java.security.SecureRandom;
+import java.time.Clock;
+import java.time.Duration;
+import net.firedevops.firemud.accountservice.client.StartSessionReservationEvidenceClient;
+import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService;
+import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository;
+import net.firedevops.firemud.accountservice.service.session.AccountControlUiActorService;
+import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository;
+import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring;
+import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource;
+import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography;
+import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring;
+import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.transaction.PlatformTransactionManager;
+
+/**
+ * Explicit, disabled-by-default composition for Account's human StartSession authorization owner.
+ *
+ * Enabling this composition requires real Account owner sources, trusted key custody, and
+ * configured bounded timing. This configuration supplies no actor, hosted-terms, fingerprint-key,
+ * or response-encryption defaults.
+ */
+@Configuration(proxyBeanMethods = false)
+@ConditionalOnProperty(
+ prefix = AccountStartSessionOperatorAuthorizationConfiguration.PROPERTY_PREFIX,
+ name = "enabled",
+ havingValue = "true",
+ matchIfMissing = false)
+public class AccountStartSessionOperatorAuthorizationConfiguration {
+ static final String PROPERTY_PREFIX = "firemud.account.start-session-operator-authorization";
+ static final String OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN =
+ "startSessionOperatorResponseEnvelopeCryptography";
+
+ /** Creates Account's explicit active/retained HMAC calculator from an owner-supplied source. */
+ @Bean
+ public AccountOperatorAuthorizationFingerprintKeyring
+ accountStartSessionOperatorFingerprintKeyring(
+ OwnerKeySource ownerKeySource,
+ @Value(
+ "${firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention}")
+ Duration requiredPostExpiryRetention) {
+ return new AccountOperatorAuthorizationFingerprintKeyring(
+ ownerKeySource, Clock.systemUTC(), requiredPostExpiryRetention);
+ }
+
+ /**
+ * Creates a separate response-envelope cryptography instance from the operator-only mount.
+ *
+ *
The generic Account envelope bean and control-ui cryptography are deliberately not injected
+ * or reused. Deployment remains responsible for supplying a distinct protected key mount.
+ */
+ @Bean(name = OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN)
+ @Qualifier(OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN)
+ public AccountResponseEnvelopeCryptography
+ accountStartSessionOperatorResponseEnvelopeCryptography(
+ @Value(
+ "${firemud.account.start-session-operator-authorization.response-envelope.keyring-path}")
+ String operatorKeyringPath,
+ @Value("${firemud.account.response-envelope.keyring-path:}")
+ String generalAccountKeyringPath) {
+ Path operatorMount = requiredAbsoluteMount(operatorKeyringPath, "operator response keyring");
+ if (generalAccountKeyringPath != null && !generalAccountKeyringPath.isBlank()) {
+ Path generalMount = Path.of(generalAccountKeyringPath).toAbsolutePath().normalize();
+ if (operatorMount.equals(generalMount)) {
+ throw new IllegalArgumentException(
+ "Operator response keyring must use its separately supplied mount");
+ }
+ }
+ return new AccountResponseEnvelopeCryptography(
+ new AccountResponseEnvelopeKeyring(operatorMount.toString()));
+ }
+
+ /** Wires only genuine owner collaborators and a same-namespace workload policy. */
+ @Bean
+ public AccountStartSessionOperatorAuthorizationService
+ accountStartSessionOperatorAuthorizationService(
+ AccountControlUiActorService actors,
+ AccountControlUiIssuanceRepository issuanceOperations,
+ StartSessionReservationEvidenceClient reservationEvidence,
+ AccountStartSessionOperatorAuthorizationRepository repository,
+ AccountOperatorAuthorizationFingerprintKeyring fingerprintKeys,
+ @Qualifier(OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN)
+ AccountResponseEnvelopeCryptography operatorResponseCryptography,
+ AccountHostedTermsService hostedTerms,
+ PlatformTransactionManager transactions,
+ @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace,
+ @Value("${firemud.account.start-session-operator-authorization.reference-lifetime}")
+ Duration referenceLifetime,
+ @Value("${firemud.account.start-session-operator-authorization.response-recovery-window}")
+ Duration responseRecoveryWindow) {
+ if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) {
+ throw new IllegalArgumentException(
+ "A valid configured workload namespace is required for operator authorization");
+ }
+ String peerPrefix = "spiffe://firemud/ns/" + workloadNamespace + "/sa/";
+ return new AccountStartSessionOperatorAuthorizationService(
+ actors,
+ issuanceOperations,
+ reservationEvidence,
+ repository,
+ fingerprintKeys,
+ operatorResponseCryptography,
+ hostedTerms,
+ transactions,
+ Clock.systemUTC(),
+ new SecureRandom(),
+ peerPrefix + "logging-admin-service",
+ peerPrefix + "game-session-service",
+ referenceLifetime,
+ responseRecoveryWindow);
+ }
+
+ private static Path requiredAbsoluteMount(String configuredPath, String field) {
+ if (configuredPath == null || configuredPath.isBlank()) {
+ throw new IllegalArgumentException("Explicit " + field + " mount is required");
+ }
+ Path path = Path.of(configuredPath);
+ if (!path.isAbsolute()) {
+ throw new IllegalArgumentException("Absolute " + field + " mount is required");
+ }
+ return path.normalize();
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java
new file mode 100644
index 0000000000..f12f41ea2b
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepository.java
@@ -0,0 +1,280 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/** Read-only exact lookup of immutable Account control-ui issuance evidence. */
+@Repository
+public class AccountControlUiCommittedIssuanceRepository {
+ private static final String TABLE = "account_control_ui_issuance_operations";
+ private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}");
+ private static final int MAX_CLAIMS = 16 * 1024;
+ private static final int MAX_SOURCE = 131072;
+ private static final int MAX_BUNDLE = 131072;
+ private static final int MAX_SIGNER_RECEIPT = 65536;
+
+ private final DSLContext dsl;
+
+ @SuppressFBWarnings(
+ value = {"EI_EXPOSE_REP2", "CT_CONSTRUCTOR_THROW"},
+ justification =
+ "Spring injects the shared transaction-aware DSLContext; this proxyable repository only validates that dependency and acquires no resources in its constructor.")
+ public AccountControlUiCommittedIssuanceRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl);
+ }
+
+ /** Reads only the exact still-COMMITTED issuance row in the caller's Account transaction. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional readCommitted(String tokenHash) {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException(
+ "Committed Account issuance read requires an Account transaction");
+ }
+ if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) {
+ throw denied();
+ }
+ Record row =
+ dsl.fetchOne(
+ "SELECT request_id, operation_id, token_jti, account_uuid, tenant_uuid, "
+ + "caller_workload, caller_context_id, request_digest, claims_payload, "
+ + "source_payload, bundle_payload, signer_receipt, issued_at_epoch_second, "
+ + "expires_at_epoch_second, recovery_expires_at, status, token_hash, "
+ + "pending_registry, active_registry, pending_receipt, committed_at, "
+ + "recovery_failed_at FROM "
+ + TABLE
+ + " WHERE token_hash = ? FOR SHARE",
+ tokenHash);
+ if (row == null) {
+ return Optional.empty();
+ }
+ try {
+ CommittedIssuance evidence = new CommittedIssuance(row);
+ if (!"COMMITTED".equals(evidence.status())
+ || !tokenHash.equals(evidence.tokenHash())
+ || evidence.recoveryFailedAt() != null
+ || evidence.committedAt() == null
+ || evidence.pendingReceipt().length == 0) {
+ throw denied();
+ }
+ return Optional.of(evidence);
+ } catch (RuntimeException malformed) {
+ throw denied();
+ }
+ }
+
+ private static IllegalStateException denied() {
+ return new IllegalStateException(
+ "Exact committed Account control-ui issuance evidence unavailable");
+ }
+
+ private static byte[] bytes(Record row, String field, int maximum) {
+ byte[] value = row.get(field, byte[].class);
+ if (value == null || value.length == 0 || value.length > maximum) {
+ throw denied();
+ }
+ return value.clone();
+ }
+
+ private static UUID uuid(Record row, String field) {
+ UUID value = row.get(field, UUID.class);
+ if (value == null || isNil(value)) {
+ throw denied();
+ }
+ return value;
+ }
+
+ private static boolean isNil(UUID value) {
+ return value.getMostSignificantBits() == 0L && value.getLeastSignificantBits() == 0L;
+ }
+
+ private static long positive(Record row, String field) {
+ Long value = row.get(field, Long.class);
+ if (value == null || value <= 0L) {
+ throw denied();
+ }
+ return value;
+ }
+
+ private static String text(Record row, String field) {
+ String value = row.get(field, String.class);
+ if (value == null || value.isBlank()) {
+ throw denied();
+ }
+ return value;
+ }
+
+ private static String tokenHash(Record row) {
+ String value = row.get("token_hash", String.class);
+ if (value == null || !TOKEN_HASH.matcher(value).matches()) {
+ throw denied();
+ }
+ return value;
+ }
+
+ /** Defensive immutable owner row; it does not contain the compact JWT or response envelope. */
+ public static final class CommittedIssuance {
+ private final UUID requestId;
+ private final UUID operationId;
+ private final UUID tokenJti;
+ private final UUID accountId;
+ private final UUID tenantId;
+ private final String callerWorkload;
+ private final UUID callerContextId;
+ private final String requestDigest;
+ private final byte[] claims;
+ private final byte[] source;
+ private final byte[] bundle;
+ private final byte[] signerReceipt;
+ private final long issuedAtEpochSecond;
+ private final long expiresAtEpochSecond;
+ private final String status;
+ private final String tokenHash;
+ private final byte[] pendingRegistry;
+ private final byte[] activeRegistry;
+ private final byte[] pendingReceipt;
+ private final java.time.OffsetDateTime committedAt;
+ private final java.time.OffsetDateTime recoveryFailedAt;
+
+ private CommittedIssuance(Record row) {
+ requestId = uuid(row, "request_id");
+ operationId = uuid(row, "operation_id");
+ tokenJti = uuid(row, "token_jti");
+ accountId = uuid(row, "account_uuid");
+ tenantId = uuid(row, "tenant_uuid");
+ callerWorkload = text(row, "caller_workload");
+ callerContextId = uuid(row, "caller_context_id");
+ requestDigest = digest(row, "request_digest");
+ claims = bytes(row, "claims_payload", MAX_CLAIMS);
+ source = bytes(row, "source_payload", MAX_SOURCE);
+ bundle = bytes(row, "bundle_payload", MAX_BUNDLE);
+ signerReceipt = bytes(row, "signer_receipt", MAX_SIGNER_RECEIPT);
+ issuedAtEpochSecond = positive(row, "issued_at_epoch_second");
+ expiresAtEpochSecond = positive(row, "expires_at_epoch_second");
+ if (expiresAtEpochSecond <= issuedAtEpochSecond
+ || expiresAtEpochSecond - issuedAtEpochSecond > 300L) {
+ throw denied();
+ }
+ status = text(row, "status");
+ tokenHash = AccountControlUiCommittedIssuanceRepository.tokenHash(row);
+ pendingRegistry = bytes(row, "pending_registry", 32768);
+ activeRegistry = bytes(row, "active_registry", 32768);
+ pendingReceipt = bytes(row, "pending_receipt", 8192);
+ committedAt = row.get("committed_at", java.time.OffsetDateTime.class);
+ recoveryFailedAt = row.get("recovery_failed_at", java.time.OffsetDateTime.class);
+ }
+
+ private static String digest(Record row, String field) {
+ String value = text(row, field);
+ if (!Pattern.matches("[0-9a-f]{64}", value)) {
+ throw denied();
+ }
+ return value;
+ }
+
+ public UUID requestId() {
+ return requestId;
+ }
+
+ public UUID operationId() {
+ return operationId;
+ }
+
+ public UUID tokenJti() {
+ return tokenJti;
+ }
+
+ public UUID accountId() {
+ return accountId;
+ }
+
+ public UUID tenantId() {
+ return tenantId;
+ }
+
+ public String callerWorkload() {
+ return callerWorkload;
+ }
+
+ public UUID callerContextId() {
+ return callerContextId;
+ }
+
+ public String requestDigest() {
+ return requestDigest;
+ }
+
+ public byte[] claims() {
+ return claims.clone();
+ }
+
+ public byte[] source() {
+ return source.clone();
+ }
+
+ public byte[] bundle() {
+ return bundle.clone();
+ }
+
+ public byte[] signerReceipt() {
+ return signerReceipt.clone();
+ }
+
+ public long issuedAtEpochSecond() {
+ return issuedAtEpochSecond;
+ }
+
+ public long expiresAtEpochSecond() {
+ return expiresAtEpochSecond;
+ }
+
+ public String status() {
+ return status;
+ }
+
+ public String tokenHash() {
+ return tokenHash;
+ }
+
+ public byte[] pendingRegistry() {
+ return pendingRegistry.clone();
+ }
+
+ public byte[] activeRegistry() {
+ return activeRegistry.clone();
+ }
+
+ public byte[] pendingReceipt() {
+ return pendingReceipt.clone();
+ }
+
+ public java.time.OffsetDateTime committedAt() {
+ return committedAt;
+ }
+
+ public java.time.OffsetDateTime recoveryFailedAt() {
+ return recoveryFailedAt;
+ }
+
+ public long expiryMillis() {
+ try {
+ return Math.multiplyExact(expiresAtEpochSecond, 1000L);
+ } catch (ArithmeticException malformed) {
+ throw denied();
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "AccountControlUiCommittedIssuanceRepository.CommittedIssuance[redacted]";
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java
new file mode 100644
index 0000000000..9b233918c2
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepository.java
@@ -0,0 +1,803 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle.BundleReference;
+import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Permanent Account-owned issuance and one-time redemption storage for StartSession operator
+ * authorization.
+ *
+ * Callers must authenticate the immediate workload peer and establish current Account authority
+ * before invoking this repository. This storage is not authority evidence and a returned record is
+ * not a source-snapshot guarantee. Callers enforce the immutable response-envelope expiry before
+ * recovering or decrypting that envelope. All methods require the caller's ambient Account
+ * transaction; this repository performs no network calls and creates no credentials, references, or
+ * keys.
+ */
+@Repository
+public class AccountStartSessionOperatorAuthorizationRepository {
+ private static final String TABLE = "account_start_session_operator_authorizations";
+ private static final String SELECT_COLUMNS =
+ "control_plane_request_id, pre_authorization_tuple, mutation_digest, "
+ + "issuance_workload_uri, reservation_owner_id, reservation_claim_fence, "
+ + "issuance_operation_id, issuance_fence, bundle_version, bundle_source_version, "
+ + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, "
+ + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, "
+ + "reference_expires_at, response_envelope_expires_at, status, "
+ + "redemption_redeemer_workload_uri, redemption_owner_attempt_id, "
+ + "redemption_owner_fence, redeemed_at, redemption_reference_fingerprint, "
+ + "redemption_authority_evidence_bundle";
+ private static final int MAX_TUPLE_BYTES = 8 * 1024;
+ private static final int MAX_AUTHORITY_BUNDLE_BYTES = 128 * 1024;
+ private static final int MAX_ENCRYPTED_ENVELOPE_BYTES = 64 * 1024;
+ private static final Duration MAX_REFERENCE_LIFETIME = Duration.ofMinutes(5);
+ private static final Duration MAX_RESPONSE_RECOVERY_WINDOW = Duration.ofMinutes(1);
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+ private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}");
+ private static final Pattern FINGERPRINT =
+ Pattern.compile("arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}");
+ private static final Pattern SPIFFE_WORKLOAD_URI =
+ Pattern.compile(
+ "spiffe://firemud/ns/[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?/sa/"
+ + "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?");
+
+ private final DSLContext dsl;
+
+ @SuppressFBWarnings(
+ value = "CT_CONSTRUCTOR_THROW",
+ justification =
+ "Constructor validates the injected DSL collaborator without acquiring resources or exposing a partially initialized repository.")
+ public AccountStartSessionOperatorAuthorizationRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl, "DSLContext is required");
+ }
+
+ /**
+ * Inserts the one permanent issuance row or returns its exact original output on duplicate.
+ *
+ *
The stable canonical control-plane request ID is the unique key. Duplicate comparison covers
+ * every original pre-authorization binding; candidate output fields are deliberately not compared
+ * or substituted when a row already exists.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public CreateOrReadResult createOrReadExact(IssuanceCandidate candidate) {
+ requireOwnerTransaction();
+ validateCandidate(candidate);
+ int inserted =
+ dsl.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (control_plane_request_id, pre_authorization_tuple, mutation_digest, "
+ + "issuance_workload_uri, reservation_owner_id, reservation_claim_fence, "
+ + "issuance_operation_id, issuance_fence, bundle_version, bundle_source_version, "
+ + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, "
+ + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, "
+ + "reference_expires_at, response_envelope_expires_at, status) "
+ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ISSUED') "
+ + "ON CONFLICT (control_plane_request_id) DO NOTHING",
+ candidate.controlPlaneRequestId(),
+ candidate.preAuthorizationTuple(),
+ candidate.mutationDigest(),
+ candidate.issuanceWorkloadUri(),
+ candidate.reservationOwnerId(),
+ candidate.reservationClaimFence(),
+ candidate.issuanceOperationId(),
+ candidate.issuanceFence(),
+ candidate.bundleReference().bundleVersion(),
+ candidate.bundleReference().sourceVersion(),
+ candidate.bundleReference().sourceFence(),
+ candidate.bundleReference().linearization(),
+ candidate.authorityEvidenceBundle(),
+ candidate.authorizationReferenceFingerprint(),
+ candidate.encryptedResponseEnvelope(),
+ utc(candidate.issuedAt()),
+ utc(candidate.referenceExpiresAt()),
+ utc(candidate.responseEnvelopeExpiresAt()));
+
+ Record row = lockByRequestId(candidate.controlPlaneRequestId());
+ IssuanceRecord original = toIssuanceRecord(row);
+ requireSameOriginalBinding(candidate, original);
+ return new CreateOrReadResult(inserted == 1, original);
+ }
+
+ /** Reads the permanent issuance record by its stable canonical request ID. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public Optional findByControlPlaneRequestId(String controlPlaneRequestId) {
+ requireOwnerTransaction();
+ StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId(
+ controlPlaneRequestId);
+ Record row =
+ dsl.fetchOne(
+ "SELECT " + SELECT_COLUMNS + " FROM " + TABLE + " WHERE control_plane_request_id = ?",
+ controlPlaneRequestId);
+ return Optional.ofNullable(row == null ? null : toIssuanceRecord(row));
+ }
+
+ /**
+ * Atomically consumes an unexpired exact reference binding for one owner attempt.
+ *
+ * The stored redemption projection contains only the immutable fingerprint and the exact
+ * source-bound authority bundle. An exact retry returns that same projection with {@code
+ * replay=true}; it does not authorize a different owner attempt.
+ */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public RedemptionResult redeemExact(RedemptionRequest request) {
+ requireOwnerTransaction();
+ validateRedemptionRequest(request);
+ Record row = lockByRequestId(request.controlPlaneRequestId());
+ if (row == null) {
+ throw unavailable();
+ }
+ IssuanceRecord issuance = toIssuanceRecord(row);
+ requireSameRedemptionBinding(request, issuance);
+
+ if (issuance.status() == Status.REDEEMED) {
+ if (!request.redeemerWorkloadUri().equals(issuance.redemptionRedeemerWorkloadUri())
+ || !request.ownerAttemptId().equals(issuance.redemptionOwnerAttemptId())
+ || request.ownerFence() != issuance.redemptionOwnerFence()) {
+ throw conflict();
+ }
+ return redemptionResult(issuance, true);
+ }
+ if (issuance.referenceExpiresAt().compareTo(request.now()) <= 0) {
+ throw new ReferenceExpiredException();
+ }
+
+ int changed =
+ dsl.execute(
+ "UPDATE "
+ + TABLE
+ + " SET status = 'REDEEMED', redemption_redeemer_workload_uri = ?, "
+ + "redemption_owner_attempt_id = ?, redemption_owner_fence = ?, redeemed_at = ?, "
+ + "redemption_reference_fingerprint = ?, "
+ + "redemption_authority_evidence_bundle = ? "
+ + "WHERE control_plane_request_id = ? AND status = 'ISSUED' "
+ + "AND reference_expires_at > ?",
+ request.redeemerWorkloadUri(),
+ request.ownerAttemptId(),
+ request.ownerFence(),
+ utc(request.now()),
+ request.authorizationReferenceFingerprint(),
+ request.authorityEvidenceBundle(),
+ request.controlPlaneRequestId(),
+ utc(request.now()));
+ if (changed != 1) {
+ throw unavailable();
+ }
+
+ Record redeemedRow = lockByRequestId(request.controlPlaneRequestId());
+ IssuanceRecord redeemed = toIssuanceRecord(redeemedRow);
+ return redemptionResult(redeemed, false);
+ }
+
+ private Record lockByRequestId(String requestId) {
+ return dsl.fetchOne(
+ "SELECT "
+ + SELECT_COLUMNS
+ + " FROM "
+ + TABLE
+ + " WHERE control_plane_request_id = ? FOR UPDATE",
+ requestId);
+ }
+
+ private IssuanceRecord toIssuanceRecord(Record row) {
+ if (row == null) {
+ throw unavailable();
+ }
+ IssuanceRecord issuance =
+ new IssuanceRecord(
+ requiredControlPlaneRequestId(row.get("control_plane_request_id", String.class)),
+ requiredBytes(row, "pre_authorization_tuple", MAX_TUPLE_BYTES),
+ requiredDigest(row.get("mutation_digest", String.class)),
+ requiredWorkloadUri(row.get("issuance_workload_uri", String.class)),
+ requiredUuid(row.get("reservation_owner_id", UUID.class), "reservation owner ID"),
+ requiredPositive(
+ row.get("reservation_claim_fence", Long.class), "reservation claim fence"),
+ requiredUuid(row.get("issuance_operation_id", UUID.class), "issuance operation ID"),
+ requiredPositive(row.get("issuance_fence", Long.class), "issuance fence"),
+ bundleReference(row),
+ requiredBytes(row, "authority_evidence_bundle", MAX_AUTHORITY_BUNDLE_BYTES),
+ requiredFingerprint(row.get("authorization_reference_fingerprint", String.class)),
+ requiredBytes(row, "encrypted_response_envelope", MAX_ENCRYPTED_ENVELOPE_BYTES),
+ requiredInstant(row.get("issued_at", OffsetDateTime.class), "issue time"),
+ requiredInstant(
+ row.get("reference_expires_at", OffsetDateTime.class), "reference expiry"),
+ requiredInstant(
+ row.get("response_envelope_expires_at", OffsetDateTime.class),
+ "response-envelope expiry"),
+ parseStatus(row.get("status", String.class)),
+ optionalWorkloadUri(row.get("redemption_redeemer_workload_uri", String.class)),
+ optionalUuid(row.get("redemption_owner_attempt_id", UUID.class), "owner attempt ID"),
+ optionalPositive(row.get("redemption_owner_fence", Long.class), "owner fence"),
+ optionalInstant(row.get("redeemed_at", OffsetDateTime.class), "redemption time"),
+ optionalFingerprint(row.get("redemption_reference_fingerprint", String.class)),
+ optionalBytes(row, "redemption_authority_evidence_bundle", MAX_AUTHORITY_BUNDLE_BYTES));
+ validateDurableRecord(issuance);
+ return issuance;
+ }
+
+ private static void validateDurableRecord(IssuanceRecord issuance) {
+ try {
+ StartSessionPreAuthorizationReservationTuple tuple =
+ decodeTuple(issuance.preAuthorizationTuple());
+ if (!issuance.controlPlaneRequestId().equals(tuple.controlPlaneRequestId())
+ || !tuple.mutationDigest().equals(issuance.mutationDigest())
+ || !issuance.issuanceWorkloadUri().endsWith("/sa/logging-admin-service")
+ || issuance.reservationClaimFence() <= 0L
+ || issuance.issuanceFence() <= 0L
+ || !Long.toString(issuance.issuanceFence())
+ .equals(issuance.bundleReference().sourceFence())
+ || !issuance.referenceExpiresAt().isAfter(issuance.issuedAt())
+ || issuance.referenceExpiresAt().isAfter(issuance.issuedAt().plus(MAX_REFERENCE_LIFETIME))
+ || !issuance.responseEnvelopeExpiresAt().isAfter(issuance.referenceExpiresAt())
+ || issuance
+ .responseEnvelopeExpiresAt()
+ .isAfter(issuance.referenceExpiresAt().plus(MAX_RESPONSE_RECOVERY_WINDOW))) {
+ throw unavailable();
+ }
+ if (issuance.status() == Status.REDEEMED
+ && (!ownerWorkloadUri(issuance.issuanceWorkloadUri(), issuance.preAuthorizationTuple())
+ .equals(issuance.redemptionRedeemerWorkloadUri())
+ || !issuance
+ .authorizationReferenceFingerprint()
+ .equals(issuance.redemptionReferenceFingerprint())
+ || !Arrays.equals(
+ issuance.authorityEvidenceBundle(),
+ issuance.redemptionAuthorityEvidenceBundle()))) {
+ throw unavailable();
+ }
+ } catch (IllegalStateException stateFailure) {
+ throw stateFailure;
+ } catch (RuntimeException malformed) {
+ throw unavailable();
+ }
+ }
+
+ private static void validateCandidate(IssuanceCandidate candidate) {
+ Objects.requireNonNull(candidate, "issuance candidate is required");
+ StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId(
+ candidate.controlPlaneRequestId());
+ byte[] tupleBytes = requireBytes(candidate.preAuthorizationTuple(), MAX_TUPLE_BYTES, "tuple");
+ StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(tupleBytes);
+ if (!candidate.controlPlaneRequestId().equals(tuple.controlPlaneRequestId())
+ || !tuple.mutationDigest().equals(candidate.mutationDigest())) {
+ throw new IllegalArgumentException("pre-authorization tuple identity or digest mismatches");
+ }
+ requireDigest(candidate.mutationDigest());
+ String issuer = requireWorkloadUri(candidate.issuanceWorkloadUri());
+ if (!issuer.endsWith("/sa/logging-admin-service")) {
+ throw new IllegalArgumentException("StartSession issuer must be Logging/Admin workload");
+ }
+ requireNonNilUuid(candidate.reservationOwnerId(), "reservationOwnerId");
+ requirePositive(candidate.reservationClaimFence(), "reservationClaimFence");
+ requireNonNilUuid(candidate.issuanceOperationId(), "issuanceOperationId");
+ requirePositive(candidate.issuanceFence(), "issuanceFence");
+ requireBundleReference(candidate.bundleReference(), candidate.issuanceFence());
+ requireBytes(
+ candidate.authorityEvidenceBundle(), MAX_AUTHORITY_BUNDLE_BYTES, "authority bundle");
+ requireFingerprint(candidate.authorizationReferenceFingerprint());
+ requireBytes(
+ candidate.encryptedResponseEnvelope(),
+ MAX_ENCRYPTED_ENVELOPE_BYTES,
+ "encrypted response envelope");
+ Objects.requireNonNull(candidate.issuedAt(), "issue time is required");
+ Objects.requireNonNull(candidate.referenceExpiresAt(), "reference expiry is required");
+ Objects.requireNonNull(
+ candidate.responseEnvelopeExpiresAt(), "response-envelope expiry is required");
+ if (!candidate.issuedAt().isAfter(Instant.EPOCH)
+ || !candidate.referenceExpiresAt().isAfter(candidate.issuedAt())
+ || candidate.referenceExpiresAt().isAfter(candidate.issuedAt().plus(MAX_REFERENCE_LIFETIME))
+ || !candidate.responseEnvelopeExpiresAt().isAfter(candidate.referenceExpiresAt())
+ || candidate
+ .responseEnvelopeExpiresAt()
+ .isAfter(candidate.referenceExpiresAt().plus(MAX_RESPONSE_RECOVERY_WINDOW))) {
+ throw new IllegalArgumentException("authorization reference lifetime is outside its bound");
+ }
+ }
+
+ private static void validateRedemptionRequest(RedemptionRequest request) {
+ Objects.requireNonNull(request, "redemption request is required");
+ StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId(
+ request.controlPlaneRequestId());
+ byte[] tupleBytes = requireBytes(request.preAuthorizationTuple(), MAX_TUPLE_BYTES, "tuple");
+ StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(tupleBytes);
+ if (!request.controlPlaneRequestId().equals(tuple.controlPlaneRequestId())) {
+ throw new IllegalArgumentException("pre-authorization tuple request ID mismatches");
+ }
+ requireDigest(tuple.mutationDigest());
+ requireFingerprint(request.authorizationReferenceFingerprint());
+ requireNonNilUuid(request.reservationOwnerId(), "reservationOwnerId");
+ requirePositive(request.reservationClaimFence(), "reservationClaimFence");
+ String redeemer = requireWorkloadUri(request.redeemerWorkloadUri());
+ if (!redeemer.endsWith("/sa/" + tuple.targetOwner())) {
+ throw new IllegalArgumentException("redeemer workload does not match the typed target owner");
+ }
+ requireNonNilUuid(request.ownerAttemptId(), "ownerAttemptId");
+ requirePositive(request.ownerFence(), "ownerFence");
+ requireBytes(request.authorityEvidenceBundle(), MAX_AUTHORITY_BUNDLE_BYTES, "authority bundle");
+ Objects.requireNonNull(request.now(), "redemption time is required");
+ if (!request.now().isAfter(Instant.EPOCH)) {
+ throw new IllegalArgumentException("redemption time must be after the Unix epoch");
+ }
+ }
+
+ private static void requireSameOriginalBinding(
+ IssuanceCandidate candidate, IssuanceRecord original) {
+ if (!Arrays.equals(candidate.preAuthorizationTuple(), original.preAuthorizationTuple())
+ || !candidate.mutationDigest().equals(original.mutationDigest())
+ || !candidate.issuanceWorkloadUri().equals(original.issuanceWorkloadUri())
+ || !candidate.reservationOwnerId().equals(original.reservationOwnerId())
+ || candidate.reservationClaimFence() != original.reservationClaimFence()) {
+ throw conflict();
+ }
+ }
+
+ private static BundleReference bundleReference(Record row) {
+ return new BundleReference(
+ row.get("bundle_version", String.class),
+ row.get("bundle_source_version", String.class),
+ row.get("bundle_source_fence", String.class),
+ row.get("bundle_linearization", String.class));
+ }
+
+ private static void requireBundleReference(BundleReference reference, long issuanceFence) {
+ Objects.requireNonNull(reference, "original authority bundle reference is required");
+ if (!Long.toString(issuanceFence).equals(reference.sourceFence())) {
+ throw new IllegalArgumentException(
+ "original bundle source fence must equal the Account issuance fence");
+ }
+ }
+
+ private static void requireSameRedemptionBinding(
+ RedemptionRequest request, IssuanceRecord issuance) {
+ if (!Arrays.equals(request.preAuthorizationTuple(), issuance.preAuthorizationTuple())
+ || !request
+ .authorizationReferenceFingerprint()
+ .equals(issuance.authorizationReferenceFingerprint())
+ || !request.reservationOwnerId().equals(issuance.reservationOwnerId())
+ || request.reservationClaimFence() != issuance.reservationClaimFence()
+ || !Arrays.equals(request.authorityEvidenceBundle(), issuance.authorityEvidenceBundle())
+ || !request
+ .redeemerWorkloadUri()
+ .equals(
+ ownerWorkloadUri(
+ issuance.issuanceWorkloadUri(), request.preAuthorizationTuple()))) {
+ throw conflict();
+ }
+ }
+
+ private static String ownerWorkloadUri(String issuerWorkloadUri, byte[] tupleBytes) {
+ StartSessionPreAuthorizationReservationTuple tuple = decodeTuple(tupleBytes);
+ int serviceSeparator = issuerWorkloadUri.lastIndexOf("/sa/");
+ if (serviceSeparator < 0) {
+ throw unavailable();
+ }
+ return issuerWorkloadUri.substring(0, serviceSeparator) + "/sa/" + tuple.targetOwner();
+ }
+
+ private static RedemptionResult redemptionResult(IssuanceRecord issuance, boolean replay) {
+ if (issuance.status() != Status.REDEEMED
+ || !issuance
+ .authorizationReferenceFingerprint()
+ .equals(issuance.redemptionReferenceFingerprint())
+ || !Arrays.equals(
+ issuance.authorityEvidenceBundle(), issuance.redemptionAuthorityEvidenceBundle())) {
+ throw unavailable();
+ }
+ return new RedemptionResult(
+ issuance.authorizationReferenceFingerprint(),
+ issuance.redemptionAuthorityEvidenceBundle(),
+ issuance.issuanceOperationId(),
+ issuance.issuanceFence(),
+ replay);
+ }
+
+ private static StartSessionPreAuthorizationReservationTuple decodeTuple(byte[] bytes) {
+ String json = new String(bytes, StandardCharsets.UTF_8);
+ StartSessionPreAuthorizationReservationTuple tuple =
+ StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json);
+ if (!Arrays.equals(bytes, tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) {
+ throw new IllegalArgumentException("pre-authorization tuple bytes are not canonical UTF-8");
+ }
+ return tuple;
+ }
+
+ private static String requiredControlPlaneRequestId(String value) {
+ try {
+ return StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId(
+ value);
+ } catch (RuntimeException malformed) {
+ throw unavailable();
+ }
+ }
+
+ private static String requireWorkloadUri(String value) {
+ if (value == null
+ || value.length() > 256
+ || !SPIFFE_WORKLOAD_URI.matcher(value).matches()
+ || !URI.create(value).toASCIIString().equals(value)) {
+ throw new IllegalArgumentException("authenticated SPIFFE workload URI is malformed");
+ }
+ return value;
+ }
+
+ private static String requiredWorkloadUri(String value) {
+ try {
+ return requireWorkloadUri(value);
+ } catch (RuntimeException malformed) {
+ throw unavailable();
+ }
+ }
+
+ private static String optionalWorkloadUri(String value) {
+ return value == null ? null : requiredWorkloadUri(value);
+ }
+
+ private static String requireDigest(String value) {
+ if (value == null || !DIGEST.matcher(value).matches()) {
+ throw new IllegalArgumentException("mutation digest is malformed");
+ }
+ return value;
+ }
+
+ private static String requiredDigest(String value) {
+ try {
+ return requireDigest(value);
+ } catch (RuntimeException malformed) {
+ throw unavailable();
+ }
+ }
+
+ private static String requireFingerprint(String value) {
+ if (value == null || !FINGERPRINT.matcher(value).matches()) {
+ throw new IllegalArgumentException("authorization-reference fingerprint is malformed");
+ }
+ return value;
+ }
+
+ private static String requiredFingerprint(String value) {
+ try {
+ return requireFingerprint(value);
+ } catch (RuntimeException malformed) {
+ throw unavailable();
+ }
+ }
+
+ private static String optionalFingerprint(String value) {
+ return value == null ? null : requiredFingerprint(value);
+ }
+
+ private static byte[] requireBytes(byte[] value, int maximum, String field) {
+ if (value == null || value.length == 0 || value.length > maximum) {
+ throw new IllegalArgumentException(field + " bytes are missing or exceed their bound");
+ }
+ return value;
+ }
+
+ private static byte[] requiredBytes(Record row, String field, int maximum) {
+ byte[] value = row.get(field, byte[].class);
+ if (value == null || value.length == 0 || value.length > maximum) {
+ throw unavailable();
+ }
+ return value;
+ }
+
+ private static byte[] optionalBytes(Record row, String field, int maximum) {
+ byte[] value = row.get(field, byte[].class);
+ if (value == null) {
+ return null;
+ }
+ if (value.length == 0 || value.length > maximum) {
+ throw unavailable();
+ }
+ return value;
+ }
+
+ private static UUID requiredUuid(UUID value, String field) {
+ if (value == null || NIL_UUID.equals(value)) {
+ throw unavailable();
+ }
+ return value;
+ }
+
+ private static UUID optionalUuid(UUID value, String field) {
+ return value == null ? null : requiredUuid(value, field);
+ }
+
+ private static long requiredPositive(Long value, String field) {
+ if (value == null || value <= 0L) {
+ throw unavailable();
+ }
+ return value;
+ }
+
+ private static Long optionalPositive(Long value, String field) {
+ if (value == null) {
+ return null;
+ }
+ if (value <= 0L) {
+ throw unavailable();
+ }
+ return value;
+ }
+
+ private static Instant requiredInstant(OffsetDateTime value, String field) {
+ if (value == null || !value.toInstant().isAfter(Instant.EPOCH)) {
+ throw unavailable();
+ }
+ return value.toInstant();
+ }
+
+ private static Instant optionalInstant(OffsetDateTime value, String field) {
+ return value == null ? null : requiredInstant(value, field);
+ }
+
+ private static Status parseStatus(String value) {
+ try {
+ return Status.valueOf(value);
+ } catch (RuntimeException malformed) {
+ throw unavailable();
+ }
+ }
+
+ private static void requireOwnerTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException(
+ "StartSession operator authorization storage requires an active Account transaction");
+ }
+ }
+
+ private static UUID requireNonNilUuid(UUID value, String field) {
+ if (value == null || NIL_UUID.equals(value)) {
+ throw new IllegalArgumentException(field + " must be a canonical nonnil UUID");
+ }
+ return value;
+ }
+
+ private static long requirePositive(long value, String field) {
+ if (value <= 0L) {
+ throw new IllegalArgumentException(field + " must be positive");
+ }
+ return value;
+ }
+
+ private static OffsetDateTime utc(Instant instant) {
+ return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
+ }
+
+ private static IllegalStateException conflict() {
+ return new IllegalStateException(
+ "StartSession operator authorization request conflicts with its immutable binding");
+ }
+
+ private static IllegalStateException unavailable() {
+ return new IllegalStateException(
+ "Exact StartSession operator authorization evidence unavailable");
+ }
+
+ public enum Status {
+ ISSUED,
+ REDEEMED
+ }
+
+ public record CreateOrReadResult(boolean created, IssuanceRecord issuance) {
+ public CreateOrReadResult {
+ Objects.requireNonNull(issuance, "issuance record is required");
+ }
+ }
+
+ /** Candidate output fields must be created by the Account authority service, never this store. */
+ public record IssuanceCandidate(
+ String controlPlaneRequestId,
+ byte[] preAuthorizationTuple,
+ String mutationDigest,
+ String issuanceWorkloadUri,
+ UUID reservationOwnerId,
+ long reservationClaimFence,
+ UUID issuanceOperationId,
+ long issuanceFence,
+ BundleReference bundleReference,
+ byte[] authorityEvidenceBundle,
+ String authorizationReferenceFingerprint,
+ byte[] encryptedResponseEnvelope,
+ Instant issuedAt,
+ Instant referenceExpiresAt,
+ Instant responseEnvelopeExpiresAt) {
+ public IssuanceCandidate {
+ Objects.requireNonNull(bundleReference, "original authority bundle reference is required");
+ preAuthorizationTuple = copy(preAuthorizationTuple);
+ authorityEvidenceBundle = copy(authorityEvidenceBundle);
+ encryptedResponseEnvelope = copy(encryptedResponseEnvelope);
+ }
+
+ @Override
+ public byte[] preAuthorizationTuple() {
+ return copy(preAuthorizationTuple);
+ }
+
+ @Override
+ public byte[] authorityEvidenceBundle() {
+ return copy(authorityEvidenceBundle);
+ }
+
+ @Override
+ public byte[] encryptedResponseEnvelope() {
+ return copy(encryptedResponseEnvelope);
+ }
+
+ @Override
+ public String toString() {
+ return "IssuanceCandidate[controlPlaneRequestId="
+ + controlPlaneRequestId
+ + ", tuple/evidence/envelope redacted]";
+ }
+ }
+
+ /** Immutable durable row view; raw references appear only inside its encrypted envelope. */
+ public record IssuanceRecord(
+ String controlPlaneRequestId,
+ byte[] preAuthorizationTuple,
+ String mutationDigest,
+ String issuanceWorkloadUri,
+ UUID reservationOwnerId,
+ long reservationClaimFence,
+ UUID issuanceOperationId,
+ long issuanceFence,
+ BundleReference bundleReference,
+ byte[] authorityEvidenceBundle,
+ String authorizationReferenceFingerprint,
+ byte[] encryptedResponseEnvelope,
+ Instant issuedAt,
+ Instant referenceExpiresAt,
+ Instant responseEnvelopeExpiresAt,
+ Status status,
+ String redemptionRedeemerWorkloadUri,
+ UUID redemptionOwnerAttemptId,
+ Long redemptionOwnerFence,
+ Instant redeemedAt,
+ String redemptionReferenceFingerprint,
+ byte[] redemptionAuthorityEvidenceBundle) {
+ public IssuanceRecord {
+ preAuthorizationTuple = copy(preAuthorizationTuple);
+ authorityEvidenceBundle = copy(authorityEvidenceBundle);
+ encryptedResponseEnvelope = copy(encryptedResponseEnvelope);
+ redemptionAuthorityEvidenceBundle = copy(redemptionAuthorityEvidenceBundle);
+ Objects.requireNonNull(status, "status is required");
+ requireBundleReference(bundleReference, issuanceFence);
+ if (status == Status.ISSUED
+ && (redemptionRedeemerWorkloadUri != null
+ || redemptionOwnerAttemptId != null
+ || redemptionOwnerFence != null
+ || redeemedAt != null
+ || redemptionReferenceFingerprint != null
+ || redemptionAuthorityEvidenceBundle != null)) {
+ throw unavailable();
+ }
+ if (status == Status.REDEEMED
+ && (redemptionRedeemerWorkloadUri == null
+ || redemptionOwnerAttemptId == null
+ || redemptionOwnerFence == null
+ || redeemedAt == null
+ || redemptionReferenceFingerprint == null
+ || redemptionAuthorityEvidenceBundle == null)) {
+ throw unavailable();
+ }
+ }
+
+ @Override
+ public byte[] preAuthorizationTuple() {
+ return copy(preAuthorizationTuple);
+ }
+
+ @Override
+ public byte[] authorityEvidenceBundle() {
+ return copy(authorityEvidenceBundle);
+ }
+
+ @Override
+ public byte[] encryptedResponseEnvelope() {
+ return copy(encryptedResponseEnvelope);
+ }
+
+ @Override
+ public byte[] redemptionAuthorityEvidenceBundle() {
+ return copy(redemptionAuthorityEvidenceBundle);
+ }
+
+ @Override
+ public String toString() {
+ return "IssuanceRecord[controlPlaneRequestId="
+ + controlPlaneRequestId
+ + ", status="
+ + status
+ + ", tuple/evidence/envelope redacted]";
+ }
+ }
+
+ public record RedemptionRequest(
+ String controlPlaneRequestId,
+ byte[] preAuthorizationTuple,
+ String authorizationReferenceFingerprint,
+ UUID reservationOwnerId,
+ long reservationClaimFence,
+ String redeemerWorkloadUri,
+ UUID ownerAttemptId,
+ long ownerFence,
+ byte[] authorityEvidenceBundle,
+ Instant now) {
+ public RedemptionRequest {
+ preAuthorizationTuple = copy(preAuthorizationTuple);
+ authorityEvidenceBundle = copy(authorityEvidenceBundle);
+ }
+
+ @Override
+ public byte[] preAuthorizationTuple() {
+ return copy(preAuthorizationTuple);
+ }
+
+ @Override
+ public byte[] authorityEvidenceBundle() {
+ return copy(authorityEvidenceBundle);
+ }
+
+ @Override
+ public String toString() {
+ return "RedemptionRequest[controlPlaneRequestId="
+ + controlPlaneRequestId
+ + ", tuple/evidence redacted]";
+ }
+ }
+
+ /** The one-time result contains authority projection only; it never contains the opaque ref. */
+ public record RedemptionResult(
+ String authorizationReferenceFingerprint,
+ byte[] authorityEvidenceBundle,
+ UUID issuanceOperationId,
+ long issuanceFence,
+ boolean replay) {
+ public RedemptionResult {
+ authorityEvidenceBundle = copy(authorityEvidenceBundle);
+ }
+
+ @Override
+ public byte[] authorityEvidenceBundle() {
+ return copy(authorityEvidenceBundle);
+ }
+
+ @Override
+ public String toString() {
+ return "RedemptionResult[issuanceOperationId="
+ + issuanceOperationId
+ + ", replay="
+ + replay
+ + ", authority bundle redacted]";
+ }
+ }
+
+ public static final class ReferenceExpiredException extends IllegalStateException {
+ private ReferenceExpiredException() {
+ super("StartSession operator authorization reference is expired");
+ }
+ }
+
+ private static byte[] copy(byte[] value) {
+ return value == null ? null : value.clone();
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java
new file mode 100644
index 0000000000..8c6bea6cd2
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptor.java
@@ -0,0 +1,73 @@
+package net.firedevops.firemud.accountservice.security;
+
+import io.grpc.Context;
+import io.grpc.Contexts;
+import io.grpc.Grpc;
+import io.grpc.Metadata;
+import io.grpc.ServerCall;
+import io.grpc.ServerCallHandler;
+import io.grpc.ServerInterceptor;
+import io.grpc.Status;
+import java.util.Optional;
+import java.util.function.Supplier;
+import javax.net.ssl.SSLPeerUnverifiedException;
+import javax.net.ssl.SSLSession;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/** Service-local certificate identity gate for only the JWT signer materialization RPCs. */
+@Component("accountJwtSignerMaterializerTlsInterceptor")
+public final class AccountJwtSignerMaterializerTlsInterceptor implements ServerInterceptor {
+ private static final Context.Key AUTHENTICATED_BINDING =
+ Context.key("account-jwt-signer-materializer-trust-binding");
+
+ private final Supplier> trustBindingProvider;
+
+ @Autowired
+ public AccountJwtSignerMaterializerTlsInterceptor(
+ AccountJwtSignerMaterializerTrustBinding trustBindingProvider) {
+ this(trustBindingProvider::current);
+ }
+
+ AccountJwtSignerMaterializerTlsInterceptor(Supplier> trustBindingProvider) {
+ this.trustBindingProvider = trustBindingProvider;
+ }
+
+ @Override
+ public ServerCall.Listener interceptCall(
+ ServerCall call, Metadata headers, ServerCallHandler next) {
+ Optional current = trustBindingProvider.get();
+ if (current.isEmpty()) {
+ return deny(call, "JWT materializer trust binding is unavailable");
+ }
+ SSLSession sslSession = call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION);
+ if (sslSession == null) {
+ return deny(call, "Authenticated JWT materializer workload is required");
+ }
+ Binding binding = current.orElseThrow();
+ java.security.cert.Certificate[] peerCertificates;
+ try {
+ peerCertificates = sslSession.getPeerCertificates();
+ } catch (SSLPeerUnverifiedException ex) {
+ return deny(call, "Authenticated JWT materializer workload is required");
+ }
+ if (!AccountJwtSignerMaterializerTrustBinding.matchesPeer(peerCertificates, binding)) {
+ return deny(call, "Authenticated JWT materializer workload is required");
+ }
+ Context authenticated = Context.current().withValue(AUTHENTICATED_BINDING, binding);
+ return Contexts.interceptCall(authenticated, call, headers, next);
+ }
+
+ /** The service re-reads protected configuration and rejects a changed snapshot before storage. */
+ public static Binding authenticatedBinding() {
+ return AUTHENTICATED_BINDING.get();
+ }
+
+ private static ServerCall.Listener deny(
+ ServerCall call, String description) {
+ call.close(Status.PERMISSION_DENIED.withDescription(description), new Metadata());
+ return new ServerCall.Listener<>() {};
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java
new file mode 100644
index 0000000000..b94bc0762f
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java
@@ -0,0 +1,739 @@
+package net.firedevops.firemud.accountservice.service.impl;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.stub.StreamObserver;
+import java.sql.SQLException;
+import java.util.UUID;
+import net.firedevops.firemud.account.v1.AccountJwtSignerMaterializationServiceGrpc;
+import net.firedevops.firemud.account.v1.ActiveSigner;
+import net.firedevops.firemud.account.v1.EnrollBootstrapRequest;
+import net.firedevops.firemud.account.v1.EnrollBootstrapResponse;
+import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestRequest;
+import net.firedevops.firemud.account.v1.GetCurrentGenerationRequestResponse;
+import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestRequest;
+import net.firedevops.firemud.account.v1.GetCurrentPromotionRequestResponse;
+import net.firedevops.firemud.account.v1.PromotionPublicKeyIdentity;
+import net.firedevops.firemud.account.v1.RecordGenerationResultRequest;
+import net.firedevops.firemud.account.v1.RecordGenerationResultResponse;
+import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultRequest;
+import net.firedevops.firemud.account.v1.RecordPrivatePromotionResultResponse;
+import net.firedevops.firemud.account.v1.RecordSecretObservationRequest;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding;
+import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionObservation;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PublicKeyIdentity;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence;
+import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.BootstrapOperationException;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtSignerBootstrapCoordinator.Stage;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose;
+import org.jooq.exception.DataAccessException;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataAccessResourceFailureException;
+import org.springframework.grpc.server.service.GrpcService;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Narrow Account-owned operation handoff to the interim mounted-key materializer.
+ *
+ * The exact peer can read Account-selected fixed-Secret generation and PREPARED promotion
+ * operations, report readbacks, and submit public key identities. It cannot select an operation,
+ * environment, resource, generation, or {@code kid}; submit private material; publish JWKS; commit
+ * the Account signer lifecycle; sign tokens; or establish readiness.
+ */
+@GrpcService(
+ interceptorNames = "accountJwtSignerMaterializerTlsInterceptor",
+ blendWithGlobalInterceptors = false)
+public class AccountJwtSignerMaterializationService
+ extends AccountJwtSignerMaterializationServiceGrpc
+ .AccountJwtSignerMaterializationServiceImplBase {
+ private final AccountJwtSignerDesiredStateRepository repository;
+ private final AccountJwtReadinessProbeRepository readinessRepository;
+ private final AccountJwtSignerMaterializerTrustBinding trustBindingProvider;
+ private final TransactionTemplate accountTransaction;
+ private final ObjectProvider bootstrapCoordinatorProvider;
+ private final ObjectProvider validatorInventorySourceProvider;
+
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification =
+ "Spring injects the same owner repositories into this gRPC adapter so lifecycle validation and persistence share the Account authority and transaction boundary.")
+ @Autowired
+ public AccountJwtSignerMaterializationService(
+ AccountJwtSignerDesiredStateRepository repository,
+ AccountJwtReadinessProbeRepository readinessRepository,
+ AccountJwtSignerMaterializerTrustBinding trustBindingProvider,
+ PlatformTransactionManager transactionManager,
+ ObjectProvider bootstrapCoordinatorProvider,
+ ObjectProvider validatorInventorySourceProvider) {
+ this.repository = repository;
+ this.readinessRepository = readinessRepository;
+ this.trustBindingProvider = trustBindingProvider;
+ this.bootstrapCoordinatorProvider = bootstrapCoordinatorProvider;
+ this.validatorInventorySourceProvider = validatorInventorySourceProvider;
+ this.accountTransaction = new TransactionTemplate(transactionManager);
+ this.accountTransaction.setReadOnly(false);
+ }
+
+ /**
+ * Retains the narrow unit-test construction path when optional bootstrap composition is absent.
+ */
+ public AccountJwtSignerMaterializationService(
+ AccountJwtSignerDesiredStateRepository repository,
+ AccountJwtReadinessProbeRepository readinessRepository,
+ AccountJwtSignerMaterializerTrustBinding trustBindingProvider,
+ PlatformTransactionManager transactionManager) {
+ this(repository, readinessRepository, trustBindingProvider, transactionManager, null, null);
+ }
+
+ @Override
+ public void enrollBootstrap(
+ EnrollBootstrapRequest request, StreamObserver responseObserver) {
+ try {
+ validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty());
+ Binding binding = requireCurrentAuthenticatedBinding();
+ AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator();
+ if (coordinator == null) {
+ throw Status.FAILED_PRECONDITION
+ .withDescription("Account JWT signer bootstrap is not enabled")
+ .asRuntimeException();
+ }
+ AccountJwtSignerBootstrapCoordinator.EnrollmentAcknowledgement acknowledgement =
+ coordinator.enrollOnce();
+ requireUnchangedTrustBinding(binding);
+ responseObserver.onNext(toEnrollmentResponse(acknowledgement));
+ responseObserver.onCompleted();
+ } catch (RuntimeException ex) {
+ responseObserver.onError(statusFor(ex).asRuntimeException());
+ }
+ }
+
+ @Override
+ public void getCurrentGenerationRequest(
+ GetCurrentGenerationRequestRequest request,
+ StreamObserver responseObserver) {
+ try {
+ validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty());
+ Binding binding = requireCurrentAuthenticatedBinding();
+ GenerationRequest current =
+ accountTransaction.execute(
+ status -> {
+ GenerationRequest requested =
+ repository.ensureCurrentGenerationRequest(
+ binding.accountBinding(), trustFence(binding));
+ requireUnchangedTrustBinding(binding);
+ return requested;
+ });
+ if (current == null) {
+ throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException(
+ "JWT signer generation request is unavailable");
+ }
+ requireUnchangedTrustBinding(binding);
+ if (current.phase() == GenerationPhase.GENERATION_RECORDED) {
+ AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator();
+ if (coordinator != null) {
+ var progress = coordinator.reconcileCurrentGenerationOnce(current.operationId());
+ requireUnchangedTrustBinding(binding);
+ if (progress.stage() != Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE) {
+ throw Status.FAILED_PRECONDITION
+ .withDescription(
+ "Account signer generation is durable but publication or mount reconciliation is incomplete")
+ .asRuntimeException();
+ }
+ }
+ }
+ responseObserver.onNext(toRequestResponse(current));
+ responseObserver.onCompleted();
+ } catch (RuntimeException ex) {
+ responseObserver.onError(statusFor(ex).asRuntimeException());
+ }
+ }
+
+ @Override
+ public void recordSecretObservation(
+ RecordSecretObservationRequest request,
+ StreamObserver responseObserver) {
+ try {
+ validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty());
+ UUID operationId = parseOperationId(request.getOperationId());
+ Binding binding = requireCurrentAuthenticatedBinding();
+ GenerationRequest current =
+ accountTransaction.execute(
+ status -> {
+ GenerationRequest observed =
+ repository.recordSecretObservation(
+ binding.accountBinding(),
+ trustFence(binding),
+ operationId,
+ request.getOperationDigest(),
+ request.getSecretUid(),
+ request.getObservedResourceVersion());
+ requireUnchangedTrustBinding(binding);
+ return observed;
+ });
+ if (current == null) {
+ throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException(
+ "JWT signer Secret observation is unavailable");
+ }
+ requireUnchangedTrustBinding(binding);
+ responseObserver.onNext(toRequestResponse(current));
+ responseObserver.onCompleted();
+ } catch (RuntimeException ex) {
+ responseObserver.onError(statusFor(ex).asRuntimeException());
+ }
+ }
+
+ @Override
+ public void recordGenerationResult(
+ RecordGenerationResultRequest request,
+ StreamObserver responseObserver) {
+ try {
+ validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty());
+ UUID operationId = parseOperationId(request.getOperationId());
+ Binding binding = requireCurrentAuthenticatedBinding();
+ GenerationResult result =
+ accountTransaction.execute(
+ status -> {
+ GenerationResult persisted =
+ repository.recordGenerationResult(
+ binding.accountBinding(),
+ trustFence(binding),
+ operationId,
+ request.getGenerationRequestDigest(),
+ request.getSecretUid(),
+ request.getExpectedPriorResourceVersion(),
+ request.getObservedResourceVersion(),
+ request.getPublicJwkJson());
+ requireUnchangedTrustBinding(binding);
+ return persisted;
+ });
+ if (result == null) {
+ throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException(
+ "JWT signer generation receipt is unavailable");
+ }
+ requireUnchangedTrustBinding(binding);
+ responseObserver.onNext(toResultResponse(result));
+ responseObserver.onCompleted();
+ } catch (RuntimeException ex) {
+ responseObserver.onError(statusFor(ex).asRuntimeException());
+ }
+ }
+
+ /** Returns only the exact Account PREPARED operation for fixed-Secret reconciliation. */
+ @Override
+ public void getCurrentPromotionRequest(
+ GetCurrentPromotionRequestRequest request,
+ StreamObserver responseObserver) {
+ try {
+ validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty());
+ Binding binding = requireCurrentAuthenticatedBinding();
+ requireValidatorInventorySourceAvailable();
+ PreparedGenerationEvidence preparedForObservation;
+ try {
+ preparedForObservation =
+ accountTransaction.execute(
+ status ->
+ repository.readPreparedGenerationForRecovery(
+ binding.accountBinding(), trustFence(binding)));
+ } catch (AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException notPrepared) {
+ AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator();
+ if (coordinator == null) {
+ throw new AccountJwtSignerDesiredStateRepository
+ .PromotionPrerequisitesIncompleteException(
+ "Account has no complete owner-verified promotion proof");
+ }
+ if (coordinator.prepareCurrentPromotionOnce().isEmpty()) {
+ if (ownerConfirmsNoPromotionReadyYet(binding)) {
+ throw new AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException();
+ }
+ throw new AccountJwtSignerDesiredStateRepository
+ .PromotionPrerequisitesIncompleteException(
+ "Account has no complete owner-verified promotion proof");
+ }
+ preparedForObservation =
+ accountTransaction.execute(
+ status ->
+ repository.readPreparedGenerationForRecovery(
+ binding.accountBinding(), trustFence(binding)));
+ }
+ if (preparedForObservation == null) {
+ throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException(
+ "Prepared Account signer operation is unavailable");
+ }
+ ObservationContext observationContext = observationContext(preparedForObservation);
+ // The first PREPARED attempt refreshed ConfigMap and mounted evidence, then sampled the
+ // protected inventory before its PREPARED transaction. Reobserve here for the dispatch fence;
+ // recovery of an existing PREPARED operation also gets this independent live recheck.
+ InventorySnapshot liveInventory = observeCurrentValidatorInventory(observationContext);
+ requireUnchangedTrustBinding(binding);
+ PreparedGenerationEvidence prepared =
+ accountTransaction.execute(
+ status -> {
+ PreparedGenerationEvidence current =
+ repository.readPreparedGenerationForRecovery(
+ binding.accountBinding(), trustFence(binding));
+ if (!observationContext.equals(observationContext(current))) {
+ throw new AccountJwtSignerDesiredStateRepository
+ .PromotionPrerequisitesIncompleteException(
+ "Prepared signer operation changed during validator inventory proof");
+ }
+ boolean completeProof =
+ readinessRepository
+ .readPromotionProof(
+ binding.accountBinding(),
+ trustFence(binding),
+ current.promotion().generationOperationId(),
+ liveInventory)
+ .isPresent();
+ if (!completeProof) {
+ throw new AccountJwtSignerDesiredStateRepository
+ .PromotionPrerequisitesIncompleteException(
+ "Complete Account readiness proof is unavailable");
+ }
+ PreparedGenerationEvidence evidence =
+ repository.readAndMarkPreparedPromotionDispatched(
+ binding.accountBinding(), trustFence(binding));
+ requireUnchangedTrustBinding(binding);
+ return evidence;
+ });
+ if (prepared == null) {
+ throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException(
+ "JWT signer promotion request is unavailable");
+ }
+ requireUnchangedTrustBinding(binding);
+ responseObserver.onNext(toPromotionRequestResponse(prepared));
+ responseObserver.onCompleted();
+ } catch (RuntimeException ex) {
+ responseObserver.onError(statusFor(ex).asRuntimeException());
+ }
+ }
+
+ /** Records Account's public-identity-only readback of the exact fixed-Secret CAS. */
+ @Override
+ public void recordPrivatePromotionResult(
+ RecordPrivatePromotionResultRequest request,
+ StreamObserver responseObserver) {
+ try {
+ validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty());
+ if (request.hasCurrent() == false
+ || request.getCurrent().getUnknownFields().asMap().isEmpty() == false
+ || (request.hasPrevious()
+ && request.getPrevious().getUnknownFields().asMap().isEmpty() == false)) {
+ throw new IllegalArgumentException("Promotion result identity is malformed");
+ }
+ UUID promotionOperationId = parseOperationId(request.getPromotionOperationId());
+ UUID generationOperationId = parseOperationId(request.getGenerationOperationId());
+ Binding binding = requireCurrentAuthenticatedBinding();
+ PrivatePromotionObservation observation =
+ new PrivatePromotionObservation(
+ promotionOperationId,
+ request.getPromotionRequestDigest(),
+ generationOperationId,
+ request.getGenerationOperationDigest(),
+ request.getSecretUid(),
+ request.getExpectedPriorResourceVersion(),
+ request.getObservedResourceVersion(),
+ publicIdentity(request.getCurrent()),
+ request.hasPrevious()
+ ? java.util.Optional.of(publicIdentity(request.getPrevious()))
+ : java.util.Optional.empty(),
+ request.getResultingSlotsList());
+ PrivatePromotionReceipt receipt =
+ accountTransaction.execute(
+ status -> {
+ PrivatePromotionReceipt persisted =
+ repository.recordPrivatePromotionResult(
+ binding.accountBinding(), trustFence(binding), observation);
+ requireUnchangedTrustBinding(binding);
+ return persisted;
+ });
+ if (receipt == null) {
+ throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException(
+ "JWT signer private promotion receipt is unavailable");
+ }
+ requireUnchangedTrustBinding(binding);
+ AccountJwtSignerBootstrapCoordinator coordinator = currentBootstrapCoordinator();
+ if (coordinator == null) {
+ throw Status.FAILED_PRECONDITION
+ .withDescription("Account JWT signer reconciliation is not enabled")
+ .asRuntimeException();
+ }
+ coordinator.reconcilePreparedPromotionOnce(observation, receipt);
+ requireUnchangedTrustBinding(binding);
+ responseObserver.onNext(
+ RecordPrivatePromotionResultResponse.newBuilder()
+ .setSchemaVersion(1)
+ .setPromotionOperationId(receipt.promotionOperationId().toString())
+ .setGenerationOperationId(receipt.generationOperationId().toString())
+ .setObservedResourceVersion(receipt.observedResourceVersion())
+ .setPublicReceiptDigest(receipt.receiptDigest())
+ .build());
+ responseObserver.onCompleted();
+ } catch (RuntimeException ex) {
+ responseObserver.onError(statusFor(ex).asRuntimeException());
+ }
+ }
+
+ private Binding requireCurrentAuthenticatedBinding() {
+ Binding authenticated = AccountJwtSignerMaterializerTlsInterceptor.authenticatedBinding();
+ Binding current = trustBindingProvider.current().orElse(null);
+ if (authenticated == null || current == null || !authenticated.equals(current)) {
+ throw Status.PERMISSION_DENIED
+ .withDescription("Authenticated JWT materializer workload is required")
+ .asRuntimeException();
+ }
+ return current;
+ }
+
+ private AccountJwtSignerBootstrapCoordinator currentBootstrapCoordinator() {
+ return bootstrapCoordinatorProvider == null
+ ? null
+ : bootstrapCoordinatorProvider.getIfAvailable();
+ }
+
+ private InventorySnapshot observeCurrentValidatorInventory(
+ ObservationContext observationContext) {
+ AccountJwtValidatorInventorySource source = currentValidatorInventorySource();
+ try {
+ return source.observe(observationContext);
+ } catch (AccountJwtValidatorInventorySource.InventoryUnavailableException failure) {
+ throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException(
+ "Protected live validator inventory is unavailable");
+ }
+ }
+
+ private static ObservationContext observationContext(
+ PreparedGenerationEvidence preparedGeneration) {
+ if (preparedGeneration == null) {
+ throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException(
+ "Prepared Account generation evidence is unavailable");
+ }
+ var promotion = preparedGeneration.promotion();
+ if (!promotion.expectedPreviousActive().equals(promotion.expectedPublishedActive())) {
+ throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException(
+ "Prepared Account active signer fence is inconsistent");
+ }
+ return new ObservationContext(
+ promotion.expectedPreviousActive().isEmpty()
+ ? ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES
+ : ObservationPurpose.STRICT_READY,
+ promotion.generationOperationId(),
+ promotion.generationOperationDigest());
+ }
+
+ private void requireValidatorInventorySourceAvailable() {
+ if (currentValidatorInventorySource() == null) {
+ throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException(
+ "Protected live validator inventory is unavailable");
+ }
+ }
+
+ private AccountJwtValidatorInventorySource currentValidatorInventorySource() {
+ return validatorInventorySourceProvider == null
+ ? null
+ : validatorInventorySourceProvider.getIfAvailable();
+ }
+
+ private void requireUnchangedTrustBinding(Binding expected) {
+ if (trustBindingProvider.current().filter(expected::equals).isEmpty()) {
+ throw Status.PERMISSION_DENIED
+ .withDescription("JWT materializer trust binding changed during the request")
+ .asRuntimeException();
+ }
+ }
+
+ private boolean ownerConfirmsNoPromotionReadyYet(Binding binding) {
+ requireUnchangedTrustBinding(binding);
+ DesiredState state =
+ accountTransaction.execute(status -> repository.read(binding.accountBinding()));
+ requireUnchangedTrustBinding(binding);
+ if (state == null || state.enrollmentIdentity().isEmpty()) {
+ return false;
+ }
+ EnrollmentIdentity enrollment = state.enrollmentIdentity().orElseThrow();
+ TrustFence currentTrust = trustFence(binding);
+ if (!enrollment
+ .expectedClusterIncarnationUid()
+ .equals(currentTrust.expectedClusterIncarnationUid())
+ || !enrollment.expectedNamespaceUid().equals(currentTrust.expectedNamespaceUid())
+ || !enrollment.materializerTrustBindingDigest().equals(currentTrust.bindingDigest())
+ || !enrollment.materializerTrustConfigRevision().equals(currentTrust.configRevision())
+ || state.preparedOperationId().isPresent()) {
+ return false;
+ }
+ if (state.generationOperationId().isEmpty()) {
+ boolean unselectedInitialEnrollment =
+ state.recordVersion() == 1
+ && state.durableActive().isEmpty()
+ && state.publishedActive().isEmpty();
+ requireUnchangedTrustBinding(binding);
+ return unselectedInitialEnrollment;
+ }
+ GenerationRequest current =
+ accountTransaction.execute(
+ status ->
+ repository.readCurrentGenerationRequest(binding.accountBinding(), currentTrust));
+ requireUnchangedTrustBinding(binding);
+ return current != null
+ && (current.phase() == GenerationPhase.OBSERVE_PRIVATE_SECRET
+ || current.phase() == GenerationPhase.GENERATE_PENDING);
+ }
+
+ private static TrustFence trustFence(Binding binding) {
+ return new TrustFence(
+ binding.expectedClusterIncarnationUid(),
+ binding.expectedNamespaceUid(),
+ binding.bindingDigest(),
+ binding.configRevision());
+ }
+
+ private static GetCurrentGenerationRequestResponse toRequestResponse(GenerationRequest request) {
+ GetCurrentGenerationRequestResponse.Builder response =
+ GetCurrentGenerationRequestResponse.newBuilder()
+ .setSchemaVersion(1)
+ .setPhase(toWirePhase(request.phase()))
+ .setOperationId(request.operationId().toString())
+ .setOperationDigest(request.operationDigest())
+ .setGenerationRequestDigest(request.generationRequestDigest())
+ .setDesiredStateVersion(Long.toString(request.desiredStateVersion()))
+ .setEnvironmentId(request.binding().environmentId())
+ .setClusterId(request.binding().clusterId())
+ .setNamespace(request.binding().namespace())
+ .setExpectedClusterIncarnationUid(request.trustFence().expectedClusterIncarnationUid())
+ .setExpectedNamespaceUid(request.trustFence().expectedNamespaceUid())
+ .setTrustBindingDigest(request.trustFence().bindingDigest())
+ .setTrustConfigRevision(request.trustFence().configRevision())
+ .setPrivateSecretName(request.privateSecretName())
+ .setTargetGeneration(request.targetGeneration())
+ .setTargetKid(request.targetKid())
+ .setTargetAlgorithm(request.targetAlgorithm())
+ .setOperationAction(request.operationAction())
+ .addAllAllowedPrivateSlots(request.allowedPrivateSlots())
+ .setSecretUid(request.secretUid())
+ .setExpectedSecretResourceVersion(request.expectedSecretResourceVersion())
+ .setGenerationReceiptDigest(request.generationReceiptDigest())
+ .setPublicKeyFingerprint(request.publicKeyFingerprint())
+ .setPublicJwkJson(request.publicJwkJson())
+ .setObservedSecretResourceVersion(request.observedSecretResourceVersion());
+ request.expectedActive().ifPresent(active -> response.setExpectedActive(toWireActive(active)));
+ request
+ .expectedPublishedActive()
+ .ifPresent(active -> response.setExpectedPublishedActive(toWireActive(active)));
+ return response.build();
+ }
+
+ private static EnrollBootstrapResponse toEnrollmentResponse(
+ AccountJwtSignerBootstrapCoordinator.EnrollmentAcknowledgement acknowledgement) {
+ return EnrollBootstrapResponse.newBuilder()
+ .setSchemaVersion(1)
+ .setEnvironmentId(acknowledgement.environmentId())
+ .setClusterId(acknowledgement.clusterId())
+ .setNamespace(acknowledgement.namespace())
+ .setExpectedClusterIncarnationUid(acknowledgement.expectedClusterIncarnationUid())
+ .setExpectedNamespaceUid(acknowledgement.expectedNamespaceUid())
+ .setMaterializerTrustBindingDigest(acknowledgement.materializerTrustBindingDigest())
+ .setMaterializerTrustConfigRevision(acknowledgement.materializerTrustConfigRevision())
+ .setApiBindingDigest(acknowledgement.apiBindingDigest())
+ .setApiConfigRevision(acknowledgement.apiConfigRevision())
+ .setApiServerUrl(acknowledgement.apiServerUrl())
+ .setApiTlsServerName(acknowledgement.apiTlsServerName())
+ .setApiServingCaSha256(acknowledgement.apiServingCaSha256())
+ .setApiExpectedUsername(acknowledgement.apiExpectedUsername())
+ .setPrivateSecretName(acknowledgement.privateSecretName())
+ .setPublicConfigMapName(acknowledgement.publicConfigMapName())
+ .setPublicConfigMapUid(acknowledgement.publicConfigMapUid())
+ .setPublicConfigMapResourceVersion(acknowledgement.publicConfigMapResourceVersion())
+ .setPublicConfigMapSnapshotDigest(acknowledgement.publicConfigMapSnapshotDigest())
+ .build();
+ }
+
+ private static ActiveSigner toWireActive(
+ AccountJwtSignerDesiredStateRepository.ActiveSigner active) {
+ return ActiveSigner.newBuilder()
+ .setGeneration(active.generation())
+ .setKid(active.kid())
+ .build();
+ }
+
+ private static GetCurrentGenerationRequestResponse.Phase toWirePhase(GenerationPhase phase) {
+ return switch (phase) {
+ case OBSERVE_PRIVATE_SECRET ->
+ GetCurrentGenerationRequestResponse.Phase.OBSERVE_PRIVATE_SECRET;
+ case GENERATE_PENDING -> GetCurrentGenerationRequestResponse.Phase.GENERATE_PENDING;
+ case GENERATION_RECORDED -> GetCurrentGenerationRequestResponse.Phase.GENERATION_RECORDED;
+ };
+ }
+
+ private static RecordGenerationResultResponse toResultResponse(GenerationResult result) {
+ return RecordGenerationResultResponse.newBuilder()
+ .setSchemaVersion(1)
+ .setOperationId(result.operationId().toString())
+ .setOperationDigest(result.operationDigest())
+ .setGenerationRequestDigest(result.generationRequestDigest())
+ .setGenerationReceiptDigest(result.receiptDigest())
+ .setDesiredStateVersion(Long.toString(result.desiredStateVersion()))
+ .setEnvironmentId(result.binding().environmentId())
+ .setClusterId(result.binding().clusterId())
+ .setNamespace(result.binding().namespace())
+ .setExpectedClusterIncarnationUid(result.trustFence().expectedClusterIncarnationUid())
+ .setExpectedNamespaceUid(result.trustFence().expectedNamespaceUid())
+ .setTrustBindingDigest(result.trustFence().bindingDigest())
+ .setTrustConfigRevision(result.trustFence().configRevision())
+ .setPrivateSecretName(result.privateSecretName())
+ .setSecretUid(result.secretUid())
+ .setExpectedPriorResourceVersion(result.expectedPriorResourceVersion())
+ .setObservedResourceVersion(result.observedResourceVersion())
+ .setTargetGeneration(result.targetGeneration())
+ .setTargetKid(result.targetKid())
+ .setTargetAlgorithm(result.targetAlgorithm())
+ .setPublicKeyFingerprint(result.publicKeyFingerprint())
+ .setPublicJwkJson(result.publicJwkJson())
+ .build();
+ }
+
+ private static GetCurrentPromotionRequestResponse toPromotionRequestResponse(
+ PreparedGenerationEvidence prepared) {
+ var promotion = prepared.promotion();
+ var generation = prepared.generationResult();
+ GetCurrentPromotionRequestResponse.Builder response =
+ GetCurrentPromotionRequestResponse.newBuilder()
+ .setSchemaVersion(1)
+ .setPromotionOperationId(promotion.operationId().toString())
+ .setPromotionRequestDigest(promotion.requestDigest())
+ .setGenerationOperationId(generation.operationId().toString())
+ .setGenerationOperationDigest(generation.operationDigest())
+ .setGenerationReceiptDigest(generation.receiptDigest())
+ .setEnvironmentId(promotion.binding().environmentId())
+ .setClusterId(promotion.binding().clusterId())
+ .setNamespace(promotion.binding().namespace())
+ .setExpectedClusterIncarnationUid(
+ promotion.trustFence().expectedClusterIncarnationUid())
+ .setExpectedNamespaceUid(promotion.trustFence().expectedNamespaceUid())
+ .setTrustBindingDigest(promotion.trustFence().bindingDigest())
+ .setTrustConfigRevision(promotion.trustFence().configRevision())
+ .setPrivateSecretName(AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME)
+ .setTargetGeneration(promotion.targetGeneration())
+ .setTargetKid(promotion.targetKid())
+ .setTargetAlgorithm(promotion.targetAlgorithm())
+ .setTargetPublicKeyFingerprint(promotion.targetPublicKeyFingerprint())
+ .setExpectedSecretUid(promotion.secretUid())
+ .setExpectedSecretResourceVersion(promotion.expectedPrivateResourceVersion())
+ .setOperationAction("PROMOTE_PENDING")
+ .addAllowedPrivateSlots("current.key")
+ .addAllowedPrivateSlots("pending.key")
+ .addAllowedPrivateSlots("previous.key");
+ promotion
+ .expectedPreviousActive()
+ .ifPresent(
+ previous -> {
+ response.setExpectedPreviousGeneration(previous.generation());
+ response.setExpectedPreviousKid(previous.kid());
+ response.setExpectedPreviousPublicKeyFingerprint(
+ promotion.expectedPreviousPublicKeyFingerprint().orElseThrow());
+ });
+ return response.build();
+ }
+
+ private static PublicKeyIdentity publicIdentity(PromotionPublicKeyIdentity identity) {
+ return new PublicKeyIdentity(
+ identity.getGeneration(), identity.getKid(), identity.getPublicKeyFingerprint());
+ }
+
+ private static void validateRequest(int schemaVersion, boolean unknownFieldsEmpty) {
+ if (schemaVersion != 1 || !unknownFieldsEmpty) {
+ throw Status.INVALID_ARGUMENT
+ .withDescription("Exact JWT materialization request schema is required")
+ .asRuntimeException();
+ }
+ }
+
+ private static UUID parseOperationId(String value) {
+ try {
+ UUID operationId = UUID.fromString(value);
+ if (operationId.version() != 4 || !operationId.toString().equals(value)) {
+ throw new IllegalArgumentException("UUIDv4 required");
+ }
+ return operationId;
+ } catch (RuntimeException ex) {
+ throw Status.INVALID_ARGUMENT
+ .withDescription("JWT signer operation ID must be canonical UUIDv4")
+ .asRuntimeException();
+ }
+ }
+
+ private static Status statusFor(RuntimeException exception) {
+ if (exception instanceof StatusRuntimeException statusException) {
+ return statusException.getStatus();
+ }
+ if (exception instanceof IllegalArgumentException) {
+ return Status.INVALID_ARGUMENT.withDescription("JWT materialization request is malformed");
+ }
+ if (exception instanceof AccountJwtSignerDesiredStateRepository.IdempotencyConflictException) {
+ return Status.ALREADY_EXISTS.withDescription(
+ "JWT materialization operation or public result conflicts with retained Account evidence");
+ }
+ if (exception instanceof BootstrapOperationException) {
+ return Status.FAILED_PRECONDITION.withDescription(
+ "Account JWT signer bootstrap enrollment is quarantined");
+ }
+ if (exception instanceof AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException) {
+ return Status.NOT_FOUND.withDescription("No Account-authorized signer promotion is pending");
+ }
+ if (exception instanceof AccountJwtSignerDesiredStateRepository.StorageUnavailableException
+ || exception instanceof DataAccessResourceFailureException
+ || hasConnectionFailure(exception)) {
+ return Status.UNAVAILABLE.withDescription(
+ "Account JWT materialization storage is unavailable");
+ }
+ if (exception instanceof AccountJwtSignerDesiredStateRepository.MissingDesiredStateException
+ || exception
+ instanceof AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException
+ || exception
+ instanceof AccountJwtSignerDesiredStateRepository.MissingGenerationObservationException
+ || exception
+ instanceof AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException
+ || exception instanceof AccountJwtSignerDesiredStateRepository.BindingMismatchException
+ || exception instanceof AccountJwtSignerDesiredStateRepository.VersionConflictException
+ || exception instanceof AccountJwtSignerDesiredStateRepository.QuarantinedStateException
+ || exception
+ instanceof
+ AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException) {
+ return Status.FAILED_PRECONDITION.withDescription(
+ "No exact current Account JWT signer generation phase is available");
+ }
+ if (exception instanceof DataAccessException) {
+ return Status.INTERNAL.withDescription(
+ "Account JWT generation evidence could not be recorded");
+ }
+ return Status.INTERNAL.withDescription("Account JWT materialization could not be completed");
+ }
+
+ private static boolean hasConnectionFailure(Throwable failure) {
+ for (Throwable current = failure; current != null; current = current.getCause()) {
+ if (current instanceof SQLException sqlException) {
+ String state = sqlException.getSQLState();
+ if (state != null && state.startsWith("08")) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java
index b3218042c6..15f6f65935 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java
@@ -1961,6 +1961,47 @@ private Optional findAccountForAuthentication(String usernameOrEmail) {
return accountRepository.findByUsername(usernameOrEmail);
}
+ /**
+ * Explicit internal control-ui owner hook. It performs real primary authentication and consumes
+ * the exact OTP in the caller's writable issuance transaction; it issues no token or session. The
+ * owner must catch primary credential denial inside that transaction so failed-attempt accounting
+ * commits, then report the denial outside it. Successful OTP consumption remains rollback-capable
+ * when later issuance preparation fails.
+ */
+ @Transactional(
+ propagation = org.springframework.transaction.annotation.Propagation.MANDATORY,
+ noRollbackFor = AuthenticationException.class)
+ public ControlUiPrimaryIdentity authenticateControlUiPrimaryIdentity(
+ String email, String secret) {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw new IllegalStateException("Writable Account issuance transaction required");
+ }
+ PrimaryAuthentication result = authenticateAccountIdentity(email, secret, true);
+ result.emailLoginChallenge().ifPresent(accountEmailLoginChallengeRepository::delete);
+ Account account = result.account();
+ UUID accountUuid = UUID.fromString(accountMapper.toDto(account).id());
+ return new ControlUiPrimaryIdentity(accountUuid);
+ }
+
+ /** No external constructor: only successful Account primary authentication creates this proof. */
+ public static final class ControlUiPrimaryIdentity {
+ private final UUID accountId;
+
+ private ControlUiPrimaryIdentity(UUID accountId) {
+ this.accountId = accountId;
+ }
+
+ public UUID accountId() {
+ return accountId;
+ }
+
+ @Override
+ public String toString() {
+ return "ControlUiPrimaryIdentity[redacted]";
+ }
+ }
+
private PrimaryAuthentication authenticateAccountIdentity(
String username, String password, boolean allowEmailLoginOtp) {
Optional accountOpt = findAccountForAuthentication(username);
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java
new file mode 100644
index 0000000000..5b1f1c4f7d
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcService.java
@@ -0,0 +1,601 @@
+package net.firedevops.firemud.accountservice.service.impl;
+
+import com.google.protobuf.ByteString;
+import com.google.protobuf.Timestamp;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import io.grpc.stub.StreamObserver;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.sql.SQLException;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.function.Supplier;
+import net.firedevops.firemud.account.v1.AuthorityEvidenceBundleReference;
+import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceRequest;
+import net.firedevops.firemud.account.v1.IssueHumanOperatorAuthorizationReferenceResponse;
+import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionRequest;
+import net.firedevops.firemud.account.v1.ReadRedeemedOperationProjectionResponse;
+import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceRequest;
+import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse;
+import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationRequest;
+import net.firedevops.firemud.account.v1.RedeemOperatorAuthorizationResponse;
+import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc;
+import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository.RedemptionResult;
+import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorityBundle.BundleReference;
+import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService;
+import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.AuthorizationResponse;
+import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.IssueRequest;
+import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RecoverRequest;
+import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemRequest;
+import net.firedevops.firemud.accountservice.service.session.AccountStartSessionOperatorAuthorizationService.RedeemedOperationProjection;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple;
+import net.firedevops.firemud.common.security.SessionContext;
+import org.jooq.exception.DataAccessException;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.grpc.server.service.GrpcService;
+import org.springframework.transaction.CannotCreateTransactionException;
+
+/** Disabled-by-default, same-namespace mTLS receiver for human StartSession authorization. */
+@GrpcService
+@ConditionalOnProperty(
+ prefix = "firemud.account.start-session-operator-authorization",
+ name = "enabled",
+ havingValue = "true",
+ matchIfMissing = false)
+public final class StartSessionOperatorAuthorizationGrpcService
+ extends StartSessionOperatorAuthorizationServiceGrpc
+ .StartSessionOperatorAuthorizationServiceImplBase {
+ private static final int MAX_TUPLE_BYTES = 8 * 1024;
+ private static final int MAX_CONTROL_UI_JWT_BYTES = 16 * 1024;
+ private static final int MAX_AUTHORIZATION_REFERENCE_BYTES = 128;
+ private static final int MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES = 128 * 1024;
+ private static final int MAX_FINGERPRINT_BYTES = 137;
+ private static final UUID NIL_UUID = new UUID(0L, 0L);
+ private static final String AUTHORIZATION_REFERENCE = "[A-Za-z0-9_-]{43}";
+ private static final String AUTHORIZATION_REFERENCE_FINGERPRINT =
+ "arfp/v1/[A-Za-z0-9_-]{1,64}/[0-9a-f]{64}";
+ private static final String MUTATION_DIGEST = "[0-9a-f]{64}";
+
+ private final AccountStartSessionOperatorAuthorizationService authorizationService;
+ private final String workloadNamespace;
+
+ public StartSessionOperatorAuthorizationGrpcService(
+ AccountStartSessionOperatorAuthorizationService authorizationService,
+ @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) {
+ this.authorizationService = Objects.requireNonNull(authorizationService);
+ this.workloadNamespace = workloadNamespace;
+ }
+
+ @Override
+ public void issueHumanOperatorAuthorizationReference(
+ IssueHumanOperatorAuthorizationReferenceRequest request,
+ StreamObserver responseObserver) {
+ if (!isAllowedPeer("logging-admin-service")) {
+ fail(
+ responseObserver,
+ Status.PERMISSION_DENIED,
+ "Verified same-namespace Logging/Admin workload identity is required");
+ return;
+ }
+
+ final IssueRequest parsed;
+ try {
+ parsed = parseIssueRequest(request);
+ } catch (IllegalArgumentException malformed) {
+ fail(
+ responseObserver,
+ Status.INVALID_ARGUMENT,
+ "Canonical StartSession issue input is required");
+ return;
+ }
+
+ invoke(
+ responseObserver,
+ () -> {
+ AuthorizationResponse authorization = authorizationService.issue(parsed);
+ return toIssueResponse(authorization, verifiedLoggingPeerUri());
+ });
+ }
+
+ @Override
+ public void recoverOperatorAuthorizationReference(
+ RecoverOperatorAuthorizationReferenceRequest request,
+ StreamObserver responseObserver) {
+ if (!isAllowedPeer("logging-admin-service")) {
+ fail(
+ responseObserver,
+ Status.PERMISSION_DENIED,
+ "Verified same-namespace Logging/Admin workload identity is required");
+ return;
+ }
+
+ final RecoverRequest parsed;
+ try {
+ parsed = parseRecoverRequest(request);
+ } catch (IllegalArgumentException malformed) {
+ fail(
+ responseObserver,
+ Status.INVALID_ARGUMENT,
+ "Canonical StartSession recovery input is required");
+ return;
+ }
+
+ invoke(
+ responseObserver,
+ () -> {
+ AuthorizationResponse authorization = authorizationService.recover(parsed);
+ return toRecoverResponse(authorization, verifiedLoggingPeerUri());
+ });
+ }
+
+ @Override
+ public void redeemOperatorAuthorization(
+ RedeemOperatorAuthorizationRequest request,
+ StreamObserver responseObserver) {
+ if (!isAllowedPeer("game-session-service")) {
+ fail(
+ responseObserver,
+ Status.PERMISSION_DENIED,
+ "Verified same-namespace Game Session workload identity is required");
+ return;
+ }
+
+ final RedeemRequest parsed;
+ try {
+ parsed = parseRedeemRequest(request);
+ } catch (IllegalArgumentException malformed) {
+ fail(
+ responseObserver,
+ Status.INVALID_ARGUMENT,
+ "Canonical StartSession redemption input is required");
+ return;
+ }
+
+ invoke(responseObserver, () -> toRedeemResponse(authorizationService.redeem(parsed)));
+ }
+
+ @Override
+ public void readRedeemedOperationProjection(
+ ReadRedeemedOperationProjectionRequest request,
+ StreamObserver responseObserver) {
+ if (!isAllowedPeer("game-design-service")) {
+ fail(
+ responseObserver,
+ Status.PERMISSION_DENIED,
+ "Verified same-namespace Game Design workload identity is required");
+ return;
+ }
+
+ final AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest
+ parsed;
+ try {
+ parsed = parseReadRedeemedOperationProjectionRequest(request);
+ } catch (IllegalArgumentException malformed) {
+ fail(
+ responseObserver,
+ Status.INVALID_ARGUMENT,
+ "Canonical StartSession operation projection input is required");
+ return;
+ }
+
+ invoke(
+ responseObserver,
+ () ->
+ toReadRedeemedOperationProjectionResponse(
+ authorizationService.readRedeemedOperationProjection(parsed), parsed));
+ }
+
+ private IssueRequest parseIssueRequest(IssueHumanOperatorAuthorizationReferenceRequest request) {
+ rejectUnknownFields(request.getUnknownFields().asMap().isEmpty());
+ byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes());
+ decodeCanonicalTuple(tupleBytes);
+ String token = requireControlUiJwt(request.getControlUiJwt());
+ UUID reservationOwnerId =
+ canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId");
+ long reservationFence =
+ positiveFence(request.getReservationClaimFence(), "reservationClaimFence");
+ UUID claimOwnerId =
+ canonicalNonNilUuid(request.getCurrentClaimOwnerId(), "currentClaimOwnerId");
+ long claimFence = positiveFence(request.getCurrentClaimFence(), "currentClaimFence");
+ return new IssueRequest(
+ token, tupleBytes, reservationOwnerId, reservationFence, claimOwnerId, claimFence);
+ }
+
+ private RecoverRequest parseRecoverRequest(RecoverOperatorAuthorizationReferenceRequest request) {
+ rejectUnknownFields(request.getUnknownFields().asMap().isEmpty());
+ byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes());
+ decodeCanonicalTuple(tupleBytes);
+ UUID reservationOwnerId =
+ canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId");
+ long reservationFence =
+ positiveFence(request.getReservationClaimFence(), "reservationClaimFence");
+ UUID claimOwnerId =
+ canonicalNonNilUuid(request.getCurrentClaimOwnerId(), "currentClaimOwnerId");
+ long claimFence = positiveFence(request.getCurrentClaimFence(), "currentClaimFence");
+ return new RecoverRequest(
+ tupleBytes, reservationOwnerId, reservationFence, claimOwnerId, claimFence);
+ }
+
+ private RedeemRequest parseRedeemRequest(RedeemOperatorAuthorizationRequest request) {
+ rejectUnknownFields(request.getUnknownFields().asMap().isEmpty());
+ byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes());
+ decodeCanonicalTuple(tupleBytes);
+ String authorizationReference =
+ requireAuthorizationReference(request.getOperatorAuthorizationReference());
+ String fingerprint = requireFingerprint(request.getAuthorizationReferenceFingerprint());
+ UUID reservationOwnerId =
+ canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId");
+ long reservationFence =
+ positiveFence(request.getReservationClaimFence(), "reservationClaimFence");
+ UUID ownerAttemptId = canonicalNonNilUuid(request.getOwnerAttemptId(), "ownerAttemptId");
+ long ownerFence = positiveFence(request.getOwnerFence(), "ownerFence");
+ return new RedeemRequest(
+ tupleBytes,
+ authorizationReference,
+ fingerprint,
+ reservationOwnerId,
+ reservationFence,
+ ownerAttemptId,
+ ownerFence);
+ }
+
+ private AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest
+ parseReadRedeemedOperationProjectionRequest(ReadRedeemedOperationProjectionRequest request) {
+ rejectUnknownFields(request.getUnknownFields().asMap().isEmpty());
+ byte[] tupleBytes = boundedTuple(request.getCanonicalPreAuthorizationTupleBytes());
+ decodeCanonicalTuple(tupleBytes);
+ String fingerprint = requireFingerprint(request.getAuthorizationReferenceFingerprint());
+ UUID reservationOwnerId =
+ canonicalNonNilUuid(request.getReservationOwnerId(), "reservationOwnerId");
+ long reservationFence =
+ positiveFence(request.getReservationClaimFence(), "reservationClaimFence");
+ UUID ownerAttemptId = canonicalNonNilUuid(request.getOwnerAttemptId(), "ownerAttemptId");
+ long ownerFence = positiveFence(request.getOwnerFence(), "ownerFence");
+ return new AccountStartSessionOperatorAuthorizationService
+ .ReadRedeemedOperationProjectionRequest(
+ tupleBytes, fingerprint, reservationOwnerId, reservationFence, ownerAttemptId, ownerFence);
+ }
+
+ private boolean isAllowedPeer(String serviceAccount) {
+ if (SessionContext.hasAuthenticatedCallerContext()
+ || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) {
+ return false;
+ }
+ GrpcPeerIdentity peer = GrpcPeerIdentity.current();
+ return peer != null
+ && workloadNamespace.equals(peer.namespace())
+ && peer.uri().equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/" + serviceAccount);
+ }
+
+ /** Returns only the exact peer identity authenticated on this successful RPC's TLS context. */
+ private String verifiedLoggingPeerUri() {
+ if (SessionContext.hasAuthenticatedCallerContext()
+ || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)) {
+ throw new IllegalStateException("verified Logging/Admin peer is unavailable");
+ }
+ GrpcPeerIdentity peer = GrpcPeerIdentity.current();
+ if (peer == null
+ || !workloadNamespace.equals(peer.namespace())
+ || !"logging-admin-service".equals(peer.service())
+ || !peer.uri()
+ .equals("spiffe://firemud/ns/" + workloadNamespace + "/sa/logging-admin-service")) {
+ throw new IllegalStateException("verified Logging/Admin peer is unavailable");
+ }
+ return peer.uri();
+ }
+
+ private static byte[] boundedTuple(ByteString tuple) {
+ if (tuple.isEmpty() || tuple.size() > MAX_TUPLE_BYTES) {
+ throw new IllegalArgumentException("bounded canonical tuple bytes are required");
+ }
+ return tuple.toByteArray();
+ }
+
+ private static StartSessionPreAuthorizationReservationTuple decodeCanonicalTuple(
+ byte[] exactBytes) {
+ final String json;
+ try {
+ json =
+ StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(exactBytes))
+ .toString();
+ } catch (CharacterCodingException malformedUtf8) {
+ throw new IllegalArgumentException("tuple is not strict UTF-8", malformedUtf8);
+ }
+ StartSessionPreAuthorizationReservationTuple tuple =
+ StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(json);
+ if (!Arrays.equals(exactBytes, tuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) {
+ throw new IllegalArgumentException("tuple bytes are not the exact canonical encoding");
+ }
+ return tuple;
+ }
+
+ private static String requireControlUiJwt(String value) {
+ if (value == null
+ || value.isBlank()
+ || value.length() > MAX_CONTROL_UI_JWT_BYTES
+ || value.chars().anyMatch(character -> character < 0x21 || character > 0x7e)) {
+ throw new IllegalArgumentException("bounded compact control-ui JWT is required");
+ }
+ return value;
+ }
+
+ private static UUID canonicalNonNilUuid(String value, String fieldName) {
+ if (value == null || value.length() > 36) {
+ throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID");
+ }
+ try {
+ UUID parsed = UUID.fromString(value);
+ if (NIL_UUID.equals(parsed) || !parsed.toString().equals(value)) {
+ throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID");
+ }
+ return parsed;
+ } catch (IllegalArgumentException malformed) {
+ throw new IllegalArgumentException(fieldName + " must be a canonical nonnil UUID", malformed);
+ }
+ }
+
+ private static long positiveFence(long value, String fieldName) {
+ // A protobuf uint64 above Long.MAX_VALUE is exposed as a negative Java long and is rejected.
+ if (value <= 0L) {
+ throw new IllegalArgumentException(fieldName + " must be a positive supported uint64");
+ }
+ return value;
+ }
+
+ private static String requireAuthorizationReference(String value) {
+ if (value == null
+ || value.getBytes(StandardCharsets.UTF_8).length > MAX_AUTHORIZATION_REFERENCE_BYTES
+ || !value.matches(AUTHORIZATION_REFERENCE)) {
+ throw new IllegalArgumentException("canonical authorization reference is required");
+ }
+ return value;
+ }
+
+ private static String requireFingerprint(String value) {
+ if (value == null
+ || value.getBytes(StandardCharsets.UTF_8).length > MAX_FINGERPRINT_BYTES
+ || !value.matches(AUTHORIZATION_REFERENCE_FINGERPRINT)) {
+ throw new IllegalArgumentException("canonical authorization fingerprint is required");
+ }
+ return value;
+ }
+
+ private static void rejectUnknownFields(boolean requestHasNoUnknownFields) {
+ if (!requestHasNoUnknownFields) {
+ throw new IllegalArgumentException("unknown request fields are not supported");
+ }
+ }
+
+ private static IssueHumanOperatorAuthorizationReferenceResponse toIssueResponse(
+ AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) {
+ requireResponse(response);
+ return IssueHumanOperatorAuthorizationReferenceResponse.newBuilder()
+ .setOperatorAuthorizationReference(response.operatorAuthorizationReference())
+ .setAuthorizationReferenceFingerprint(response.authorizationReferenceFingerprint())
+ .setExpiresAt(timestamp(response.expiresAt()))
+ .setAuthorityEvidenceBundle(ByteString.copyFrom(response.authorityEvidenceBundle()))
+ .setBundleReference(toWireBundleReference(response.bundleReference()))
+ .setAuthenticatedLoggingWorkloadIdentity(authenticatedLoggingWorkloadIdentity)
+ .build();
+ }
+
+ private static RecoverOperatorAuthorizationReferenceResponse toRecoverResponse(
+ AuthorizationResponse response, String authenticatedLoggingWorkloadIdentity) {
+ requireResponse(response);
+ return RecoverOperatorAuthorizationReferenceResponse.newBuilder()
+ .setOperatorAuthorizationReference(response.operatorAuthorizationReference())
+ .setAuthorizationReferenceFingerprint(response.authorizationReferenceFingerprint())
+ .setExpiresAt(timestamp(response.expiresAt()))
+ .setAuthorityEvidenceBundle(ByteString.copyFrom(response.authorityEvidenceBundle()))
+ .setBundleReference(toWireBundleReference(response.bundleReference()))
+ .setAuthenticatedLoggingWorkloadIdentity(authenticatedLoggingWorkloadIdentity)
+ .build();
+ }
+
+ private static void requireResponse(AuthorizationResponse response) {
+ if (response == null
+ || response.operatorAuthorizationReference() == null
+ || response.operatorAuthorizationReference().getBytes(StandardCharsets.UTF_8).length
+ > MAX_AUTHORIZATION_REFERENCE_BYTES
+ || !response.operatorAuthorizationReference().matches(AUTHORIZATION_REFERENCE)
+ || response.authorizationReferenceFingerprint() == null
+ || response.authorizationReferenceFingerprint().getBytes(StandardCharsets.UTF_8).length
+ > MAX_FINGERPRINT_BYTES
+ || !response
+ .authorizationReferenceFingerprint()
+ .matches(AUTHORIZATION_REFERENCE_FINGERPRINT)
+ || response.expiresAt() == null
+ || !response.expiresAt().isAfter(Instant.EPOCH)
+ || response.authorityEvidenceBundle() == null
+ || response.authorityEvidenceBundle().length == 0
+ || response.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES
+ || response.bundleReference() == null) {
+ throw new IllegalStateException(
+ "Account produced an invalid StartSession authorization result");
+ }
+ }
+
+ private static AuthorityEvidenceBundleReference toWireBundleReference(BundleReference reference) {
+ if (reference == null) {
+ throw new IllegalStateException("Account bundle reference is missing");
+ }
+ return AuthorityEvidenceBundleReference.newBuilder()
+ .setBundleVersion(reference.bundleVersion())
+ .setSourceVersion(reference.sourceVersion())
+ .setSourceFence(reference.sourceFence())
+ .setLinearization(reference.linearization())
+ .build();
+ }
+
+ private static RedeemOperatorAuthorizationResponse toRedeemResponse(RedemptionResult result) {
+ if (result == null
+ || result.authorizationReferenceFingerprint() == null
+ || result.authorizationReferenceFingerprint().getBytes(StandardCharsets.UTF_8).length
+ > MAX_FINGERPRINT_BYTES
+ || !result.authorizationReferenceFingerprint().matches(AUTHORIZATION_REFERENCE_FINGERPRINT)
+ || result.authorityEvidenceBundle() == null
+ || result.authorityEvidenceBundle().length == 0
+ || result.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES
+ || result.issuanceOperationId() == null
+ || NIL_UUID.equals(result.issuanceOperationId())
+ || result.issuanceFence() <= 0L) {
+ throw new IllegalStateException("Account produced an invalid StartSession redemption result");
+ }
+ return RedeemOperatorAuthorizationResponse.newBuilder()
+ .setAuthorizationReferenceFingerprint(result.authorizationReferenceFingerprint())
+ .setAuthorityEvidenceBundle(ByteString.copyFrom(result.authorityEvidenceBundle()))
+ .setIssuanceOperationId(result.issuanceOperationId().toString())
+ .setIssuanceFence(result.issuanceFence())
+ .setReplay(result.replay())
+ .build();
+ }
+
+ private ReadRedeemedOperationProjectionResponse toReadRedeemedOperationProjectionResponse(
+ RedeemedOperationProjection projection,
+ AccountStartSessionOperatorAuthorizationService.ReadRedeemedOperationProjectionRequest
+ request) {
+ if (projection == null) {
+ throw new IllegalStateException("Account produced an invalid redeemed operation projection");
+ }
+ byte[] requestTupleBytes = request.canonicalPreAuthorizationTuple();
+ byte[] projectionTupleBytes = projection.canonicalPreAuthorizationTuple();
+ StartSessionPreAuthorizationReservationTuple tuple = decodeCanonicalTuple(requestTupleBytes);
+ String expectedRedeemerUri =
+ "spiffe://firemud/ns/" + workloadNamespace + "/sa/game-session-service";
+ if (!StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId(
+ projection.controlPlaneRequestId())
+ .equals(tuple.controlPlaneRequestId())
+ || !Arrays.equals(projectionTupleBytes, requestTupleBytes)
+ || projection.mutationDigest() == null
+ || !projection.mutationDigest().matches(MUTATION_DIGEST)
+ || !tuple.mutationDigest().equals(projection.mutationDigest())
+ || !request
+ .authorizationReferenceFingerprint()
+ .equals(projection.authorizationReferenceFingerprint())
+ || !request.reservationOwnerId().equals(projection.reservationOwnerId())
+ || request.reservationClaimFence() != projection.reservationClaimFence()
+ || !request.ownerAttemptId().equals(projection.ownerAttemptId())
+ || request.ownerFence() != projection.ownerFence()
+ || !GrpcPeerIdentity.isValidNamespace(workloadNamespace)
+ || !expectedRedeemerUri.equals(projection.redeemerWorkloadUri())
+ || projection.referenceExpiresAt() == null
+ || projection.redeemedAt() == null
+ || !projection.referenceExpiresAt().isAfter(projection.redeemedAt())
+ || projection.issuanceOperationId() == null
+ || NIL_UUID.equals(projection.issuanceOperationId())
+ || projection.issuanceFence() <= 0L
+ || projection.bundleReference() == null
+ || projection.authorityEvidenceBundle() == null
+ || projection.authorityEvidenceBundle().length == 0
+ || projection.authorityEvidenceBundle().length > MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES) {
+ throw new IllegalStateException("Account produced an invalid redeemed operation projection");
+ }
+ return ReadRedeemedOperationProjectionResponse.newBuilder()
+ .setControlPlaneRequestId(projection.controlPlaneRequestId())
+ .setCanonicalPreAuthorizationTupleBytes(ByteString.copyFrom(projectionTupleBytes))
+ .setMutationDigest(projection.mutationDigest())
+ .setAuthorizationReferenceFingerprint(projection.authorizationReferenceFingerprint())
+ .setReservationOwnerId(projection.reservationOwnerId().toString())
+ .setReservationClaimFence(projection.reservationClaimFence())
+ .setAuthenticatedRedeemerWorkloadIdentity(projection.redeemerWorkloadUri())
+ .setOwnerAttemptId(projection.ownerAttemptId().toString())
+ .setOwnerFence(projection.ownerFence())
+ .setReferenceExpiresAt(timestamp(projection.referenceExpiresAt()))
+ .setRedeemedAt(timestamp(projection.redeemedAt()))
+ .setIssuanceOperationId(projection.issuanceOperationId().toString())
+ .setIssuanceFence(projection.issuanceFence())
+ .setBundleReference(toWireBundleReference(projection.bundleReference()))
+ .setAuthorityEvidenceBundle(ByteString.copyFrom(projection.authorityEvidenceBundle()))
+ .build();
+ }
+
+ private static Timestamp timestamp(Instant instant) {
+ return Timestamp.newBuilder()
+ .setSeconds(instant.getEpochSecond())
+ .setNanos(instant.getNano())
+ .build();
+ }
+
+ private static void invoke(StreamObserver observer, Supplier operation) {
+ try {
+ observer.onNext(operation.get());
+ observer.onCompleted();
+ } catch (AccountStartSessionOperatorAuthorizationService.NotFoundException missing) {
+ fail(observer, Status.NOT_FOUND, "No original StartSession authorization exists");
+ } catch (CannotCreateTransactionException unavailable) {
+ fail(
+ observer,
+ Status.UNAVAILABLE,
+ "Account operator authorization is temporarily unavailable");
+ } catch (DataAccessException failure) {
+ Status status = hasConnectionFailureSqlState(failure) ? Status.UNAVAILABLE : Status.INTERNAL;
+ fail(
+ observer,
+ status,
+ status.getCode() == Status.Code.UNAVAILABLE
+ ? "Account operator authorization is temporarily unavailable"
+ : "Account operator authorization could not be completed");
+ } catch (StatusRuntimeException upstream) {
+ Status mapped = mapUpstreamStatus(Status.fromThrowable(upstream).getCode());
+ fail(observer, mapped, descriptionFor(mapped));
+ } catch (IllegalArgumentException malformed) {
+ fail(observer, Status.INVALID_ARGUMENT, "StartSession authorization input is invalid");
+ } catch (IllegalStateException rejected) {
+ fail(
+ observer,
+ Status.FAILED_PRECONDITION,
+ "Current Account authorization evidence is unavailable");
+ } catch (RuntimeException failure) {
+ fail(observer, Status.INTERNAL, "Account operator authorization could not be completed");
+ }
+ }
+
+ private static boolean hasConnectionFailureSqlState(Throwable failure) {
+ for (Throwable cause = failure; cause != null; cause = cause.getCause()) {
+ if (cause instanceof SQLException exception) {
+ String sqlState = exception.getSQLState();
+ if (sqlState != null && sqlState.startsWith("08")) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static Status mapUpstreamStatus(Status.Code code) {
+ return switch (code) {
+ case INVALID_ARGUMENT -> Status.INVALID_ARGUMENT;
+ case NOT_FOUND -> Status.NOT_FOUND;
+ case PERMISSION_DENIED -> Status.PERMISSION_DENIED;
+ case FAILED_PRECONDITION, ABORTED -> Status.FAILED_PRECONDITION;
+ case UNAVAILABLE, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED -> Status.UNAVAILABLE;
+ default -> Status.INTERNAL;
+ };
+ }
+
+ private static String descriptionFor(Status status) {
+ return switch (status.getCode()) {
+ case INVALID_ARGUMENT -> "StartSession authorization input is invalid";
+ case NOT_FOUND -> "No original StartSession authorization exists";
+ case PERMISSION_DENIED -> "Account rejected the authenticated StartSession caller";
+ case FAILED_PRECONDITION -> "Current Account authorization evidence is unavailable";
+ case UNAVAILABLE -> "Account operator authorization is temporarily unavailable";
+ default -> "Account operator authorization could not be completed";
+ };
+ }
+
+ private static void fail(StreamObserver observer, Status status, String description) {
+ observer.onError(status.withDescription(description).asRuntimeException());
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java
new file mode 100644
index 0000000000..96c78606ff
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java
@@ -0,0 +1,370 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.function.Function;
+import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority;
+import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository;
+import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding;
+import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier;
+import net.firedevops.firemud.common.security.AccountPublicJwksCache;
+import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/** Genuine creator actor/currentness and same-transaction original Draft ordering; unregistered. */
+public final class AccountControlUiActorService {
+ private static final AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy POLICY =
+ new AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy(
+ "account-internal-creator-draft",
+ "control-ui",
+ "control-ui",
+ "firemud-account-service",
+ "control-ui",
+ ControlUiJwtProfileValidator.REQUIRED_CLAIMS,
+ ControlUiJwtProfileValidator.OPTIONAL_CLAIMS,
+ 300,
+ 0,
+ 16384,
+ claims -> ControlUiJwtProfileValidator.validateClaims(claims, 1));
+ private final AccountControlUiIssuanceRepository operations;
+ private final AccountControlUiAuthority authority;
+ private final AccountControlUiSignerOwner signers;
+ private final AccountControlUiCoordination registry;
+ private final AccountJwtJwksTrustedSource publicSource;
+ private final DraftAuthorizationFenceRepository fences;
+ private final TransactionTemplate transaction;
+ private final Clock clock;
+
+ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification =
+ "Injected Draft fence repository is an internal Account owner transaction collaborator.")
+ public AccountControlUiActorService(
+ AccountControlUiIssuanceRepository operations,
+ AccountControlUiAuthority authority,
+ AccountControlUiSignerOwner signers,
+ AccountControlUiCoordination registry,
+ AccountJwtJwksTrustedSource publicSource,
+ DraftAuthorizationFenceRepository fences,
+ PlatformTransactionManager transactions,
+ Clock clock) {
+ this.operations = Objects.requireNonNull(operations);
+ this.authority = Objects.requireNonNull(authority);
+ this.signers = Objects.requireNonNull(signers);
+ this.registry = Objects.requireNonNull(registry);
+ this.publicSource = Objects.requireNonNull(publicSource);
+ this.fences = Objects.requireNonNull(fences);
+ this.clock = Objects.requireNonNull(clock);
+ transaction = new TransactionTemplate(Objects.requireNonNull(transactions));
+ transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
+ }
+
+ public AuthenticatedActor authenticate(
+ String compactJwt, UUID selectedTenant, CapturedEnvironmentBoundary environment) {
+ return withCurrent(
+ compactJwt,
+ selectedTenant,
+ environment,
+ current ->
+ new AuthenticatedActor(
+ current.stored.accountId,
+ current.stored.tenantId,
+ current.stored.operationId,
+ current.stored.tokenHash));
+ }
+
+ /** Exact retained producer recovery; absence alone permits a fresh authenticated claim. */
+ boolean readHeldOriginalDraft(DraftAuthorizationFenceBinding original) {
+ outsideSql();
+ return Objects.requireNonNull(
+ transaction.execute(
+ ignored -> {
+ var retained = fences.readOriginalBinding(original.operationId());
+ if (retained.isEmpty()) return false;
+ if (!Arrays.equals(retained.get().canonicalBytes(), original.canonicalBytes()))
+ throw io.grpc.Status.FAILED_PRECONDITION.asRuntimeException();
+ var order = fences.read(original);
+ if (order.ordering() != DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER
+ || order.reservedAt() == null
+ || order.orderedAt() == null
+ || !Arrays.equals(order.binding(), original.canonicalBytes())
+ || fences.readSettlement(original)
+ != DraftAuthorizationFenceRepository.Settlement.PENDING)
+ throw io.grpc.Status.FAILED_PRECONDITION.asRuntimeException();
+ return true;
+ }));
+ }
+
+ /** No transport or World mutation: original Account reservation/order is the only effect. */
+ public DraftAuthorizationFenceRepository.FenceSnapshot claimOriginalDraft(
+ String compactJwt,
+ DraftAuthorizationFenceBinding original,
+ CapturedEnvironmentBoundary environment) {
+ Objects.requireNonNull(original);
+ return withCurrent(
+ compactJwt,
+ original.tenantId(),
+ environment,
+ current -> {
+ if (!original.actorAccountId().equals(current.stored.accountId)
+ || !exactSources(original.sources(), current.source.sources())) {
+ throw denied();
+ }
+ // Never wait for a source-first writer while retaining captured owner rows.
+ fences.lockProducerSourcesNowait(current.source.sources());
+ fences.reserve(original);
+ var order = fences.claimCommitOrder(original);
+ if (fences.readSettlement(original)
+ != DraftAuthorizationFenceRepository.Settlement.PENDING) throw denied();
+ return order;
+ });
+ }
+
+ T withCurrent(
+ String compactJwt,
+ UUID selectedTenant,
+ CapturedEnvironmentBoundary environment,
+ Function action) {
+ outsideSql();
+ var signed = verifySigned(compactJwt);
+ String tokenHash =
+ AccountControlUiIssuanceRepository.hash(compactJwt.getBytes(StandardCharsets.US_ASCII));
+ byte[] exactRegistry = registry.readActive(tokenHash);
+ return transaction.execute(
+ ignored -> {
+ var stored = operations.findToken(tokenHash);
+ if (stored == null
+ || !selectedTenant.equals(stored.tenantId)
+ || !"COMMITTED".equals(stored.status)
+ || !Arrays.equals(stored.activeRegistry, exactRegistry)
+ || !Arrays.equals(
+ stored.claims, AccountControlUiAuthority.canonical(signed.claims.claims()))) {
+ throw denied();
+ }
+ requireSignerIdentity(stored, signed);
+ signers.requireOriginal(stored.signerReceipt);
+ var current = authority.capture(stored.accountId, selectedTenant, environment);
+ if (!Arrays.equals(current.evidence(), stored.sources)) {
+ throw denied();
+ }
+ var committed = operations.requireCommitted(stored);
+ if (!committed.tokenHash().equals(tokenHash)) {
+ throw denied();
+ }
+ return action.apply(new Current(stored, current));
+ });
+ }
+
+ /**
+ * Revalidates an already committed control-ui actor without requiring the caller to forward its
+ * JWT again. The token jti selects Account's immutable issuance record; active registry readback,
+ * original signer provenance, expiry, and current Account sources are still independently
+ * required. The supplied action runs in the same owner transaction as source capture.
+ */
+ T withCurrentCommitted(
+ UUID actorAccountId,
+ UUID selectedTenant,
+ UUID tokenJti,
+ CapturedEnvironmentBoundary environment,
+ Function action) {
+ outsideSql();
+ Objects.requireNonNull(actorAccountId, "actor account is required");
+ Objects.requireNonNull(selectedTenant, "selected tenant is required");
+ Objects.requireNonNull(tokenJti, "control-ui token jti is required");
+ Objects.requireNonNull(environment, "captured Account environment is required");
+ Objects.requireNonNull(action, "current actor action is required");
+ var original = transaction.execute(ignored -> operations.findTokenJti(tokenJti));
+ if (original == null
+ || !actorAccountId.equals(original.accountId)
+ || !selectedTenant.equals(original.tenantId)
+ || !tokenJti.equals(original.jti)
+ || !"COMMITTED".equals(original.status)
+ || original.tokenHash == null
+ || original.expiresAt == null
+ || !clock.instant().isBefore(original.expiresAt)) {
+ throw denied();
+ }
+
+ byte[] exactRegistry = registry.readActive(original.tokenHash);
+ return transaction.execute(
+ ignored -> {
+ var observed = operations.findTokenJti(tokenJti);
+ if (!sameCommittedOperation(original, observed)
+ || !Arrays.equals(observed.activeRegistry, exactRegistry)) {
+ throw denied();
+ }
+ requireStoredActorIdentity(observed, actorAccountId, selectedTenant, tokenJti);
+ signers.requireOriginal(observed.signerReceipt);
+ var current = authority.capture(actorAccountId, selectedTenant, environment);
+ if (!Arrays.equals(current.evidence(), observed.sources)
+ || !clock.instant().isBefore(observed.expiresAt)) {
+ throw denied();
+ }
+ operations.requireCommitted(observed);
+ var committed = operations.findTokenJti(tokenJti);
+ if (!sameCommittedOperation(observed, committed)
+ || !Arrays.equals(committed.activeRegistry, exactRegistry)) {
+ throw denied();
+ }
+ return action.apply(new Current(committed, current));
+ });
+ }
+
+ /** Production asymmetric/profile verification, also used before any candidate is persisted. */
+ SignedObservation verifySigned(String compactJwt) {
+ outsideSql();
+ var pin = publicSource.sourceIdentity();
+ var cache = new AccountPublicJwksCache(publicSource, pin, clock, Duration.ofSeconds(30));
+ return new SignedObservation(
+ new AccountAsymmetricJwtVerifier(cache, clock).verify(compactJwt, POLICY), pin);
+ }
+
+ void requireSignerIdentity(
+ AccountControlUiIssuanceRepository.Stored stored, SignedObservation observation) {
+ var signed = observation.claims;
+ var receipt = AccountControlUiIssuanceRepository.object(stored.signerReceipt);
+ var pin = observation.pin;
+ if (!signed.keyId().equals(receipt.get("kid"))
+ || !pin.environmentId().equals(receipt.get("environmentId"))
+ || !pin.clusterId().equals(receipt.get("clusterId"))
+ || !pin.clusterIncarnationUid().equals(receipt.get("clusterIncarnationUid"))
+ || !pin.namespace().equals(receipt.get("namespace"))
+ || !pin.namespaceUid().equals(receipt.get("namespaceUid"))
+ || !pin.configMapUid().equals(receipt.get("publicConfigMapUid"))
+ || !pin.bindingRevision().equals(receipt.get("apiConfigRevision"))
+ || !stored.accountId.toString().equals(signed.claims().get("sub"))
+ || !stored.accountId.toString().equals(signed.claims().get("accountId"))
+ || !stored.jti.toString().equals(signed.claims().get("jti"))
+ || !Map.of(stored.tenantId.toString(), List.of("tenantAdmin"))
+ .equals(signed.claims().get("scopedRoles"))
+ || signed.claims().containsKey("globalRoles")) {
+ throw denied();
+ }
+ }
+
+ private static boolean exactSources(
+ List first,
+ List second) {
+ if (first.size() != second.size()) {
+ return false;
+ }
+ for (int index = 0; index < first.size(); index++) {
+ if (!Arrays.equals(first.get(index).canonicalBytes(), second.get(index).canonicalBytes())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static boolean sameCommittedOperation(
+ AccountControlUiIssuanceRepository.Stored first,
+ AccountControlUiIssuanceRepository.Stored second) {
+ return second != null
+ && "COMMITTED".equals(second.status)
+ && first.requestId.equals(second.requestId)
+ && first.operationId.equals(second.operationId)
+ && first.jti.equals(second.jti)
+ && first.accountId.equals(second.accountId)
+ && first.tenantId.equals(second.tenantId)
+ && first.callerContextId.equals(second.callerContextId)
+ && first.caller.equals(second.caller)
+ && first.requestMacKeyId.equals(second.requestMacKeyId)
+ && first.requestDigest.equals(second.requestDigest)
+ && Objects.equals(first.tokenHash, second.tokenHash)
+ && first.issuedAt.equals(second.issuedAt)
+ && first.expiresAt.equals(second.expiresAt)
+ && first.recoveryExpiry.equals(second.recoveryExpiry)
+ && Arrays.equals(first.claims, second.claims)
+ && Arrays.equals(first.sources, second.sources)
+ && Arrays.equals(first.bundle, second.bundle)
+ && Arrays.equals(first.signerReceipt, second.signerReceipt)
+ && Arrays.equals(first.pendingRegistry, second.pendingRegistry)
+ && Arrays.equals(first.activeRegistry, second.activeRegistry);
+ }
+
+ private static void requireStoredActorIdentity(
+ AccountControlUiIssuanceRepository.Stored stored,
+ UUID actorAccountId,
+ UUID tenantId,
+ UUID tokenJti) {
+ Map claims = AccountControlUiIssuanceRepository.object(stored.claims);
+ if (!actorAccountId.toString().equals(claims.get("sub"))
+ || !actorAccountId.toString().equals(claims.get("accountId"))
+ || !tenantId.toString().equals(stored.tenantId.toString())
+ || !tokenJti.toString().equals(claims.get("jti"))
+ || !tokenJti.equals(stored.jti)
+ || !"control-ui".equals(claims.get("aud"))) {
+ throw denied();
+ }
+ }
+
+ record Current(
+ AccountControlUiIssuanceRepository.Stored stored,
+ AccountControlUiAuthority.Snapshot source) {}
+
+ static final class SignedObservation {
+ final AccountAsymmetricJwtVerifier.VerifiedClaims claims;
+ final AccountPublicJwksCache.SourceIdentity pin;
+
+ private SignedObservation(
+ AccountAsymmetricJwtVerifier.VerifiedClaims claims,
+ AccountPublicJwksCache.SourceIdentity pin) {
+ this.claims = claims;
+ this.pin = pin;
+ }
+ }
+
+ /** No externally callable constructor; workload possession or a claimed UUID cannot create it. */
+ public static final class AuthenticatedActor {
+ private final UUID accountId, tenantId, issuanceOperationId;
+ private final String tokenHash;
+
+ private AuthenticatedActor(UUID accountId, UUID tenantId, UUID operationId, String tokenHash) {
+ this.accountId = accountId;
+ this.tenantId = tenantId;
+ this.issuanceOperationId = operationId;
+ this.tokenHash = tokenHash;
+ }
+
+ public UUID accountId() {
+ return accountId;
+ }
+
+ public UUID tenantId() {
+ return tenantId;
+ }
+
+ public UUID issuanceOperationId() {
+ return issuanceOperationId;
+ }
+
+ public String tokenHash() {
+ return tokenHash;
+ }
+
+ @Override
+ public String toString() {
+ return "AccountControlUiActorService.AuthenticatedActor[redacted]";
+ }
+ }
+
+ private static void outsideSql() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException("Signature/registry reads must precede owner SQL locks");
+ }
+ }
+
+ private static IllegalStateException denied() {
+ return new IllegalStateException("Exact current authenticated initial creator required");
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java
new file mode 100644
index 0000000000..0be5dfa889
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java
@@ -0,0 +1,267 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import io.lettuce.core.ScriptOutputType;
+import io.lettuce.core.api.sync.RedisCommands;
+import io.lettuce.core.codec.ByteArrayCodec;
+import io.lettuce.core.output.ArrayOutput;
+import io.lettuce.core.protocol.CommandArgs;
+import io.lettuce.core.protocol.ProtocolKeyword;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.util.Arrays;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Objects;
+import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+
+/**
+ * Actual private Coordination reader/CAS with exact catalog, ACL, physical connection and WAITAOF.
+ */
+public final class AccountControlUiCoordination {
+ private final AccountCoordinationPinnedConnectionProvider connections;
+ private final AcknowledgementRequirements acknowledgements;
+ private final RedisScriptCatalog catalog;
+
+ public AccountControlUiCoordination(
+ AccountCoordinationPinnedConnectionProvider connections,
+ AcknowledgementRequirements acknowledgements,
+ RedisScriptCatalog catalog) {
+ this.connections = Objects.requireNonNull(connections);
+ this.acknowledgements = Objects.requireNonNull(acknowledgements);
+ this.catalog = Objects.requireNonNull(catalog);
+ }
+
+ /** Read-only pinned GET and physical expiry; no repair or gameplay-profile interpretation. */
+ public byte[] readActive(String tokenHash) {
+ outsideSql();
+ return withConnection(
+ commands -> {
+ byte[] value = commands.get(key(tokenHash));
+ if (value == null || value.length == 0 || value.length > 32768) {
+ throw denied();
+ }
+ var record = AccountControlUiIssuanceRepository.object(value);
+ if (!"control-ui".equals(record.get("profile"))
+ || !"control-ui".equals(record.get("type"))
+ || !"control-ui".equals(record.get("audience"))
+ || !"active".equals(record.get("state"))
+ || !tokenHash.equals(record.get("tokenHash"))) {
+ throw denied();
+ }
+ Object encodedExpiry = record.get("exp");
+ if (!(encodedExpiry instanceof Number number)
+ || !number.toString().matches("[1-9][0-9]{0,18}")) {
+ throw denied();
+ }
+ long exactExpiry = Math.multiplyExact(Long.parseLong(number.toString()), 1000L);
+ Long physicalExpiry = commands.pexpiretime(key(tokenHash));
+ // This distinct minimum profile uses zero cleanup margin, never an inferred/renewed TTL.
+ if (physicalExpiry == null || physicalExpiry != exactExpiry) {
+ throw denied();
+ }
+ return value.clone();
+ });
+ }
+
+ /** Exact readback for the owner's protected delivery workflow. */
+ public void requireExactActive(String tokenHash, byte[] exactActive, long expiryMillis) {
+ outsideSql();
+ withConnection(
+ commands -> {
+ byte[] key = key(tokenHash);
+ if (!Arrays.equals(exactActive, commands.get(key))) {
+ throw denied();
+ }
+ Long expiry = commands.pexpiretime(key);
+ if (expiry == null || expiry != expiryMillis) {
+ throw denied();
+ }
+ return null;
+ });
+ }
+
+ /** Only package-local owner workflow may register a non-authorizing pending candidate. */
+ Receipt registerPending(String tokenHash, byte[] exactPending, long expiryMillis) {
+ return cas(tokenHash, new byte[0], exactPending, expiryMillis);
+ }
+
+ /** The private committed owner readback is mandatory; arbitrary byte callers cannot activate. */
+ Receipt activate(AccountControlUiIssuanceRepository.Committed original) {
+ return cas(
+ original.tokenHash(),
+ original.pendingRegistry(),
+ original.activeRegistry(),
+ original.expiryMillis());
+ }
+
+ /** Durable owner intent is non-authorizing even if this external CAS cannot complete. */
+ Receipt revoke(AccountControlUiIssuanceRepository.Stored original) {
+ outsideSql();
+ byte[] replacement = AccountControlUiIssuanceRepository.revokedRegistry(original);
+ byte[] expected =
+ withConnection(
+ commands -> {
+ byte[] observed = commands.get(key(original.tokenHash));
+ Long expiry = commands.pexpiretime(key(original.tokenHash));
+ if (expiry == null
+ || expiry != original.expiryMillis()
+ || (!Arrays.equals(observed, original.pendingRegistry)
+ && !Arrays.equals(observed, original.activeRegistry)
+ && !Arrays.equals(observed, replacement))) {
+ throw denied();
+ }
+ return observed;
+ });
+ return cas(original.tokenHash, expected, replacement, original.expiryMillis());
+ }
+
+ private Receipt cas(String tokenHash, byte[] expected, byte[] replacement, long expiryMillis) {
+ outsideSql();
+ if (expected == null
+ || replacement == null
+ || replacement.length == 0
+ || replacement.length > 32768
+ || expected.length > 32768
+ || expiryMillis <= 0) {
+ throw denied();
+ }
+ var descriptor = AccountControlUiRegistryContract.descriptor();
+ if (!descriptor.equals(catalog.require(descriptor.scriptId()))) {
+ throw denied();
+ }
+ byte[] source;
+ try (var stream = getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) {
+ if (stream == null) {
+ throw denied();
+ }
+ source = stream.readNBytes(32769);
+ if (source.length == 0
+ || source.length > 32768
+ || !digest("SHA-256", source).equals(descriptor.sha256())) {
+ throw denied();
+ }
+ } catch (java.io.IOException | RuntimeException failure) {
+ throw denied();
+ }
+ return withConnection(
+ commands -> {
+ byte[] key = key(tokenHash);
+ String sha = commands.scriptLoad(source);
+ if (!digest("SHA-1", source).equals(sha)) {
+ throw denied();
+ }
+ Long outcome =
+ commands.evalsha(
+ sha,
+ ScriptOutputType.INTEGER,
+ new byte[][] {key},
+ expected,
+ replacement,
+ Long.toString(expiryMillis).getBytes(StandardCharsets.US_ASCII));
+ if (outcome == null || (outcome != 0L && outcome != 1L)) {
+ throw denied();
+ }
+ List counts =
+ commands.dispatch(
+ WaitAof.INSTANCE,
+ new ArrayOutput<>(ByteArrayCodec.INSTANCE),
+ new CommandArgs<>(ByteArrayCodec.INSTANCE)
+ .add(acknowledgements.requiredLocalAofCount())
+ .add(acknowledgements.requiredReplicaAofCount())
+ .add(acknowledgements.timeoutMillis()));
+ if (counts == null
+ || counts.size() != 2
+ || !(counts.get(0) instanceof Long local)
+ || !(counts.get(1) instanceof Long replicas)
+ || local < acknowledgements.requiredLocalAofCount()
+ || replicas < acknowledgements.requiredReplicaAofCount()) {
+ throw denied();
+ }
+ Long expiry = commands.pexpiretime(key);
+ if (!Arrays.equals(replacement, commands.get(key))
+ || expiry == null
+ || expiry != expiryMillis) {
+ throw denied();
+ }
+ return new Receipt(
+ tokenHash,
+ digest("SHA-256", replacement),
+ expiryMillis,
+ acknowledgements.requiredLocalAofCount(),
+ acknowledgements.requiredReplicaAofCount());
+ });
+ }
+
+ private T withConnection(
+ java.util.function.Function, T> action) {
+ try (var connection = connections.openPinnedConnection()) {
+ if (connection == null
+ || !connection.isOpen()
+ || connection.getOptions() == null
+ || connection.getOptions().isAutoReconnect()) {
+ throw denied();
+ }
+ var commands = connection.sync();
+ if (!"account_coord_app".equals(commands.aclWhoami())) {
+ throw denied();
+ }
+ return action.apply(commands);
+ } catch (RuntimeException failure) {
+ throw denied();
+ }
+ }
+
+ private static byte[] key(String tokenHash) {
+ if (tokenHash == null || !tokenHash.matches("[0-9a-f]{64}")) {
+ throw denied();
+ }
+ return ("session:auth:token:" + tokenHash).getBytes(StandardCharsets.US_ASCII);
+ }
+
+ static String digest(String algorithm, byte[] value) {
+ try {
+ return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(value));
+ } catch (java.security.NoSuchAlgorithmException | RuntimeException failure) {
+ throw denied();
+ }
+ }
+
+ private static void outsideSql() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException("Coordination calls cannot retain owner SQL locks");
+ }
+ }
+
+ /** Non-authorizing receipt, constructible only after actual durable exact Redis readback. */
+ static final class Receipt {
+ final String tokenHash;
+ final String recordDigest;
+ final long expiryMillis;
+ final long localAof;
+ final long replicas;
+
+ private Receipt(
+ String tokenHash, String recordDigest, long expiryMillis, long localAof, long replicas) {
+ this.tokenHash = tokenHash;
+ this.recordDigest = recordDigest;
+ this.expiryMillis = expiryMillis;
+ this.localAof = localAof;
+ this.replicas = replicas;
+ }
+ }
+
+ private enum WaitAof implements ProtocolKeyword {
+ INSTANCE;
+
+ @Override
+ public byte[] getBytes() {
+ return "WAITAOF".getBytes(StandardCharsets.US_ASCII);
+ }
+ }
+
+ private static IllegalStateException denied() {
+ return new IllegalStateException("Exact Account control-ui Coordination evidence unavailable");
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java
new file mode 100644
index 0000000000..52dc1e045e
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java
@@ -0,0 +1,848 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.Clock;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding;
+import net.firedevops.firemud.accountservice.dto.TenantAuthorityEventV1Codec.Event;
+import net.firedevops.firemud.accountservice.entity.AccountTenantMembership;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository.CompositeSnapshot;
+import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository;
+import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot;
+import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository;
+import net.firedevops.firemud.accountservice.repository.AccountControlUiCommittedIssuanceRepository.CommittedIssuance;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository;
+import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.PairAuthority;
+import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository;
+import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec;
+import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.MembershipEvent;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier;
+import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.ExplicitRouteProfilePolicy;
+import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier.VerifiedClaims;
+import net.firedevops.firemud.common.security.AccountPublicJwksCache;
+import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot;
+import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity;
+import net.firedevops.firemud.common.security.ControlUiJwtProfileValidator;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.core.type.TypeReference;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Read-only Account verification of a signed control-ui actor against committed issuance,
+ * Coordination, protected signer/JWKS state, and current Account tenant membership sources.
+ *
+ * The returned object is authenticated-current actor evidence only. This class does not issue or
+ * redeem operator references, select a privileged route, or turn a creator grant into owner
+ * authority. It deliberately denies global-role claims; callers must perform the approved route
+ * predicate separately against this current tenant-scoped evidence.
+ */
+public final class AccountControlUiCurrentActorVerifier {
+ private static final String ISSUER = "firemud-account-service";
+ private static final int MAX_BUNDLE_BYTES = 131072;
+ private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}");
+ private static final Set SIGNER_RECEIPT_FIELDS =
+ Set.of(
+ "schema",
+ "environmentId",
+ "clusterId",
+ "namespace",
+ "clusterIncarnationUid",
+ "namespaceUid",
+ "trustBindingDigest",
+ "trustConfigRevision",
+ "apiBindingDigest",
+ "apiConfigRevision",
+ "promotionOperationId",
+ "promotionRequestDigest",
+ "generationOperationId",
+ "signerGeneration",
+ "kid",
+ "algorithm",
+ "publicKeyFingerprint",
+ "privateReceiptDigest",
+ "privateResourceVersion",
+ "publicReceiptDigest",
+ "publicResourceVersion",
+ "publicConfigMapUid",
+ "publicDataDigest");
+ private static final Set PENDING_RECEIPT_FIELDS =
+ Set.of(
+ "schema",
+ "tokenHash",
+ "recordDigest",
+ "expiryMillis",
+ "aclIdentity",
+ "localAofCount",
+ "replicaAofCount");
+ private static final Set BUNDLE_FIELDS =
+ Set.of(
+ "schema",
+ "bundleRef",
+ "snapshotIdentity",
+ "evaluationIdentity",
+ "issuer",
+ "profile",
+ "audience",
+ "scope",
+ "operation",
+ "tokenIdentity",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence",
+ "authoritySourceVersions",
+ "accountIdentitySource",
+ "outboxCheckpoints",
+ "roleEvidence");
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+ private static final TypeReference> OBJECT = new TypeReference<>() {};
+ private static final ExplicitRouteProfilePolicy POLICY =
+ new ExplicitRouteProfilePolicy(
+ "account-control-ui-current-actor",
+ ControlUiJwtProfileValidator.PROFILE,
+ ControlUiJwtProfileValidator.TOKEN_TYPE,
+ ISSUER,
+ ControlUiJwtProfileValidator.AUDIENCE,
+ ControlUiJwtProfileValidator.REQUIRED_CLAIMS,
+ Set.of(),
+ 300,
+ 0,
+ 16384,
+ claims -> ControlUiJwtProfileValidator.validateClaims(claims, 1));
+
+ private final AccountJwtJwksTrustedSource publicJwks;
+ private final AccountJwtSignerDesiredStateRepository signerStates;
+ private final AccountJwtSignerMaterializerTrustBinding materializerTrust;
+ private final AccountJwtJwksApiBinding jwksApiBinding;
+ private final AccountControlUiRegistryReader registry;
+ private final AccountControlUiCommittedIssuanceRepository issuances;
+ private final AccountAuthoritySourceEvidenceRepository sourceEvidence;
+ private final AccountAuthorityGenerationRepository generations;
+ private final AccountTenantAuthorityEventRepository tenantEvents;
+ private final AccountTenantMembershipRepository memberships;
+ private final AccountMembershipPairAuthorityRepository membershipPairs;
+ private final AccountTenantMembershipRoleSnapshotRepository roleSnapshots;
+ private final AccountAuthorityOutboxRepository outbox;
+ private final TransactionTemplate accountTransaction;
+ private final Clock clock;
+
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification =
+ "Injected Account repositories are shared owner services; they must retain their transaction and current-state identity rather than be copied.")
+ public AccountControlUiCurrentActorVerifier(
+ AccountJwtJwksTrustedSource publicJwks,
+ AccountJwtSignerDesiredStateRepository signerStates,
+ AccountJwtSignerMaterializerTrustBinding materializerTrust,
+ AccountJwtJwksApiBinding jwksApiBinding,
+ AccountControlUiRegistryReader registry,
+ AccountControlUiCommittedIssuanceRepository issuances,
+ AccountAuthoritySourceEvidenceRepository sourceEvidence,
+ AccountAuthorityGenerationRepository generations,
+ AccountTenantAuthorityEventRepository tenantEvents,
+ AccountTenantMembershipRepository memberships,
+ AccountMembershipPairAuthorityRepository membershipPairs,
+ AccountTenantMembershipRoleSnapshotRepository roleSnapshots,
+ AccountAuthorityOutboxRepository outbox,
+ PlatformTransactionManager transactionManager,
+ Clock clock) {
+ this.publicJwks = Objects.requireNonNull(publicJwks);
+ this.signerStates = Objects.requireNonNull(signerStates);
+ this.materializerTrust = Objects.requireNonNull(materializerTrust);
+ this.jwksApiBinding = Objects.requireNonNull(jwksApiBinding);
+ this.registry = Objects.requireNonNull(registry);
+ this.issuances = Objects.requireNonNull(issuances);
+ this.sourceEvidence = Objects.requireNonNull(sourceEvidence);
+ this.generations = Objects.requireNonNull(generations);
+ this.tenantEvents = Objects.requireNonNull(tenantEvents);
+ this.memberships = Objects.requireNonNull(memberships);
+ this.membershipPairs = Objects.requireNonNull(membershipPairs);
+ this.roleSnapshots = Objects.requireNonNull(roleSnapshots);
+ this.outbox = Objects.requireNonNull(outbox);
+ this.clock = Objects.requireNonNull(clock);
+ accountTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager));
+ accountTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
+ accountTransaction.setReadOnly(false);
+ }
+
+ /** Verifies one signed actor for its selected canonical tenant; no authorization is returned. */
+ public CurrentActor verify(String compactJwt, UUID selectedTenant) {
+ outsideSql();
+ requireTenant(selectedTenant);
+ byte[] compactBytes = compactBytes(compactJwt);
+ SourceIdentity pin = publicJwks.sourceIdentity();
+ AccountPublicJwksCache cache =
+ new AccountPublicJwksCache(publicJwks, pin, clock, Duration.ofSeconds(30));
+ VerifiedClaims signed =
+ new AccountAsymmetricJwtVerifier(cache, clock).verify(compactJwt, POLICY);
+ PublicJwksSnapshot currentJwks = publicJwks.load();
+ String tokenHash = sha256(compactBytes);
+ byte[] activeRegistry = registry.readActive(tokenHash);
+
+ CurrentActor result =
+ accountTransaction.execute(
+ ignored ->
+ verifyOwnerState(
+ tokenHash, selectedTenant, signed, pin, currentJwks, activeRegistry));
+ if (result == null) {
+ throw denied();
+ }
+ return result;
+ }
+
+ private CurrentActor verifyOwnerState(
+ String tokenHash,
+ UUID selectedTenant,
+ VerifiedClaims signed,
+ SourceIdentity pin,
+ PublicJwksSnapshot currentJwks,
+ byte[] activeRegistry) {
+ Map claims = signed.claims();
+ UUID accountId = uuid(claims.get("accountId"));
+ UUID tokenTenant = selectedScopedTenant(claims, selectedTenant);
+ if (!selectedTenant.equals(tokenTenant) || claims.containsKey("globalRoles")) {
+ throw denied();
+ }
+ CommittedIssuance issuance =
+ issuances
+ .readCommitted(tokenHash)
+ .orElseThrow(AccountControlUiCurrentActorVerifier::denied);
+ Map registryRecord =
+ AccountControlUiRegistryReader.parseActiveRecord(activeRegistry, tokenHash);
+ if (!ISSUER.equals(claims.get("iss"))
+ || !claims.get("sub").equals(accountId.toString())
+ || !issuance.tokenHash().equals(tokenHash)
+ || !issuance.accountId().equals(accountId)
+ || !issuance.tenantId().equals(selectedTenant)
+ || !issuance.tokenJti().equals(uuid(claims.get("jti")))
+ || !issuance.requestId().equals(uuid(registryRecord.get("requestId")))
+ || !issuance.operationId().equals(uuid(registryRecord.get("operationId")))
+ || !Arrays.equals(activeRegistry, issuance.activeRegistry())
+ || !Arrays.equals(canonicalBytes(claims), issuance.claims())
+ || !signed.keyId().equals(registryRecord.get("kid"))
+ || !accountId.toString().equals(registryRecord.get("accountId"))
+ || !claims.get("jti").equals(registryRecord.get("jti"))
+ || !canonicalMapEquals(registryRecord.get("authorityTuple"), claims.get("authorityTuple"))
+ || !canonicalMapEquals(
+ registryRecord.get("membershipVersion"), claims.get("membershipVersion"))
+ || !numericEquals(
+ registryRecord.get("tokenGeneration"), positiveLong(claims.get("tokenGeneration")))
+ || !numericEquals(
+ registryRecord.get("issuanceFence"), positiveLong(claims.get("issuanceFence")))
+ || !numericEquals(claims.get("iat"), issuance.issuedAtEpochSecond())
+ || !numericEquals(claims.get("nbf"), issuance.issuedAtEpochSecond())
+ || !numericEquals(claims.get("exp"), issuance.expiresAtEpochSecond())
+ || !numericEquals(registryRecord.get("iat"), issuance.issuedAtEpochSecond())
+ || !numericEquals(registryRecord.get("nbf"), issuance.issuedAtEpochSecond())
+ || !numericEquals(registryRecord.get("exp"), issuance.expiresAtEpochSecond())
+ || !Arrays.equals(issuance.pendingRegistry(), derivePendingRegistry(activeRegistry))) {
+ throw denied();
+ }
+ requireBundle(issuance, claims, registryRecord);
+ requirePendingReceipt(issuance);
+ requireSignerReceipt(issuance, signed.keyId(), pin, currentJwks);
+ return requireCurrentAccountAuthority(issuance, claims, selectedTenant, tokenHash);
+ }
+
+ private void requireBundle(
+ CommittedIssuance issuance, Map claims, Map registryRecord) {
+ Map storedClaims = parseCanonicalObject(issuance.claims(), 16384);
+ Map bundle = parseCanonicalObject(issuance.bundle(), MAX_BUNDLE_BYTES);
+ Map bundleRef = object(bundle.get("bundleRef"));
+ Map scope = object(bundle.get("scope"));
+ Map operation = object(bundle.get("operation"));
+ Map tokenIdentity = object(bundle.get("tokenIdentity"));
+ Map roleEvidence = object(bundle.get("roleEvidence"));
+ if (!bundle.keySet().equals(BUNDLE_FIELDS)
+ || !bundleRef
+ .keySet()
+ .equals(Set.of("bundleVersion", "sourceVersion", "sourceFence", "linearization"))
+ || !scope.keySet().equals(Set.of("kind", "accountId", "tenantIds"))
+ || !operation
+ .keySet()
+ .equals(
+ Set.of(
+ "operationId",
+ "requestId",
+ "requestDigest",
+ "callerWorkload",
+ "callerContextId",
+ "accountId"))
+ || !tokenIdentity.keySet().equals(Set.of("jti", "tokenGeneration", "iat", "nbf", "exp"))
+ || !roleEvidence.keySet().equals(Set.of("scopedRoles", "freshnessSource"))
+ || !Arrays.equals(canonicalBytes(claims), canonicalBytes(storedClaims))
+ || !"account-auth-evidence-bundle/v1".equals(bundle.get("schema"))
+ || !ISSUER.equals(bundle.get("issuer"))
+ || !"control-ui".equals(bundle.get("profile"))
+ || !"control-ui".equals(bundle.get("audience"))
+ || !issuance.operationId().toString().equals(operation.get("operationId"))
+ || !issuance.requestId().toString().equals(operation.get("requestId"))
+ || !issuance.requestDigest().equals(operation.get("requestDigest"))
+ || !issuance.accountId().toString().equals(operation.get("accountId"))
+ || !issuance.callerWorkload().equals(operation.get("callerWorkload"))
+ || !issuance.callerContextId().toString().equals(operation.get("callerContextId"))
+ || !issuance.accountId().toString().equals(scope.get("accountId"))
+ || !List.of(issuance.tenantId().toString()).equals(scope.get("tenantIds"))
+ || !"TENANT".equals(scope.get("kind"))
+ || !canonicalMapEquals(bundle.get("authorityTuple"), claims.get("authorityTuple"))
+ || !canonicalMapEquals(bundle.get("membershipVersion"), claims.get("membershipVersion"))
+ || !numericEquals(bundle.get("issuanceFence"), positiveLong(claims.get("issuanceFence")))
+ || !canonicalMapEquals(
+ bundle.get("authoritySourceVersions"), registryRecord.get("authoritySourceVersions"))
+ || !canonicalMapEquals(tokenIdentity, tokenIdentity(claims))
+ || !canonicalMapEquals(roleEvidence.get("scopedRoles"), claims.get("scopedRoles"))) {
+ throw denied();
+ }
+ parseCanonicalObject(issuance.source(), 131072);
+ String sourceIdentity = sha256(issuance.source());
+ if (!sourceIdentity.equals(bundle.get("snapshotIdentity"))
+ || !sourceIdentity.equals(roleEvidence.get("freshnessSource"))) {
+ throw denied();
+ }
+ Map expectedReference = new LinkedHashMap<>(bundleRef);
+ expectedReference.put("canonicalSha256", sha256(issuance.bundle()));
+ if (!canonicalMapEquals(expectedReference, registryRecord.get("authEvidenceBundle"))) {
+ throw denied();
+ }
+ Map evaluation =
+ Map.of(
+ "operation", operation,
+ "claims", claims,
+ "bundleRef", bundleRef,
+ "snapshotIdentity", sourceIdentity);
+ if (!sha256(canonicalBytes(evaluation)).equals(bundle.get("evaluationIdentity"))) {
+ throw denied();
+ }
+ }
+
+ private void requirePendingReceipt(CommittedIssuance issuance) {
+ Map receipt = parseCanonicalObject(issuance.pendingReceipt(), 8192);
+ if (!receipt.keySet().equals(PENDING_RECEIPT_FIELDS)
+ || !"account-control-ui-pending-readback/v1".equals(receipt.get("schema"))
+ || !issuance.tokenHash().equals(receipt.get("tokenHash"))
+ || !sha256(issuance.pendingRegistry()).equals(receipt.get("recordDigest"))
+ || !"account_coord_app".equals(receipt.get("aclIdentity"))
+ || !numericEquals(receipt.get("expiryMillis"), issuance.expiryMillis())
+ || !atLeastOne(receipt.get("localAofCount"))
+ || !atLeastOne(receipt.get("replicaAofCount"))) {
+ throw denied();
+ }
+ }
+
+ private void requireSignerReceipt(
+ CommittedIssuance issuance,
+ String verifiedKid,
+ SourceIdentity pin,
+ PublicJwksSnapshot currentJwks) {
+ Map receipt = parseCanonicalObject(issuance.signerReceipt(), 65536);
+ Optional fingerprint =
+ AccountJwtJwksTrustedSource.publicKeyFingerprint(currentJwks, pin, verifiedKid);
+ Map registryRecord =
+ AccountControlUiRegistryReader.parseActiveRecord(
+ issuance.activeRegistry(), issuance.tokenHash());
+ if (!receipt.keySet().equals(SIGNER_RECEIPT_FIELDS)
+ || !"account-control-ui-committed-signer/v1".equals(receipt.get("schema"))
+ || !pin.environmentId().equals(receipt.get("environmentId"))
+ || !pin.clusterId().equals(receipt.get("clusterId"))
+ || !pin.clusterIncarnationUid().equals(receipt.get("clusterIncarnationUid"))
+ || !pin.namespace().equals(receipt.get("namespace"))
+ || !pin.namespaceUid().equals(receipt.get("namespaceUid"))
+ || !pin.configMapUid().equals(receipt.get("publicConfigMapUid"))
+ || !pin.bindingRevision().equals(receipt.get("apiConfigRevision"))
+ || !verifiedKid.equals(receipt.get("kid"))
+ || !verifiedKid.equals(registryRecord.get("kid"))
+ || !"RS256".equals(receipt.get("algorithm"))
+ || !fingerprint.orElse("").equals(receipt.get("publicKeyFingerprint"))
+ || !registryRecord.get("signerGeneration").equals(receipt.get("signerGeneration"))
+ || !issuance.operationId().toString().equals(registryRecord.get("operationId"))
+ || !issuance.requestId().toString().equals(registryRecord.get("requestId"))
+ || !issuance.requestDigest().equals(registryRecord.get("requestDigest"))
+ || !sha256(issuance.signerReceipt())
+ .equals(registryRecord.get("originalSignerReceiptDigest"))
+ || !DIGEST.matcher(text(receipt.get("trustBindingDigest"))).matches()
+ || !DIGEST.matcher(text(receipt.get("apiBindingDigest"))).matches()
+ || !DIGEST.matcher(text(receipt.get("promotionRequestDigest"))).matches()
+ || !DIGEST.matcher(text(receipt.get("privateReceiptDigest"))).matches()
+ || !DIGEST.matcher(text(receipt.get("publicReceiptDigest"))).matches()
+ || !DIGEST.matcher(text(receipt.get("publicDataDigest"))).matches()
+ || !DIGEST.matcher(text(receipt.get("publicKeyFingerprint"))).matches()) {
+ throw denied();
+ }
+ requireOriginalCommittedSigner(receipt, verifiedKid);
+ }
+
+ private void requireOriginalCommittedSigner(Map receipt, String verifiedKid) {
+ var materializer =
+ materializerTrust.current().orElseThrow(AccountControlUiCurrentActorVerifier::denied);
+ var api = jwksApiBinding.current();
+ if (!materializer.environmentId().equals(api.environmentId())
+ || !materializer.clusterId().equals(api.clusterId())
+ || !materializer.namespace().equals(api.namespace())
+ || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid())
+ || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid())
+ || !text(receipt.get("apiBindingDigest")).equals(api.bindingDigest())
+ || !text(receipt.get("apiConfigRevision")).equals(api.configRevision())
+ || !text(receipt.get("trustBindingDigest")).equals(materializer.bindingDigest())
+ || !text(receipt.get("trustConfigRevision")).equals(materializer.configRevision())) {
+ throw denied();
+ }
+ Binding binding =
+ new Binding(
+ materializer.environmentId(),
+ materializer.clusterId(),
+ materializer.namespace(),
+ CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK);
+ TrustFence trust =
+ new TrustFence(
+ materializer.expectedClusterIncarnationUid(),
+ materializer.expectedNamespaceUid(),
+ materializer.bindingDigest(),
+ materializer.configRevision());
+ var original =
+ signerStates
+ .readOriginalCommittedSigner(
+ binding,
+ trust,
+ api.bindingDigest(),
+ api.configRevision(),
+ uuid(receipt.get("promotionOperationId")),
+ uuid(receipt.get("generationOperationId")))
+ .orElseThrow(AccountControlUiCurrentActorVerifier::denied);
+ var promotion = original.promotion();
+ var generation = original.generationResult();
+ if (!"COMMITTED".equals(promotion.status())
+ || !promotion.operationId().toString().equals(receipt.get("promotionOperationId"))
+ || !promotion.requestDigest().equals(receipt.get("promotionRequestDigest"))
+ || !generation.operationId().toString().equals(receipt.get("generationOperationId"))
+ || !verifiedKid.equals(generation.targetKid())
+ || !generation.targetGeneration().equals(receipt.get("signerGeneration"))
+ || !"RS256".equals(generation.targetAlgorithm())
+ || !generation.publicKeyFingerprint().equals(receipt.get("publicKeyFingerprint"))
+ || !original.privateReceipt().receiptDigest().equals(receipt.get("privateReceiptDigest"))
+ || !original
+ .privateReceipt()
+ .observedResourceVersion()
+ .equals(receipt.get("privateResourceVersion"))
+ || !original.publicReceipt().receiptDigest().equals(receipt.get("publicReceiptDigest"))
+ || !original
+ .publicReceipt()
+ .observedResourceVersion()
+ .equals(receipt.get("publicResourceVersion"))
+ || !original.publicReceipt().configMapUid().equals(receipt.get("publicConfigMapUid"))
+ || !original.publicReceipt().publicDataDigest().equals(receipt.get("publicDataDigest"))) {
+ throw denied();
+ }
+ }
+
+ private CurrentActor requireCurrentAccountAuthority(
+ CommittedIssuance issuance, Map claims, UUID tenantId, String tokenHash) {
+ UUID accountId = issuance.accountId();
+ IssuerAccountSourceSnapshot source =
+ sourceEvidence.readCurrentIssuerAccountSources(ISSUER, accountId);
+ CompositeSnapshot snapshot =
+ generations.readCompositeSnapshot(ISSUER, accountId, List.of(tenantId), List.of(tenantId));
+ if (source.issuer().generation() != snapshot.issuer().generation()
+ || source.issuer().sourceVersion() != snapshot.issuer().sourceVersion()
+ || source.account().generation() != snapshot.account().generation()
+ || source.account().sourceVersion() != snapshot.account().sourceVersion()
+ || !source.issuanceFence().equals(snapshot.issuanceFence())) {
+ throw denied();
+ }
+ var tenantState = only(snapshot.tenants(), "tenant authority");
+ var membershipState = only(snapshot.memberships(), "membership authority");
+ Event currentTenant = tenantEvents.readCurrentByTenant(tenantId);
+ if (!tenantId.equals(currentTenant.tenantId())
+ || currentTenant.tenantAuthorityGeneration() != tenantState.generation()
+ || currentTenant.tenantAuthoritySourceVersion() != tenantState.sourceVersion()) {
+ throw denied();
+ }
+
+ PairAuthority pair =
+ membershipPairs
+ .readPositive(accountId, tenantId)
+ .orElseThrow(AccountControlUiCurrentActorVerifier::denied);
+ AccountTenantMembership membership =
+ memberships
+ .findFreshMembership(accountId, tenantId)
+ .orElseThrow(AccountControlUiCurrentActorVerifier::denied);
+ if (!pair.membershipExists()
+ || pair.eventSequence() <= 0L
+ || pair.lastTransitionInvalidated()
+ || membership.getId() == null
+ || membership.getAccount() == null
+ || membership.getAccount().getId() == null
+ || !accountId.equals(membership.getAccount().getAccountUuid())
+ || !tenantId.equals(membership.getTenantUuid())
+ || !"ACTIVE".equals(membership.getLifecycleState())
+ || membership.getMembershipVersion() != pair.membershipVersion()
+ || membership.getMembershipAuthorityGeneration() != pair.membershipAuthorityGeneration()
+ || pair.membershipAuthorityGeneration() != membershipState.generation()) {
+ throw denied();
+ }
+ MembershipEvent currentMembershipEvent =
+ requireCurrentMembershipEvent(accountId, tenantId, pair, membershipState.generation());
+ RoleSnapshot roles =
+ roleSnapshots
+ .findForCanonicalUpdate(
+ accountId,
+ tenantId,
+ pair.provenance(),
+ membership.getId(),
+ membership.getMembershipVersion())
+ .orElseThrow(AccountControlUiCurrentActorVerifier::denied);
+ if (!roles.roles().equals(currentMembershipEvent.roles())) {
+ throw denied();
+ }
+ requireClaimsCurrent(
+ claims, accountId, tenantId, source, snapshot, currentTenant, pair, membership, roles);
+ return new CurrentActor(
+ accountId,
+ tenantId,
+ issuance.operationId(),
+ tokenHash,
+ roles.roles(),
+ snapshot.issuer().generation(),
+ snapshot.account().generation(),
+ tenantState.generation(),
+ membershipState.generation(),
+ membership.getMembershipVersion(),
+ snapshot.issuanceFence().value());
+ }
+
+ private MembershipEvent requireCurrentMembershipEvent(
+ UUID accountId, UUID tenantId, PairAuthority pair, long membershipGeneration) {
+ String streamKey =
+ MembershipAuthorityEventV1Codec.EVENT_STREAM_PREFIX
+ + "membership/"
+ + accountId
+ + "/"
+ + tenantId;
+ var stored =
+ outbox
+ .findEvent(streamKey, pair.eventSequence())
+ .orElseThrow(AccountControlUiCurrentActorVerifier::denied);
+ MembershipEvent event =
+ MembershipAuthorityEventV1Codec.verify(
+ new String(stored.payload(), StandardCharsets.UTF_8));
+ if (!stored.outboxStreamKey().equals(streamKey)
+ || !stored.eventId().equals(event.eventId())
+ || !stored.eventDigest().equals(event.eventDigest())
+ || !Long.toString(stored.outboxSequence()).equals(event.outboxSequence())
+ || !pair.eventId().equals(event.eventId())
+ || !pair.eventDigest().equals(event.eventDigest())
+ || !accountId.toString().equals(event.accountId())
+ || !tenantId.toString().equals(event.tenantId())
+ || !Long.toString(pair.membershipVersion())
+ .equals(event.membershipVersion().get(tenantId.toString()))
+ || !Long.toString(membershipGeneration).equals(event.membershipAuthorityGeneration())
+ || !"ACTIVE".equals(event.membershipLifecycleState())
+ || event.callerBoundAuthorityInvalidated() != pair.lastTransitionInvalidated()) {
+ throw denied();
+ }
+ return event;
+ }
+
+ private void requireClaimsCurrent(
+ Map claims,
+ UUID accountId,
+ UUID tenantId,
+ IssuerAccountSourceSnapshot source,
+ CompositeSnapshot snapshot,
+ Event tenantEvent,
+ PairAuthority pair,
+ AccountTenantMembership membership,
+ RoleSnapshot roles) {
+ Map tuple = object(claims.get("authorityTuple"));
+ Map tenantGenerations =
+ Map.of(tenantId.toString(), only(snapshot.tenants(), "tenant").generation());
+ Map membershipGenerations =
+ Map.of(tenantId.toString(), pair.membershipAuthorityGeneration());
+ Map membershipVersions = Map.of(tenantId.toString(), pair.membershipVersion());
+ Map expectedTuple = new LinkedHashMap<>();
+ expectedTuple.put("issuerAuthGeneration", snapshot.issuer().generation());
+ expectedTuple.put("accountAuthorityGeneration", snapshot.account().generation());
+ expectedTuple.put("tenantAuthorityGeneration", tenantGenerations);
+ expectedTuple.put("membershipAuthorityGeneration", membershipGenerations);
+ expectedTuple.put("privateRealmGrantVersions", List.of());
+ source
+ .account()
+ .accountSecurityCutoff()
+ .ifPresent(
+ cutoff ->
+ expectedTuple.put(
+ "accountSecurityCutoff",
+ Map.of(
+ "accountAuthorityGeneration",
+ Long.parseLong(cutoff.accountAuthorityGeneration()),
+ "outboxStreamKey",
+ cutoff.outboxStreamKey(),
+ "outboxSequence",
+ Long.parseLong(cutoff.outboxSequence()))));
+ if (tuple.containsKey("tenantBillingCutoff")) {
+ expectedTuple.put(
+ "tenantBillingCutoff",
+ Map.of(
+ tenantId.toString(),
+ Map.of(
+ "tenantAuthorityGeneration",
+ tenantEvent.tenantAuthorityGeneration(),
+ "tenantBillingSequence",
+ tenantEvent.tenantBillingSequence(),
+ "outboxStreamKey",
+ tenantEvent.tenantBillingStreamKey(),
+ "outboxSequence",
+ tenantEvent.outboxSequence())));
+ }
+ Map scoped = object(claims.get("scopedRoles"));
+ if (!numericEquals(tuple.get("issuerAuthGeneration"), snapshot.issuer().generation())
+ || !numericEquals(tuple.get("accountAuthorityGeneration"), snapshot.account().generation())
+ || !canonicalMapEquals(tuple.get("tenantAuthorityGeneration"), tenantGenerations)
+ || !canonicalMapEquals(tuple.get("membershipAuthorityGeneration"), membershipGenerations)
+ || !canonicalMapEquals(tuple, expectedTuple)
+ || !canonicalMapEquals(claims.get("membershipVersion"), membershipVersions)
+ || !numericEquals(claims.get("issuanceFence"), snapshot.issuanceFence().value())
+ || !canonicalMapEquals(scoped, Map.of(tenantId.toString(), roles.roles()))
+ || membership.getMembershipVersion() != pair.membershipVersion()
+ || !accountId.equals(membership.getAccount().getAccountUuid())) {
+ throw denied();
+ }
+ }
+
+ private static byte[] derivePendingRegistry(byte[] activeBytes) {
+ Map active =
+ parseCanonicalObject(activeBytes, AccountControlUiRegistryReader.MAX_RECORD_BYTES);
+ if (!"active".equals(active.get("state"))
+ || !Integer.valueOf(2).equals(number(active.get("registryVersion")))) {
+ throw denied();
+ }
+ Map pending = new LinkedHashMap<>(active);
+ pending.put("state", "pending");
+ pending.put("registryVersion", 1);
+ return canonicalBytes(pending);
+ }
+
+ private static Map tokenIdentity(Map claims) {
+ Map identity = new LinkedHashMap<>();
+ identity.put("jti", claims.get("jti"));
+ identity.put("tokenGeneration", claims.get("tokenGeneration"));
+ identity.put("iat", claims.get("iat"));
+ identity.put("nbf", claims.get("nbf"));
+ identity.put("exp", claims.get("exp"));
+ return identity;
+ }
+
+ private static UUID selectedScopedTenant(Map claims, UUID selectedTenant) {
+ Map roles = object(claims.get("scopedRoles"));
+ if (!roles.keySet().equals(Set.of(selectedTenant.toString()))) {
+ throw denied();
+ }
+ return selectedTenant;
+ }
+
+ private static AccountAuthorityGenerationRepository.ScopeState only(
+ List states, String label) {
+ if (states == null || states.size() != 1) {
+ throw denied();
+ }
+ return states.getFirst();
+ }
+
+ private static Map parseCanonicalObject(byte[] bytes, int maximum) {
+ if (bytes == null || bytes.length == 0 || bytes.length > maximum) {
+ throw denied();
+ }
+ try {
+ String json =
+ StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(bytes)).toString();
+ if (!Arrays.equals(bytes, Rfc8785CanonicalJson.canonicalizeUtf8(json))) {
+ throw denied();
+ }
+ Map fields = JSON.readValue(bytes, OBJECT);
+ if (fields == null) {
+ throw denied();
+ }
+ return Map.copyOf(fields);
+ } catch (IOException | RuntimeException malformed) {
+ throw denied();
+ }
+ }
+
+ private static Map object(Object value) {
+ if (!(value instanceof Map, ?> map)) {
+ throw denied();
+ }
+ Map result = new LinkedHashMap<>();
+ map.forEach(
+ (key, item) -> {
+ if (!(key instanceof String text)) {
+ throw denied();
+ }
+ result.put(text, item);
+ });
+ return result;
+ }
+
+ private static boolean canonicalMapEquals(Object first, Object second) {
+ return Arrays.equals(canonicalBytes(first), canonicalBytes(second));
+ }
+
+ private static byte[] canonicalBytes(Object value) {
+ try {
+ return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value));
+ } catch (IOException | RuntimeException failure) {
+ throw denied();
+ }
+ }
+
+ private static boolean numericEquals(Object actual, long expected) {
+ return actual instanceof Number number && number.toString().equals(Long.toString(expected));
+ }
+
+ private static Number number(Object value) {
+ return value instanceof Number number ? number : null;
+ }
+
+ private static long positiveLong(Object value) {
+ if (!(value instanceof Number number)) {
+ throw denied();
+ }
+ try {
+ long parsed = Long.parseLong(number.toString());
+ if (parsed <= 0L) {
+ throw denied();
+ }
+ return parsed;
+ } catch (NumberFormatException malformed) {
+ throw denied();
+ }
+ }
+
+ private static boolean atLeastOne(Object value) {
+ return value instanceof Number number
+ && number.toString().matches("[1-9][0-9]{0,2}")
+ && number.longValue() >= 1L;
+ }
+
+ private static UUID uuid(Object value) {
+ if (!(value instanceof String text)) {
+ throw denied();
+ }
+ try {
+ UUID parsed = UUID.fromString(text);
+ if (!parsed.toString().equals(text)
+ || parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) {
+ throw denied();
+ }
+ return parsed;
+ } catch (IllegalArgumentException malformed) {
+ throw denied();
+ }
+ }
+
+ private static String text(Object value) {
+ return value instanceof String text ? text : "";
+ }
+
+ private static String sha256(byte[] bytes) {
+ try {
+ return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
+ } catch (NoSuchAlgorithmException unavailable) {
+ throw denied();
+ }
+ }
+
+ private static byte[] compactBytes(String compactJwt) {
+ if (compactJwt == null
+ || compactJwt.isBlank()
+ || compactJwt.length() > 16384
+ || compactJwt.codePoints().anyMatch(codePoint -> codePoint > 0x7f)) {
+ throw denied();
+ }
+ return compactJwt.getBytes(StandardCharsets.US_ASCII);
+ }
+
+ private static void requireTenant(UUID tenant) {
+ if (tenant == null
+ || tenant.getMostSignificantBits() == 0L && tenant.getLeastSignificantBits() == 0L) {
+ throw denied();
+ }
+ }
+
+ private static void outsideSql() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException(
+ "Account JWT and Coordination reads must precede SQL ownership");
+ }
+ }
+
+ private static IllegalStateException denied() {
+ return new IllegalStateException("Current Account control-ui actor evidence unavailable");
+ }
+
+ /**
+ * Identity and current source tuple only. It is not a route authorization or a reference grant.
+ */
+ public record CurrentActor(
+ UUID accountId,
+ UUID tenantId,
+ UUID issuanceOperationId,
+ String tokenHash,
+ List currentTenantRoles,
+ long issuerGeneration,
+ long accountGeneration,
+ long tenantGeneration,
+ long membershipGeneration,
+ long membershipVersion,
+ long issuanceFence) {
+ public CurrentActor {
+ Objects.requireNonNull(accountId);
+ Objects.requireNonNull(tenantId);
+ Objects.requireNonNull(issuanceOperationId);
+ if (tokenHash == null || !DIGEST.matcher(tokenHash).matches()) {
+ throw new IllegalArgumentException("Control-ui actor token identity is invalid");
+ }
+ currentTenantRoles = List.copyOf(currentTenantRoles);
+ if (issuerGeneration <= 0L
+ || accountGeneration <= 0L
+ || tenantGeneration <= 0L
+ || membershipGeneration <= 0L
+ || membershipVersion <= 0L
+ || issuanceFence <= 0L) {
+ throw new IllegalArgumentException("Control-ui current authority values must be positive");
+ }
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java
new file mode 100644
index 0000000000..7935bc39be
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java
@@ -0,0 +1,589 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.nio.charset.StandardCharsets;
+import java.sql.Connection;
+import java.time.Instant;
+import java.time.OffsetDateTime;
+import java.util.Arrays;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority;
+import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl.ControlUiPrimaryIdentity;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.core.type.TypeReference;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.json.JsonMapper;
+
+/** Genuine durable control-ui owner state. No caller-provided registry or evidence is accepted. */
+public final class AccountControlUiIssuanceRepository {
+ private static final String TABLE = "account_control_ui_issuance_operations";
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+ private static final Pattern TRANSACTION_ID = Pattern.compile("[1-9][0-9]{0,19}");
+ private final DSLContext dsl;
+
+ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification = "Injected DSLContext is an internal Account transaction collaborator.")
+ public AccountControlUiIssuanceRepository(DSLContext dsl) {
+ this.dsl = Objects.requireNonNull(dsl);
+ }
+
+ Stored findRequest(UUID requestId) {
+ requireTransaction();
+ Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE request_id = ?", requestId);
+ return row == null ? null : new Stored(row);
+ }
+
+ Stored findToken(String tokenHash) {
+ requireTransaction();
+ Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE token_hash = ?", tokenHash);
+ return row == null ? null : new Stored(row);
+ }
+
+ Stored findTokenJti(UUID tokenJti) {
+ requireTransaction();
+ Objects.requireNonNull(tokenJti, "control-ui token jti is required");
+ Record row = dsl.fetchOne("SELECT * FROM " + TABLE + " WHERE token_jti = ?", tokenJti);
+ return row == null ? null : new Stored(row);
+ }
+
+ /** Account-owned linearization from the caller's existing current-source transaction. */
+ public OwnerLinearization captureOwnerLinearization() {
+ requireTransaction();
+ Record row =
+ dsl.fetchOne(
+ "SELECT pg_current_xact_id()::TEXT AS xid, "
+ + "nextval('account_control_ui_source_fence') AS fence");
+ String transactionId = row == null ? null : row.get("xid", String.class);
+ Long sourceFence = row == null ? null : row.get("fence", Long.class);
+ if (transactionId == null
+ || !TRANSACTION_ID.matcher(transactionId).matches()
+ || sourceFence == null
+ || sourceFence <= 0L) {
+ throw denied();
+ }
+ return new OwnerLinearization(transactionId, sourceFence);
+ }
+
+ Stored prepare(
+ UUID requestId,
+ String caller,
+ UUID callerContextId,
+ String macKeyId,
+ String digest,
+ ControlUiPrimaryIdentity authenticated,
+ AccountControlUiAuthority.Snapshot source,
+ AccountControlUiSignerOwner.Capture signer,
+ Instant issuedAt) {
+ requireTransaction();
+ if (!authenticated.accountId().equals(source.actor())) {
+ throw denied();
+ }
+ UUID operationId = UUID.randomUUID();
+ UUID jti = UUID.randomUUID();
+ Instant expiry = issuedAt.plusSeconds(300);
+ Instant recovery = issuedAt.plusSeconds(60);
+ var spec =
+ new AccountControlUiSigningSpec(operationId, requestId, jti, source, issuedAt, expiry);
+ var transaction =
+ dsl.fetchOne(
+ "SELECT pg_current_xact_id()::TEXT AS xid, nextval('account_control_ui_source_fence') AS fence");
+ if (transaction == null) {
+ throw denied();
+ }
+ String xid = transaction.get("xid", String.class);
+ Long fence = transaction.get("fence", Long.class);
+ if (xid == null || !xid.matches("[1-9][0-9]{0,19}") || fence == null || fence <= 0) {
+ throw denied();
+ }
+ Map ref =
+ Map.of(
+ "bundleVersion",
+ "1",
+ "sourceVersion",
+ xid,
+ "sourceFence",
+ Long.toString(fence),
+ "linearization",
+ xid);
+ Map operation =
+ Map.of(
+ "operationId",
+ operationId.toString(),
+ "requestId",
+ requestId.toString(),
+ "requestDigest",
+ digest,
+ "callerWorkload",
+ caller,
+ "callerContextId",
+ callerContextId.toString(),
+ "accountId",
+ source.actor().toString());
+ var bundle = new LinkedHashMap();
+ bundle.put("schema", "account-auth-evidence-bundle/v1");
+ bundle.put("bundleRef", ref);
+ bundle.put("snapshotIdentity", hash(source.evidence()));
+ bundle.put(
+ "evaluationIdentity",
+ hash(
+ AccountControlUiAuthority.canonical(
+ Map.of(
+ "operation",
+ operation,
+ "claims",
+ spec.claims(),
+ "bundleRef",
+ ref,
+ "snapshotIdentity",
+ hash(source.evidence())))));
+ bundle.put("issuer", "firemud-account-service");
+ bundle.put("profile", "control-ui");
+ bundle.put("audience", "control-ui");
+ bundle.put(
+ "scope",
+ Map.of(
+ "kind",
+ "TENANT",
+ "accountId",
+ source.actor().toString(),
+ "tenantIds",
+ java.util.List.of(source.tenant().toString())));
+ bundle.put("operation", operation);
+ bundle.put(
+ "tokenIdentity",
+ Map.of(
+ "jti",
+ jti.toString(),
+ "tokenGeneration",
+ 1,
+ "iat",
+ issuedAt.getEpochSecond(),
+ "nbf",
+ issuedAt.getEpochSecond(),
+ "exp",
+ expiry.getEpochSecond()));
+ bundle.put("authorityTuple", source.authorityTuple());
+ bundle.put("membershipVersion", source.membershipVersion());
+ bundle.put("issuanceFence", source.issuanceFence());
+ Map versions = new LinkedHashMap<>();
+ source.sources().forEach(value -> versions.put(value.key(), value.sourceVersion()));
+ bundle.put("authoritySourceVersions", Map.copyOf(versions));
+ bundle.put("accountIdentitySource", source.accountIdentitySource());
+ bundle.put("outboxCheckpoints", source.outboxCheckpoints());
+ bundle.put(
+ "roleEvidence",
+ Map.of(
+ "scopedRoles",
+ spec.claims().get("scopedRoles"),
+ "freshnessSource",
+ hash(source.evidence())));
+ int inserted =
+ dsl.execute(
+ "INSERT INTO "
+ + TABLE
+ + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload,"
+ + " caller_context_id, request_mac_key_id, request_digest, claims_payload, source_payload,"
+ + " bundle_payload, signer_receipt, issued_at_epoch_second, expires_at_epoch_second,"
+ + " recovery_expires_at, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')"
+ + " ON CONFLICT (request_id) DO NOTHING",
+ requestId,
+ operationId,
+ jti,
+ source.actor(),
+ source.tenant(),
+ caller,
+ callerContextId,
+ macKeyId,
+ digest,
+ AccountControlUiAuthority.canonical(spec.claims()),
+ source.evidence(),
+ AccountControlUiAuthority.canonical(bundle),
+ signer.receipt(),
+ issuedAt.getEpochSecond(),
+ expiry.getEpochSecond(),
+ OffsetDateTime.ofInstant(recovery, java.time.ZoneOffset.UTC));
+ Stored stored = findRequest(requestId);
+ if (inserted != 1 || stored == null || !operationId.equals(stored.operationId)) {
+ throw denied();
+ }
+ // The complete fixed-width digest field permits both final registry sizes to be checked now,
+ // before any private signing or Coordination mutation. No placeholder is retained as evidence.
+ registry(stored, signer, "0".repeat(64), false);
+ registry(stored, signer, "0".repeat(64), true);
+ return stored;
+ }
+
+ Stored bindCandidate(
+ Stored original,
+ String tokenHash,
+ byte[] envelope,
+ byte[] binding,
+ AccountControlUiSignerOwner.Capture signer) {
+ requireTransaction();
+ Stored current = lockExact(original);
+ if (!Arrays.equals(current.signerReceipt, signer.receipt())
+ || !"PREPARED".equals(current.status)) {
+ throw denied();
+ }
+ byte[] pending = registry(current, signer, tokenHash, false);
+ byte[] active = registry(current, signer, tokenHash, true);
+ dsl.execute(
+ "INSERT INTO account_control_ui_response_envelopes"
+ + " (operation_id, encrypted_response, owner_binding, recovery_expires_at) VALUES (?, ?, ?, ?::timestamptz)",
+ current.operationId,
+ envelope,
+ binding,
+ OffsetDateTime.ofInstant(current.recoveryExpiry, java.time.ZoneOffset.UTC));
+ if (dsl.execute(
+ "UPDATE "
+ + TABLE
+ + " SET status = 'CANDIDATE', token_hash = ?, pending_registry = ?, active_registry = ?"
+ + " WHERE operation_id = ? AND status = 'PREPARED'",
+ tokenHash,
+ pending,
+ active,
+ current.operationId)
+ != 1) {
+ throw denied();
+ }
+ return findRequest(current.requestId);
+ }
+
+ Committed commit(Stored original, AccountControlUiCoordination.Receipt pending) {
+ requireTransaction();
+ Stored current = lockExact(original);
+ if (!Objects.equals(current.tokenHash, pending.tokenHash)
+ || !hash(current.pendingRegistry).equals(pending.recordDigest)
+ || current.expiryMillis() != pending.expiryMillis
+ || !"CANDIDATE".equals(current.status)) {
+ throw denied();
+ }
+ byte[] receipt =
+ AccountControlUiAuthority.canonical(
+ Map.of(
+ "schema",
+ "account-control-ui-pending-readback/v1",
+ "tokenHash",
+ pending.tokenHash,
+ "recordDigest",
+ pending.recordDigest,
+ "expiryMillis",
+ pending.expiryMillis,
+ "aclIdentity",
+ "account_coord_app",
+ "localAofCount",
+ pending.localAof,
+ "replicaAofCount",
+ pending.replicas));
+ if (dsl.execute(
+ "UPDATE "
+ + TABLE
+ + " SET status = 'COMMITTED', pending_receipt = ?, committed_at = CURRENT_TIMESTAMP"
+ + " WHERE operation_id = ? AND status = 'CANDIDATE'",
+ receipt,
+ current.operationId)
+ != 1) {
+ throw denied();
+ }
+ return requireCommitted(findRequest(current.requestId));
+ }
+
+ Committed requireCommitted(Stored original) {
+ Stored current = lockExact(original);
+ if (!"COMMITTED".equals(current.status)) {
+ throw denied();
+ }
+ return new Committed(current);
+ }
+
+ /** Durable non-authorizing intent precedes any external revocation; no source recapture. */
+ Stored beginRecoveryFailure(Stored original) {
+ Stored current = lockExact(original);
+ if (java.util.List.of("FAILED", "REVOKING", "REVOKED").contains(current.status)) {
+ return current;
+ }
+ String next = current.tokenHash == null ? "FAILED" : "REVOKING";
+ if (dsl.execute(
+ "UPDATE "
+ + TABLE
+ + " SET status = ?, recovery_failed_at = CURRENT_TIMESTAMP"
+ + " WHERE operation_id = ? AND status = ?",
+ next,
+ current.operationId,
+ current.status)
+ != 1) {
+ throw denied();
+ }
+ return findRequest(current.requestId);
+ }
+
+ void finishRecoveryFailure(Stored original, AccountControlUiCoordination.Receipt receipt) {
+ Stored current = lockExact(original);
+ if (!"REVOKING".equals(current.status)
+ || !Objects.equals(current.tokenHash, receipt.tokenHash)
+ || !hash(revokedRegistry(current)).equals(receipt.recordDigest)
+ || current.expiryMillis() != receipt.expiryMillis) {
+ throw denied();
+ }
+ byte[] evidence =
+ AccountControlUiAuthority.canonical(
+ Map.of(
+ "schema",
+ "account-control-ui-revoked-readback/v1",
+ "tokenHash",
+ receipt.tokenHash,
+ "recordDigest",
+ receipt.recordDigest,
+ "expiryMillis",
+ receipt.expiryMillis,
+ "aclIdentity",
+ "account_coord_app",
+ "localAofCount",
+ receipt.localAof,
+ "replicaAofCount",
+ receipt.replicas));
+ if (dsl.execute(
+ "UPDATE "
+ + TABLE
+ + " SET status = 'REVOKED', revocation_receipt = ?"
+ + " WHERE operation_id = ? AND status = 'REVOKING'",
+ evidence,
+ current.operationId)
+ != 1) {
+ throw denied();
+ }
+ }
+
+ static byte[] revokedRegistry(Stored original) {
+ if (!"REVOKING".equals(original.status)) {
+ throw denied();
+ }
+ var record = new LinkedHashMap(object(original.pendingRegistry));
+ record.put("state", "revoked");
+ record.put("registryVersion", 3);
+ return AccountControlUiAuthority.canonical(record);
+ }
+
+ Envelope envelope(Stored original) {
+ requireTransaction();
+ Record value =
+ dsl.fetchOne(
+ "SELECT encrypted_response, owner_binding, recovery_expires_at"
+ + " FROM account_control_ui_response_envelopes WHERE operation_id = ?",
+ original.operationId);
+ if (value == null) {
+ return null;
+ }
+ if (!value
+ .get("recovery_expires_at", OffsetDateTime.class)
+ .toInstant()
+ .equals(original.recoveryExpiry)) {
+ return null;
+ }
+ return new Envelope(
+ value.get("encrypted_response", byte[].class), value.get("owner_binding", byte[].class));
+ }
+
+ private Stored lockExact(Stored original) {
+ requireTransaction();
+ Record row =
+ dsl.fetchOne(
+ "SELECT * FROM " + TABLE + " WHERE operation_id = ? FOR UPDATE", original.operationId);
+ if (row == null) {
+ throw denied();
+ }
+ Stored current = new Stored(row);
+ if (!original.requestId.equals(current.requestId)
+ || !Arrays.equals(original.claims, current.claims)
+ || !Arrays.equals(original.sources, current.sources)
+ || !Arrays.equals(original.bundle, current.bundle)
+ || !Arrays.equals(original.signerReceipt, current.signerReceipt)
+ || !original.requestDigest.equals(current.requestDigest)) {
+ throw denied();
+ }
+ return current;
+ }
+
+ private static byte[] registry(
+ Stored value, AccountControlUiSignerOwner.Capture signer, String tokenHash, boolean active) {
+ var claims = object(value.claims);
+ var bundle = object(value.bundle);
+ var result = new LinkedHashMap();
+ result.put("schemaVersion", 1);
+ result.put("registryVersion", active ? 2 : 1);
+ result.put("tokenHash", tokenHash);
+ result.put("kid", signer.kid());
+ result.put("signerGeneration", signer.generation());
+ result.put("issuer", "firemud-account-service");
+ result.put("profile", "control-ui");
+ result.put("type", "control-ui");
+ result.put("audience", "control-ui");
+ for (String field :
+ java.util.List.of(
+ "accountId",
+ "jti",
+ "iat",
+ "nbf",
+ "exp",
+ "tokenGeneration",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence")) {
+ result.put(field, claims.get(field));
+ }
+ result.put("operationId", value.operationId.toString());
+ result.put("requestId", value.requestId.toString());
+ result.put("requestDigest", value.requestDigest);
+ result.put("state", active ? "active" : "pending");
+ result.put("authoritySourceVersions", bundle.get("authoritySourceVersions"));
+ var reference = new LinkedHashMap();
+ @SuppressWarnings("unchecked")
+ var bundleRef = (Map) bundle.get("bundleRef");
+ reference.putAll(bundleRef);
+ reference.put("canonicalSha256", hash(value.bundle));
+ result.put("authEvidenceBundle", Map.copyOf(reference));
+ result.put("originalSignerReceiptDigest", hash(value.signerReceipt));
+ byte[] bytes = AccountControlUiAuthority.canonical(result);
+ if (bytes.length > 32768) {
+ throw denied();
+ }
+ return bytes;
+ }
+
+ static Map object(byte[] bytes) {
+ try {
+ return JSON.readValue(new String(bytes, StandardCharsets.UTF_8), new TypeReference<>() {});
+ } catch (RuntimeException failure) {
+ throw denied();
+ }
+ }
+
+ static String hash(byte[] bytes) {
+ return AccountControlUiCoordination.digest("SHA-256", bytes);
+ }
+
+ private void requireTransaction() {
+ if (!TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
+ throw denied();
+ }
+ dsl.connection(
+ connection -> {
+ if (connection.getAutoCommit()
+ || connection.isReadOnly()
+ || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) {
+ throw denied();
+ }
+ });
+ }
+
+ static final class Stored {
+ final UUID requestId, operationId, jti, accountId, tenantId, callerContextId;
+ final String caller, requestMacKeyId, requestDigest, status, tokenHash;
+ final byte[] claims, sources, bundle, signerReceipt, pendingRegistry, activeRegistry;
+ final Instant issuedAt, expiresAt, recoveryExpiry;
+
+ Stored(Record row) {
+ requestId = row.get("request_id", UUID.class);
+ operationId = row.get("operation_id", UUID.class);
+ jti = row.get("token_jti", UUID.class);
+ accountId = row.get("account_uuid", UUID.class);
+ tenantId = row.get("tenant_uuid", UUID.class);
+ callerContextId = row.get("caller_context_id", UUID.class);
+ caller = row.get("caller_workload", String.class);
+ requestMacKeyId = row.get("request_mac_key_id", String.class);
+ requestDigest = row.get("request_digest", String.class);
+ status = row.get("status", String.class);
+ tokenHash = row.get("token_hash", String.class);
+ claims = row.get("claims_payload", byte[].class);
+ sources = row.get("source_payload", byte[].class);
+ bundle = row.get("bundle_payload", byte[].class);
+ signerReceipt = row.get("signer_receipt", byte[].class);
+ pendingRegistry = row.get("pending_registry", byte[].class);
+ activeRegistry = row.get("active_registry", byte[].class);
+ issuedAt = Instant.ofEpochSecond(row.get("issued_at_epoch_second", Long.class));
+ expiresAt = Instant.ofEpochSecond(row.get("expires_at_epoch_second", Long.class));
+ recoveryExpiry = row.get("recovery_expires_at", OffsetDateTime.class).toInstant();
+ }
+
+ long expiryMillis() {
+ return expiresAt.toEpochMilli();
+ }
+
+ @Override
+ public String toString() {
+ return "AccountControlUiIssuanceRepository.Stored[redacted]";
+ }
+ }
+
+ public record OwnerLinearization(String transactionId, long sourceFence) {
+ public OwnerLinearization {
+ if (transactionId == null
+ || !TRANSACTION_ID.matcher(transactionId).matches()
+ || sourceFence <= 0L) {
+ throw denied();
+ }
+ }
+ }
+
+ public static final class Committed {
+ final Stored stored;
+
+ private Committed(Stored stored) {
+ this.stored = stored;
+ }
+
+ public String tokenHash() {
+ return stored.tokenHash;
+ }
+
+ public byte[] pendingRegistry() {
+ return stored.pendingRegistry.clone();
+ }
+
+ public byte[] activeRegistry() {
+ return stored.activeRegistry.clone();
+ }
+
+ public long expiryMillis() {
+ return stored.expiryMillis();
+ }
+
+ @Override
+ public String toString() {
+ return "AccountControlUiIssuanceRepository.Committed[redacted]";
+ }
+ }
+
+ record Envelope(byte[] encrypted, byte[] binding) {
+ Envelope {
+ encrypted = encrypted.clone();
+ binding = binding.clone();
+ }
+
+ @Override
+ public byte[] encrypted() {
+ return encrypted.clone();
+ }
+
+ @Override
+ public byte[] binding() {
+ return binding.clone();
+ }
+ }
+
+ private static IllegalStateException denied() {
+ return new IllegalStateException("Exact Account control-ui issuance owner evidence required");
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java
new file mode 100644
index 0000000000..7541f70084
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java
@@ -0,0 +1,422 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority;
+import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository;
+import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary;
+import net.firedevops.firemud.accountservice.service.exception.AuthenticationException;
+import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl;
+import net.firedevops.firemud.common.EmailCanonicalization;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.TransactionDefinition;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Minimum genuine backend creator issuance/recovery, deliberately unregistered and unmounted.
+ * Primary credentials, existing owner sources and actual Coordination are all required. An
+ * independently protected exact peer binding supplies transport identity, never creator authority.
+ */
+public final class AccountControlUiIssuanceService {
+ private final AccountServiceImpl primaryAuthentication;
+ private final AccountControlUiIssuanceRepository operations;
+ private final AccountControlUiAuthority authority;
+ private final DraftAuthorizationFenceRepository fences;
+ private final AccountControlUiSignerOwner signers;
+ private final AccountControlUiResponseCryptography cryptography;
+ private final AccountControlUiCoordination registry;
+ private final AccountControlUiActorService actors;
+ private final TransactionTemplate transaction;
+ private final Clock clock;
+ private final String protectedCallerUri;
+
+ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification =
+ "Injected primary authentication and Draft fence services remain internal Account owner collaborators.")
+ public AccountControlUiIssuanceService(
+ AccountServiceImpl primaryAuthentication,
+ AccountControlUiIssuanceRepository operations,
+ AccountControlUiAuthority authority,
+ DraftAuthorizationFenceRepository fences,
+ AccountControlUiSignerOwner signers,
+ AccountControlUiResponseCryptography cryptography,
+ AccountControlUiCoordination registry,
+ AccountControlUiActorService actors,
+ PlatformTransactionManager transactions,
+ Clock clock,
+ String independentlyProtectedCallerUri) {
+ this.primaryAuthentication = Objects.requireNonNull(primaryAuthentication);
+ this.operations = Objects.requireNonNull(operations);
+ this.authority = Objects.requireNonNull(authority);
+ this.fences = Objects.requireNonNull(fences);
+ this.signers = Objects.requireNonNull(signers);
+ this.cryptography = Objects.requireNonNull(cryptography);
+ this.registry = Objects.requireNonNull(registry);
+ this.actors = Objects.requireNonNull(actors);
+ this.clock = Objects.requireNonNull(clock);
+ protectedCallerUri =
+ GrpcPeerIdentity.parseUri(independentlyProtectedCallerUri)
+ .orElseThrow(
+ () -> new IllegalArgumentException("One protected exact issuer peer URI required"))
+ .uri();
+ transaction = new TransactionTemplate(Objects.requireNonNull(transactions));
+ transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
+ }
+
+ public IssuedCredential issue(Request request, CapturedEnvironmentBoundary environment) {
+ if (TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException("Control-ui workflow cannot inherit owner SQL locks");
+ }
+ Objects.requireNonNull(request);
+ Objects.requireNonNull(environment);
+ var peer = GrpcPeerIdentity.current();
+ if (peer == null || !protectedCallerUri.equals(peer.uri())) {
+ throw denied();
+ }
+ String email = EmailCanonicalization.normalize(request.email);
+ byte[] exactRequest =
+ AccountControlUiAuthority.canonical(
+ Map.of(
+ "schema",
+ "account-control-ui-request/v1",
+ "requestId",
+ request.requestId.toString(),
+ "email",
+ email,
+ "secret",
+ request.secret,
+ "canonicalTenantId",
+ request.tenantId.toString(),
+ "callerWorkload",
+ peer.uri(),
+ "callerContextId",
+ request.callerContextId.toString()));
+ try {
+ InitialPreparation initial =
+ transaction.execute(
+ ignored -> {
+ var existing = operations.findRequest(request.requestId);
+ if (existing != null) {
+ requireRequest(existing, request, peer.uri(), exactRequest);
+ return new InitialPreparation(current(existing, environment), null);
+ }
+ // Preserve canonical tenant -> Account owner order before OTP/advisory
+ // authentication.
+ var source = authority.captureInitial(request.tenantId, environment);
+ fences.lockProducerSourcesNowait(source.sources());
+ AccountServiceImpl.ControlUiPrimaryIdentity authenticated;
+ try {
+ authenticated =
+ primaryAuthentication.authenticateControlUiPrimaryIdentity(
+ email, request.secret);
+ } catch (AuthenticationException denial) {
+ // Only primary denial commits attempt accounting. No signer/issuance work
+ // follows.
+ return new InitialPreparation(
+ null, new PrimaryDenial(denial.getCode(), denial.getMessage()));
+ }
+ if (!source.actor().equals(authenticated.accountId())) {
+ throw denied();
+ }
+ var signer = signers.captureCurrent();
+ String macKey = cryptography.currentKeyId();
+ String requestDigest = cryptography.requestDigest(macKey, exactRequest);
+ var stored =
+ operations.prepare(
+ request.requestId,
+ peer.uri(),
+ request.callerContextId,
+ macKey,
+ requestDigest,
+ authenticated,
+ source,
+ signer,
+ Instant.ofEpochSecond(clock.instant().getEpochSecond()));
+ return new InitialPreparation(new Prepared(stored, source, signer), null);
+ });
+ if (initial == null) {
+ throw denied();
+ }
+ if (initial.denial != null) {
+ throw new AuthenticationException(initial.denial.code, initial.denial.message);
+ }
+ Prepared preparation = Objects.requireNonNull(initial.prepared);
+ var original = preparation.stored;
+ if ("PREPARED".equals(original.status)) {
+ var spec =
+ new AccountControlUiSigningSpec(
+ original.operationId,
+ original.requestId,
+ original.jti,
+ preparation.source,
+ original.issuedAt,
+ original.expiresAt);
+ if (!Arrays.equals(original.claims, AccountControlUiAuthority.canonical(spec.claims()))) {
+ throw denied();
+ }
+ signers.sign(
+ preparation.signer,
+ spec,
+ (tokenHash, credential) -> {
+ String compact = new String(credential, StandardCharsets.US_ASCII);
+ var signed = actors.verifySigned(compact);
+ actors.requireSignerIdentity(original, signed);
+ if (!Arrays.equals(
+ original.claims, AccountControlUiAuthority.canonical(signed.claims.claims()))) {
+ throw denied();
+ }
+ byte[] binding = envelopeBinding(original, tokenHash);
+ byte[] encrypted = cryptography.seal(credential, binding, original.recoveryExpiry);
+ transaction.execute(
+ ignored -> {
+ var stillCurrent = current(original, environment);
+ operations.bindCandidate(
+ stillCurrent.stored, tokenHash, encrypted, binding, stillCurrent.signer);
+ return null;
+ });
+ });
+ }
+ var candidate = transaction.execute(ignored -> current(original, environment).stored);
+ if (candidate == null) {
+ throw denied();
+ }
+ AccountControlUiIssuanceRepository.Committed committed;
+ if ("CANDIDATE".equals(candidate.status)) {
+ var pending =
+ registry.registerPending(
+ candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis());
+ committed =
+ transaction.execute(
+ ignored -> {
+ var observed = current(candidate, environment);
+ return operations.commit(observed.stored, pending);
+ });
+ } else if ("COMMITTED".equals(candidate.status)) {
+ committed =
+ transaction.execute(
+ ignored -> {
+ current(candidate, environment);
+ return operations.requireCommitted(candidate);
+ });
+ } else {
+ throw denied();
+ }
+ if (committed == null) {
+ throw denied();
+ }
+ registry.activate(committed);
+ var envelope =
+ transaction.execute(
+ ignored -> {
+ current(committed.stored, environment);
+ return operations.envelope(committed.stored);
+ });
+ if (envelope == null
+ || !Arrays.equals(
+ envelope.binding(), envelopeBinding(committed.stored, committed.tokenHash()))) {
+ throw new RecoveryLost(committed.stored);
+ }
+ byte[] credential;
+ try {
+ credential =
+ cryptography.open(
+ envelope.encrypted(), envelope.binding(), committed.stored.recoveryExpiry);
+ } catch (AccountResponseEnvelopeCryptography.IntegrityException
+ | AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException permanent) {
+ throw new RecoveryLost(committed.stored);
+ }
+ try {
+ if (!committed.tokenHash().equals(AccountControlUiIssuanceRepository.hash(credential))) {
+ throw new RecoveryLost(committed.stored);
+ }
+ var actor =
+ actors.authenticate(
+ new String(credential, StandardCharsets.US_ASCII), request.tenantId, environment);
+ if (!actor.accountId().equals(committed.stored.accountId)
+ || !actor.issuanceOperationId().equals(committed.stored.operationId)) {
+ throw denied();
+ }
+ return new IssuedCredential(
+ credential, committed.stored.expiresAt, committed.stored.recoveryExpiry);
+ } finally {
+ Arrays.fill(credential, (byte) 0);
+ }
+ } catch (RecoveryLost permanent) {
+ // Caller conflicts and unavailable SQL/custody/Coordination never enter this path.
+ // Persist denial first; ambiguous/missing Redis evidence leaves REVOKING, never success.
+ var failed =
+ transaction.execute(ignored -> operations.beginRecoveryFailure(permanent.original));
+ if (failed != null && "REVOKING".equals(failed.status)) {
+ var receipt = registry.revoke(failed);
+ transaction.execute(
+ ignored -> {
+ operations.finishRecoveryFailure(failed, receipt);
+ return null;
+ });
+ }
+ throw denied();
+ } finally {
+ Arrays.fill(exactRequest, (byte) 0);
+ }
+ }
+
+ private void requireRequest(
+ AccountControlUiIssuanceRepository.Stored stored,
+ Request request,
+ String caller,
+ byte[] exactRequest) {
+ if (!stored.requestId.equals(request.requestId)
+ || !stored.tenantId.equals(request.tenantId)
+ || !stored.caller.equals(caller)
+ || !stored.callerContextId.equals(request.callerContextId)
+ || !stored.requestDigest.equals(
+ cryptography.requestDigest(stored.requestMacKeyId, exactRequest))) {
+ throw new IllegalArgumentException("Control-ui issuance idempotency conflict");
+ }
+ }
+
+ private Prepared current(
+ AccountControlUiIssuanceRepository.Stored original, CapturedEnvironmentBoundary environment) {
+ if (!clock.instant().isBefore(original.recoveryExpiry)
+ || java.util.List.of("FAILED", "REVOKING", "REVOKED").contains(original.status)) {
+ throw new RecoveryLost(original);
+ }
+ var source = authority.capture(original.accountId, original.tenantId, environment);
+ fences.lockProducerSourcesNowait(source.sources());
+ if (!Arrays.equals(source.evidence(), original.sources)) {
+ throw denied();
+ }
+ var signer = signers.requireOriginal(original.signerReceipt);
+ var stored = operations.findRequest(original.requestId);
+ if (stored == null
+ || !stored.operationId.equals(original.operationId)
+ || !Arrays.equals(stored.sources, original.sources)
+ || !Arrays.equals(stored.claims, original.claims)
+ || !Arrays.equals(stored.signerReceipt, original.signerReceipt)) {
+ throw denied();
+ }
+ return new Prepared(stored, source, signer);
+ }
+
+ private static byte[] envelopeBinding(
+ AccountControlUiIssuanceRepository.Stored original, String tokenHash) {
+ return AccountControlUiAuthority.canonical(
+ Map.ofEntries(
+ Map.entry("purpose", "account-control-ui-original-credential/v1"),
+ Map.entry("operationId", original.operationId.toString()),
+ Map.entry("requestId", original.requestId.toString()),
+ Map.entry("accountId", original.accountId.toString()),
+ Map.entry("tenantId", original.tenantId.toString()),
+ Map.entry("callerWorkload", original.caller),
+ Map.entry("callerContextId", original.callerContextId.toString()),
+ Map.entry("requestMacKeyId", original.requestMacKeyId),
+ Map.entry("requestDigest", original.requestDigest),
+ Map.entry("tokenHash", tokenHash),
+ Map.entry("claimsDigest", AccountControlUiIssuanceRepository.hash(original.claims)),
+ Map.entry("bundleDigest", AccountControlUiIssuanceRepository.hash(original.bundle)),
+ Map.entry(
+ "signerReceiptDigest",
+ AccountControlUiIssuanceRepository.hash(original.signerReceipt)),
+ Map.entry("recoveryExpiresAt", original.recoveryExpiry.toString())));
+ }
+
+ private record PrimaryDenial(String code, String message) {
+ private PrimaryDenial {
+ Objects.requireNonNull(code);
+ Objects.requireNonNull(message);
+ }
+ }
+
+ private record InitialPreparation(Prepared prepared, PrimaryDenial denial) {
+ private InitialPreparation {
+ if ((prepared == null) == (denial == null)) {
+ throw new IllegalArgumentException(
+ "Exactly one initial creator preparation outcome required");
+ }
+ }
+ }
+
+ private record Prepared(
+ AccountControlUiIssuanceRepository.Stored stored,
+ AccountControlUiAuthority.Snapshot source,
+ AccountControlUiSignerOwner.Capture signer) {}
+
+ /**
+ * Only permanent loss established against the original owner record, never dependency failure.
+ */
+ private static final class RecoveryLost extends RuntimeException {
+ private final AccountControlUiIssuanceRepository.Stored original;
+
+ private RecoveryLost(AccountControlUiIssuanceRepository.Stored original) {
+ super("Original protected control-ui recovery permanently unavailable");
+ this.original = original;
+ }
+ }
+
+ public record Request(
+ UUID requestId, String email, String secret, UUID tenantId, UUID callerContextId) {
+ public Request {
+ if (requestId == null
+ || email == null
+ || email.isBlank()
+ || email.length() > 254
+ || secret == null
+ || secret.isEmpty()
+ || secret.length() > 1024
+ || tenantId == null
+ || callerContextId == null) {
+ throw new IllegalArgumentException("Exact bounded issuer request required");
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "AccountControlUiIssuanceService.Request[redacted]";
+ }
+ }
+
+ public static final class IssuedCredential implements AutoCloseable {
+ private final byte[] bytes;
+ private final Instant expiresAt, recoveryExpiresAt;
+
+ private IssuedCredential(byte[] bytes, Instant expiresAt, Instant recoveryExpiresAt) {
+ this.bytes = bytes.clone();
+ this.expiresAt = expiresAt;
+ this.recoveryExpiresAt = recoveryExpiresAt;
+ }
+
+ public byte[] compactBytes() {
+ return bytes.clone();
+ }
+
+ public Instant expiresAt() {
+ return expiresAt;
+ }
+
+ public Instant recoveryExpiresAt() {
+ return recoveryExpiresAt;
+ }
+
+ @Override
+ public void close() {
+ Arrays.fill(bytes, (byte) 0);
+ }
+
+ @Override
+ public String toString() {
+ return "AccountControlUiIssuanceService.IssuedCredential[redacted]";
+ }
+ }
+
+ private static IllegalStateException denied() {
+ return new IllegalStateException("Control-ui original issuance/current recovery unavailable");
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java
new file mode 100644
index 0000000000..5c8f6d5621
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiKeyring.java
@@ -0,0 +1,47 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.nio.file.Path;
+import java.time.Instant;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * Separate unpublished control-ui custody using the existing bounded mounted-ring parser.
+ * encryption/ and request-mac/ each contain an independent existing-format keyring. Neither
+ * defaults to or reads the gameplay response-envelope mount.
+ */
+public final class AccountControlUiKeyring {
+ private final AccountResponseEnvelopeKeyring encryption;
+ private final AccountResponseEnvelopeKeyring requestMac;
+
+ public AccountControlUiKeyring(Path dedicatedRoot) {
+ if (dedicatedRoot == null || !dedicatedRoot.isAbsolute()) {
+ throw new IllegalArgumentException("Separate absolute control-ui custody root required");
+ }
+ encryption = new AccountResponseEnvelopeKeyring(dedicatedRoot.resolve("encryption").toString());
+ requestMac =
+ new AccountResponseEnvelopeKeyring(dedicatedRoot.resolve("request-mac").toString());
+ }
+
+ AccountResponseEnvelopeKeyring encryption() {
+ return encryption;
+ }
+
+ String requestKeyId() {
+ return requestMac.readCurrent().activeKeyId();
+ }
+
+ SecretKey requestKey(String id, Instant now) {
+ byte[] bytes = requestMac.readCurrent().decryptionKey(id, now).secretKey().getEncoded();
+ byte[] encryptionBytes = encryption.readCurrent().activeKey().secretKey().getEncoded();
+ try {
+ if (java.util.Arrays.equals(bytes, encryptionBytes)) {
+ throw new IllegalStateException("Control-ui encryption and request-MAC keys must differ");
+ }
+ return new SecretKeySpec(bytes, "HmacSHA256");
+ } finally {
+ java.util.Arrays.fill(bytes, (byte) 0);
+ java.util.Arrays.fill(encryptionBytes, (byte) 0);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java
new file mode 100644
index 0000000000..3009ba9d21
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryContract.java
@@ -0,0 +1,45 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.util.List;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor;
+import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor.*;
+
+/** Distinct owner descriptor; runtime catalog registration and ACL provisioning remain closed. */
+public final class AccountControlUiRegistryContract {
+ public static final String SCRIPT_ID = "account-control-ui-registry-cas.v1";
+ public static final String RESOURCE = "redis/lua/account-control-ui-registry-cas.lua";
+
+ private AccountControlUiRegistryContract() {}
+
+ public static RedisScriptDescriptor descriptor() {
+ return new RedisScriptDescriptor(
+ SCRIPT_ID,
+ RESOURCE,
+ "65cb013abd1d32b4a718b5a67ea4e8b568693adc8388f3a9303713d4284d3f14",
+ "account-service",
+ "account_coord_app",
+ RedisRole.COORDINATION,
+ List.of(new KeySpec("tokenRecord", "session:auth:token:", HashTagDeclaration.NOT_REQUIRED)),
+ List.of(
+ new ArgumentSpec("expectedOriginalRecord"),
+ new ArgumentSpec("exactReplacementRecord"),
+ new ArgumentSpec("absoluteExpiryEpochMillis")),
+ ScriptCategory.SESSION_CAS,
+ List.of(
+ new OutcomeSpec("APPLIED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING),
+ new OutcomeSpec("EXACT_REASSERTED", OutcomeCategory.SUCCESS, MutationEffect.MUTATING),
+ new OutcomeSpec(
+ "INVALID_ARGUMENTS",
+ OutcomeCategory.VALIDATION_FAILURE,
+ MutationEffect.NON_MUTATING),
+ new OutcomeSpec("EXPIRED", OutcomeCategory.STALE, MutationEffect.NON_MUTATING),
+ new OutcomeSpec("EXPIRY_MISMATCH", OutcomeCategory.STALE, MutationEffect.NON_MUTATING),
+ new OutcomeSpec("CONFLICT", OutcomeCategory.STALE, MutationEffect.NON_MUTATING)),
+ ResetSensitivity.CLUSTER,
+ LossClass.SESSION_LEASE_CACHE_OR_WAKE_UP,
+ "Missing or changed control-ui record denies; only original durable Account issuance may reconcile.",
+ CompatibilityLevel.REQUIRES_CLUSTER_RESET,
+ List.of(new SupportedCoexistence("v1", "v1")),
+ null);
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java
new file mode 100644
index 0000000000..8246f90998
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReader.java
@@ -0,0 +1,212 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import io.lettuce.core.api.sync.RedisCommands;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.core.type.TypeReference;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Read-only Account Coordination view of one committed control-ui token record.
+ *
+ * This class is deliberately not a Spring bean and contains no Redis mutation path. A caller
+ * must supply Account's protected pinned connection provider; each read proves the live ACL user
+ * and exact physical cleanup deadline on that same non-reconnecting connection. Registry presence
+ * is only one input to Account's committed issuance/current-authority verification.
+ */
+public final class AccountControlUiRegistryReader {
+ public static final String TOKEN_KEY_PREFIX = "session:auth:token:";
+ public static final String REQUIRED_ACL_IDENTITY = "account_coord_app";
+ public static final int MAX_RECORD_BYTES = 32 * 1024;
+
+ private static final Pattern TOKEN_HASH = Pattern.compile("[0-9a-f]{64}");
+ private static final Pattern DIGEST = Pattern.compile("[0-9a-f]{64}");
+ private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}");
+ private static final Pattern DECIMAL = Pattern.compile("[1-9][0-9]{0,18}");
+ private static final Set FIELDS =
+ Set.of(
+ "schemaVersion",
+ "registryVersion",
+ "tokenHash",
+ "kid",
+ "signerGeneration",
+ "issuer",
+ "profile",
+ "type",
+ "audience",
+ "accountId",
+ "jti",
+ "iat",
+ "nbf",
+ "exp",
+ "tokenGeneration",
+ "authorityTuple",
+ "membershipVersion",
+ "issuanceFence",
+ "operationId",
+ "requestId",
+ "requestDigest",
+ "state",
+ "authoritySourceVersions",
+ "authEvidenceBundle",
+ "originalSignerReceiptDigest");
+ private static final JsonMapper JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+ private static final TypeReference> OBJECT = new TypeReference<>() {};
+
+ private final AccountCoordinationPinnedConnectionProvider connections;
+
+ public AccountControlUiRegistryReader(AccountCoordinationPinnedConnectionProvider connections) {
+ this.connections =
+ Objects.requireNonNull(connections, "private Account Coordination is required");
+ }
+
+ /** Reads and validates one active registry value without holding an Account SQL transaction. */
+ public byte[] readActive(String tokenHash) {
+ outsideSql();
+ if (tokenHash == null || !TOKEN_HASH.matcher(tokenHash).matches()) {
+ throw denied();
+ }
+ try (var connection = connections.openPinnedConnection()) {
+ if (connection == null
+ || !connection.isOpen()
+ || connection.getOptions() == null
+ || connection.getOptions().isAutoReconnect()) {
+ throw denied();
+ }
+ RedisCommands commands = connection.sync();
+ if (!REQUIRED_ACL_IDENTITY.equals(commands.aclWhoami())) {
+ throw denied();
+ }
+ byte[] key = (TOKEN_KEY_PREFIX + tokenHash).getBytes(StandardCharsets.US_ASCII);
+ byte[] exact = commands.get(key);
+ Map record = parseActiveRecord(exact, tokenHash);
+ long expiresAtMillis = checkedExpiryMillis(record.get("exp"));
+ Long physicalExpiry = commands.pexpiretime(key);
+ if (physicalExpiry == null || physicalExpiry.longValue() != expiresAtMillis) {
+ throw denied();
+ }
+ return exact.clone();
+ } catch (RuntimeException unavailable) {
+ throw denied();
+ }
+ }
+
+ static Map parseActiveRecord(byte[] exact, String tokenHash) {
+ if (exact == null || exact.length == 0 || exact.length > MAX_RECORD_BYTES) {
+ throw denied();
+ }
+ try {
+ String json =
+ StandardCharsets.UTF_8.newDecoder().decode(java.nio.ByteBuffer.wrap(exact)).toString();
+ if (!Arrays.equals(exact, Rfc8785CanonicalJson.canonicalizeUtf8(json))) {
+ throw denied();
+ }
+ Map fields = JSON.readValue(exact, OBJECT);
+ if (fields == null
+ || !fields.keySet().equals(FIELDS)
+ || !Integer.valueOf(1).equals(number(fields.get("schemaVersion")))
+ || !Integer.valueOf(2).equals(number(fields.get("registryVersion")))
+ || !tokenHash.equals(text(fields.get("tokenHash")))
+ || !"firemud-account-service".equals(text(fields.get("issuer")))
+ || !"control-ui".equals(text(fields.get("profile")))
+ || !"control-ui".equals(text(fields.get("type")))
+ || !"control-ui".equals(text(fields.get("audience")))
+ || !"active".equals(text(fields.get("state")))
+ || !KID.matcher(text(fields.get("kid"))).matches()
+ || !DECIMAL.matcher(text(fields.get("signerGeneration"))).matches()
+ || !DIGEST.matcher(text(fields.get("requestDigest"))).matches()
+ || !DIGEST.matcher(text(fields.get("originalSignerReceiptDigest"))).matches()
+ || !(fields.get("authorityTuple") instanceof Map, ?>)
+ || !(fields.get("membershipVersion") instanceof Map, ?>)
+ || !(fields.get("authoritySourceVersions") instanceof Map, ?>)
+ || !(fields.get("authEvidenceBundle") instanceof Map, ?>)) {
+ throw denied();
+ }
+ requireUuid(fields.get("accountId"));
+ requireUuid(fields.get("jti"));
+ requireUuid(fields.get("operationId"));
+ requireUuid(fields.get("requestId"));
+ requirePositiveNumber(fields.get("iat"));
+ requirePositiveNumber(fields.get("nbf"));
+ requirePositiveNumber(fields.get("exp"));
+ requirePositiveNumber(fields.get("tokenGeneration"));
+ requirePositiveNumber(fields.get("issuanceFence"));
+ return Map.copyOf(fields);
+ } catch (IOException | RuntimeException malformed) {
+ throw denied();
+ }
+ }
+
+ static long checkedExpiryMillis(Object encodedExpiry) {
+ try {
+ long exp = requirePositiveNumber(encodedExpiry);
+ // The committed control-ui profile uses the exact token expiry and zero cleanup margin.
+ return Math.multiplyExact(exp, 1000L);
+ } catch (ArithmeticException | IllegalArgumentException malformed) {
+ throw denied();
+ }
+ }
+
+ private static Number number(Object value) {
+ return value instanceof Number number ? number : null;
+ }
+
+ private static String text(Object value) {
+ return value instanceof String text ? text : "";
+ }
+
+ private static long requirePositiveNumber(Object value) {
+ if (!(value instanceof Number number)) {
+ throw denied();
+ }
+ String encoded = number.toString();
+ if (!DECIMAL.matcher(encoded).matches()) {
+ throw denied();
+ }
+ try {
+ return Long.parseLong(encoded);
+ } catch (NumberFormatException malformed) {
+ throw denied();
+ }
+ }
+
+ private static void requireUuid(Object value) {
+ if (!(value instanceof String text)) {
+ throw denied();
+ }
+ try {
+ UUID parsed = UUID.fromString(text);
+ if (!parsed.toString().equals(text)
+ || parsed.getMostSignificantBits() == 0L && parsed.getLeastSignificantBits() == 0L) {
+ throw denied();
+ }
+ } catch (IllegalArgumentException malformed) {
+ throw denied();
+ }
+ }
+
+ private static void outsideSql() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw new IllegalStateException("Account Coordination reads cannot retain Account SQL locks");
+ }
+ }
+
+ private static IllegalStateException denied() {
+ return new IllegalStateException(
+ "Exact Account active control-ui registry evidence unavailable");
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java
new file mode 100644
index 0000000000..a3de42db00
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiResponseCryptography.java
@@ -0,0 +1,76 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.Optional;
+import javax.crypto.Mac;
+
+/** Distinct control-ui custody and purpose over the existing tested envelope primitive. */
+public final class AccountControlUiResponseCryptography {
+ private final AccountControlUiKeyring keys;
+ private final AccountResponseEnvelopeCryptography envelopes;
+ private final Clock clock;
+
+ public AccountControlUiResponseCryptography(AccountControlUiKeyring keys, Clock clock) {
+ this.keys = Objects.requireNonNull(keys);
+ this.clock = Objects.requireNonNull(clock);
+ envelopes =
+ new AccountResponseEnvelopeCryptography(
+ keys.encryption(), clock, new java.security.SecureRandom());
+ }
+
+ String currentKeyId() {
+ return keys.requestKeyId();
+ }
+
+ String requestDigest(String keyId, byte[] exactRequest) {
+ if (exactRequest == null || exactRequest.length == 0 || exactRequest.length > 16384) {
+ throw new IllegalArgumentException("Bounded control-ui credential request required");
+ }
+ try {
+ Mac mac = Mac.getInstance("HmacSHA256");
+ mac.init(keys.requestKey(keyId, clock.instant()));
+ mac.update("firemud/control-ui/credential-request/v1\0".getBytes(StandardCharsets.US_ASCII));
+ return HexFormat.of().formatHex(mac.doFinal(exactRequest));
+ } catch (java.security.GeneralSecurityException | RuntimeException exception) {
+ throw new IllegalStateException("Control-ui request MAC unavailable");
+ }
+ }
+
+ byte[] seal(byte[] credential, byte[] binding, Instant recoveryExpiry) {
+ return envelopes.encrypt(binding(binding), credential, recoveryExpiry).bytes();
+ }
+
+ byte[] open(byte[] envelope, byte[] binding, Instant recoveryExpiry) {
+ return envelopes.decrypt(
+ new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope(envelope),
+ binding(binding),
+ recoveryExpiry);
+ }
+
+ private static AccountResponseEnvelopeCryptography.Binding binding(byte[] exactOwnerBinding) {
+ try {
+ byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(exactOwnerBinding);
+ String identity = HexFormat.of().formatHex(digest);
+ // Labels identify cryptographic purpose, not a workload or authenticated actor.
+ return new AccountResponseEnvelopeCryptography.Binding(
+ "control-ui-issuance/v1",
+ identity,
+ digest,
+ "account-control-ui-custody",
+ identity,
+ Optional.empty(),
+ Optional.empty(),
+ Optional.empty(),
+ 1,
+ "{}".getBytes(StandardCharsets.US_ASCII),
+ "{}".getBytes(StandardCharsets.US_ASCII),
+ exactOwnerBinding);
+ } catch (java.security.NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException(impossible);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java
new file mode 100644
index 0000000000..c982a8210a
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerOwner.java
@@ -0,0 +1,201 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.nio.file.Path;
+import java.util.LinkedHashMap;
+import java.util.Objects;
+import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority;
+import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence;
+
+/** Unregistered genuine committed-signer owner, separate from non-authorizing readiness probes. */
+public final class AccountControlUiSignerOwner {
+ private final AccountJwtSignerDesiredStateRepository repository;
+ private final AccountJwtSignerMaterializerTrustBinding trust;
+ private final AccountJwtJwksApiBinding api;
+ private final Path privateRoot;
+ private final Path publicRoot;
+
+ @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification =
+ "Injected signer repository is an internal Account owner transaction collaborator.")
+ public AccountControlUiSignerOwner(
+ AccountJwtSignerDesiredStateRepository repository,
+ AccountJwtSignerMaterializerTrustBinding trust,
+ AccountJwtJwksApiBinding api,
+ Path privateRoot,
+ Path publicRoot) {
+ this.repository = Objects.requireNonNull(repository);
+ this.trust = Objects.requireNonNull(trust);
+ this.api = Objects.requireNonNull(api);
+ this.privateRoot = Objects.requireNonNull(privateRoot);
+ this.publicRoot = Objects.requireNonNull(publicRoot);
+ if (!privateRoot.isAbsolute() || !publicRoot.isAbsolute()) {
+ throw new IllegalArgumentException("Protected Account signer roots required");
+ }
+ }
+
+ /** Reads existing real lifecycle receipts under their existing Account owner transaction. */
+ public Capture captureCurrent() {
+ return capture(null);
+ }
+
+ /** Original retained owner receipt, independently re-read rather than treated as caller proof. */
+ public Capture requireOriginal(byte[] originalReceipt) {
+ var observed = capture(Objects.requireNonNull(originalReceipt));
+ if (!java.util.Arrays.equals(originalReceipt, observed.receipt())) {
+ throw unavailable();
+ }
+ return observed;
+ }
+
+ private Capture capture(byte[] originalReceipt) {
+ var materializer = trust.current().orElseThrow(AccountControlUiSignerOwner::unavailable);
+ var publicApi = api.current();
+ if (!materializer.environmentId().equals(publicApi.environmentId())
+ || !materializer.clusterId().equals(publicApi.clusterId())
+ || !materializer.namespace().equals(publicApi.namespace())
+ || !materializer
+ .expectedClusterIncarnationUid()
+ .equals(publicApi.expectedClusterIncarnationUid())
+ || !materializer.expectedNamespaceUid().equals(publicApi.expectedNamespaceUid())) {
+ throw unavailable();
+ }
+ var binding =
+ new AccountJwtSignerDesiredStateRepository.Binding(
+ materializer.environmentId(),
+ materializer.clusterId(),
+ materializer.namespace(),
+ CustodyMode.INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK);
+ var fence =
+ new TrustFence(
+ materializer.expectedClusterIncarnationUid(),
+ materializer.expectedNamespaceUid(),
+ materializer.bindingDigest(),
+ materializer.configRevision());
+ AccountJwtSignerDesiredStateRepository.GenerationResult generation;
+ AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence promotion;
+ AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt privateReceipt;
+ AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt publicReceipt;
+ if (originalReceipt == null) {
+ var evidence =
+ repository
+ .readCurrentCommittedSigner(
+ binding, fence, publicApi.bindingDigest(), publicApi.configRevision())
+ .orElseThrow(AccountControlUiSignerOwner::unavailable);
+ generation = evidence.generationResult();
+ promotion = evidence.promotion();
+ privateReceipt = evidence.privateReceipt();
+ publicReceipt = evidence.publicReceipt();
+ } else {
+ var original = AccountControlUiIssuanceRepository.object(originalReceipt);
+ var evidence =
+ repository
+ .readOriginalCommittedSigner(
+ binding,
+ fence,
+ publicApi.bindingDigest(),
+ publicApi.configRevision(),
+ java.util.UUID.fromString((String) original.get("promotionOperationId")),
+ java.util.UUID.fromString((String) original.get("generationOperationId")))
+ .orElseThrow(AccountControlUiSignerOwner::unavailable);
+ generation = evidence.generationResult();
+ promotion = evidence.promotion();
+ privateReceipt = evidence.privateReceipt();
+ publicReceipt = evidence.publicReceipt();
+ }
+ if (!binding.equals(promotion.binding())
+ || !binding.equals(generation.binding())
+ || !fence.equals(promotion.trustFence())
+ || !fence.equals(generation.trustFence())
+ || !promotion.targetGeneration().equals(generation.targetGeneration())
+ || !promotion.targetKid().equals(generation.targetKid())
+ || !"RS256".equals(promotion.targetAlgorithm())
+ || !"RS256".equals(generation.targetAlgorithm())
+ || !promotion.targetPublicKeyFingerprint().equals(generation.publicKeyFingerprint())) {
+ throw unavailable();
+ }
+ var expected =
+ new AccountMountedJwtSignerBundle.ExpectedIdentity(
+ binding.environmentId(),
+ binding.clusterId(),
+ binding.namespace(),
+ generation.operationId().toString(),
+ generation.targetGeneration(),
+ generation.targetKid(),
+ generation.publicKeyFingerprint());
+ var receipt = new LinkedHashMap();
+ receipt.put("schema", "account-control-ui-committed-signer/v1");
+ receipt.put("environmentId", binding.environmentId());
+ receipt.put("clusterId", binding.clusterId());
+ receipt.put("namespace", binding.namespace());
+ receipt.put("clusterIncarnationUid", materializer.expectedClusterIncarnationUid());
+ receipt.put("namespaceUid", materializer.expectedNamespaceUid());
+ receipt.put("trustBindingDigest", materializer.bindingDigest());
+ receipt.put("trustConfigRevision", materializer.configRevision());
+ receipt.put("apiBindingDigest", publicApi.bindingDigest());
+ receipt.put("apiConfigRevision", publicApi.configRevision());
+ receipt.put("promotionOperationId", promotion.operationId().toString());
+ receipt.put("promotionRequestDigest", promotion.requestDigest());
+ receipt.put("generationOperationId", generation.operationId().toString());
+ receipt.put("signerGeneration", generation.targetGeneration());
+ receipt.put("kid", generation.targetKid());
+ receipt.put("algorithm", generation.targetAlgorithm());
+ receipt.put("publicKeyFingerprint", generation.publicKeyFingerprint());
+ receipt.put("privateReceiptDigest", privateReceipt.receiptDigest());
+ receipt.put("privateResourceVersion", privateReceipt.observedResourceVersion());
+ receipt.put("publicReceiptDigest", publicReceipt.receiptDigest());
+ receipt.put("publicResourceVersion", publicReceipt.observedResourceVersion());
+ receipt.put("publicConfigMapUid", publicReceipt.configMapUid());
+ receipt.put("publicDataDigest", publicReceipt.publicDataDigest());
+ return new Capture(expected, AccountControlUiAuthority.canonical(receipt));
+ }
+
+ String sign(
+ Capture original,
+ AccountControlUiSigningSpec spec,
+ java.util.function.BiConsumer candidateConsumer) {
+ return AccountMountedJwtSignerBundle.signCommittedControlUiDigest(
+ privateRoot,
+ Path.of("current.key"),
+ publicRoot,
+ Path.of("jwks.json"),
+ original.expected,
+ spec,
+ candidateConsumer);
+ }
+
+ public static final class Capture {
+ private final AccountMountedJwtSignerBundle.ExpectedIdentity expected;
+ private final byte[] receipt;
+
+ private Capture(AccountMountedJwtSignerBundle.ExpectedIdentity expected, byte[] receipt) {
+ this.expected = expected;
+ this.receipt = receipt.clone();
+ }
+
+ public byte[] receipt() {
+ return receipt.clone();
+ }
+
+ public String kid() {
+ return expected.kid();
+ }
+
+ public String generation() {
+ return expected.generation();
+ }
+
+ @Override
+ public String toString() {
+ return "AccountControlUiSignerOwner.Capture[redacted]";
+ }
+ }
+
+ private static IllegalStateException unavailable() {
+ return new IllegalStateException("Existing committed control-ui signer unavailable");
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java
new file mode 100644
index 0000000000..33b0c3650e
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountCoordinationPinnedConnectionProvider.java
@@ -0,0 +1,28 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import io.lettuce.core.api.StatefulRedisConnection;
+
+/** Opens one private, dedicated, non-clustered Coordination connection for one Account read. */
+@FunctionalInterface
+public interface AccountCoordinationPinnedConnectionProvider {
+ /**
+ * The provider must not return an ambient Spring connection, must disable automatic reconnect,
+ * and must retain one pinned physical Redis connection for the invocation. The caller checks the
+ * open/no-auto-reconnect contract and authenticates its ACL identity before reading data.
+ */
+ StatefulRedisConnection openPinnedConnection();
+
+ /** Bounded durability acknowledgement requirements for one owner Coordination operation. */
+ record AcknowledgementRequirements(
+ int requiredLocalAofCount, int requiredReplicaAofCount, int timeoutMillis) {
+ public AcknowledgementRequirements {
+ if (requiredLocalAofCount != 1
+ || requiredReplicaAofCount < 1
+ || requiredReplicaAofCount > 16
+ || timeoutMillis < 1
+ || timeoutMillis > 60_000) {
+ throw new IllegalArgumentException("WAITAOF requirements are outside the supported bound");
+ }
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java
new file mode 100644
index 0000000000..3f2077f190
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java
@@ -0,0 +1,704 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.nio.ByteBuffer;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.function.Supplier;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding;
+import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiCall;
+import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ApiResponse;
+import net.firedevops.firemud.accountservice.config.AccountJwtJwksApiBinding.ParsedBinding;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * The Account-only Kubernetes adapter for the pre-created public {@code jwt-jwks} ConfigMap. Every
+ * write is a fixed-name, resourceVersion-guarded merge patch followed by exact readback. This class
+ * is intentionally not a lifecycle, readiness, or signer-promotion authority.
+ */
+public final class AccountJwtJwksConfigMapClient {
+ public static final String CONFIG_MAP_NAME = "jwt-jwks";
+ public static final String JWKS_DATA_KEY = "jwks.json";
+ public static final String GENERATION_DATA_KEY = "jwt-generation.json";
+ public static final int MAX_DESIRED_VALUE_BYTES = 768 * 1024;
+ private static final int MAX_CONFIG_MAP_DATA_KEYS = 128;
+ private static final int MAX_CONFIG_MAP_DATA_BYTES = 1024 * 1024;
+ private static final Pattern RESOURCE_VERSION = Pattern.compile("[!-~]{1,256}");
+ private static final Pattern UID =
+ Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}");
+ private static final Set ACCOUNT_DATA_KEYS = Set.of(JWKS_DATA_KEY, GENERATION_DATA_KEY);
+ private static final Set PRIVATE_JWK_FIELDS =
+ Set.of("d", "p", "q", "dp", "dq", "qi", "oth", "k");
+ private static final byte[] SELF_SUBJECT_REVIEW_REQUEST =
+ "{\"apiVersion\":\"authentication.k8s.io/v1\",\"kind\":\"SelfSubjectReview\",\"spec\":{}}"
+ .getBytes(StandardCharsets.UTF_8);
+ private static final JsonMapper STRICT_JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+
+ private final Supplier operationSupplier;
+
+ /** Production constructor; API TLS and bearer handling remain inside the protected binding. */
+ public AccountJwtJwksConfigMapClient(AccountJwtJwksApiBinding binding) {
+ AccountJwtJwksApiBinding requiredBinding =
+ Objects.requireNonNull(binding, "Account JWT JWKS API binding is required");
+ this.operationSupplier =
+ () -> {
+ AccountJwtJwksApiBinding.ApiOperation operation = requiredBinding.beginOperation();
+ return new ApiSession() {
+ @Override
+ public ParsedBinding binding() {
+ return operation.binding();
+ }
+
+ @Override
+ public ApiResponse send(ApiCall call, byte[] body) {
+ return operation.send(call, body);
+ }
+
+ @Override
+ public void close() {
+ operation.close();
+ }
+ };
+ };
+ }
+
+ /** Deterministic bounded transport seam for focused tests. */
+ AccountJwtJwksConfigMapClient(Supplier operationSupplier) {
+ this.operationSupplier =
+ Objects.requireNonNull(operationSupplier, "API operation supplier is required");
+ }
+
+ /**
+ * Returns only the independently protected non-secret API/destination pins. Callers can compare
+ * these with Account's materializer binding before creating durable publication intent.
+ */
+ public BindingIdentity identity() {
+ try (ApiSession operation = beginOperation()) {
+ return toIdentity(operation.binding());
+ }
+ }
+
+ /**
+ * Reads only the fixed pre-created public ConfigMap after checking Account API identity and both
+ * namespace incarnation pins. No list, create, delete, or Secret endpoint is available.
+ */
+ public ConfigMapSnapshot observe() {
+ try (ApiSession operation = beginOperation()) {
+ verifyEnvironment(operation);
+ return readConfigMap(operation);
+ }
+ }
+
+ /**
+ * Applies an exact owner-authored public data map using Kubernetes resourceVersion CAS. Only
+ * {@code jwks.json} and {@code jwt-generation.json} are accepted; unrelated data is preserved. An
+ * ambiguous write is successful only after a fresh exact-content readback on the same UID.
+ */
+ public CasObservation publish(ConfigMapSnapshot expected, Map desiredPublicData) {
+ Objects.requireNonNull(expected, "expected ConfigMap snapshot is required");
+ Map desired = validateDesiredPublicData(desiredPublicData);
+ requireSnapshotIdentity(expected);
+
+ try (ApiSession operation = beginOperation()) {
+ return publish(operation, expected, desired);
+ }
+ }
+
+ /**
+ * Reconciles Account's exact active-marker transition from its durable prepublication RV. The
+ * freshly observed full snapshot preserves unrelated entries on a first write; an exact replay is
+ * accepted only when the live Account-owned data already matches and its RV advanced beyond the
+ * original prepublication fence.
+ */
+ public CasObservation publishActiveProjection(
+ ConfigMapSnapshot observed,
+ String expectedPriorResourceVersion,
+ Map desiredPublicData) {
+ Objects.requireNonNull(observed, "fresh ConfigMap observation is required");
+ Map desired = validateDesiredPublicData(desiredPublicData);
+ requireSnapshotIdentity(observed);
+ if (expectedPriorResourceVersion == null
+ || !RESOURCE_VERSION.matcher(expectedPriorResourceVersion).matches()) {
+ throw new IllegalArgumentException("Active ConfigMap prior resourceVersion is malformed");
+ }
+
+ try (ApiSession operation = beginOperation()) {
+ verifyEnvironment(operation);
+ ConfigMapSnapshot before = readConfigMap(operation);
+ if (!before.uid().equals(observed.uid())
+ || !before.resourceVersion().equals(observed.resourceVersion())
+ || !before.data().equals(observed.data())) {
+ throw conflict(before);
+ }
+ if (sameAccountData(before.data(), desired)) {
+ if (before.resourceVersion().equals(expectedPriorResourceVersion)) {
+ throw conflict(before);
+ }
+ return observationWithPrior(
+ expectedPriorResourceVersion, before, desired, Outcome.EXACT_REPLAY);
+ }
+ if (!before.resourceVersion().equals(expectedPriorResourceVersion)) {
+ throw conflict(before);
+ }
+
+ byte[] patch = createMergePatch(before, desired);
+ verifyEnvironment(operation);
+ ApiResponse response;
+ try {
+ response = operation.send(ApiCall.PATCH_JWKS_CONFIG_MAP, patch);
+ } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) {
+ throw new BindingRejectedException();
+ } catch (AccountJwtJwksApiBinding.ApiTransportException ex) {
+ return reconcileUnknownWrite(operation, before, before, desired);
+ }
+ if (response.statusCode() == 409) {
+ verifyEnvironment(operation);
+ throw conflict(readConfigMap(operation));
+ }
+ if (response.statusCode() == 404) {
+ throw new ResourceMissingException();
+ }
+ if (response.statusCode() >= 500 || response.statusCode() == 408) {
+ return reconcileUnknownWrite(operation, before, before, desired);
+ }
+ if (!isSuccess(response.statusCode())) {
+ throw new ApiFailureException(response.statusCode());
+ }
+ ConfigMapSnapshot readback;
+ try {
+ verifyEnvironment(operation);
+ readback = readConfigMap(operation);
+ } catch (RuntimeException ex) {
+ throw new UncertainOutcomeException();
+ }
+ requireExactPostcondition(before, before, readback, desired);
+ return observationWithPrior(expectedPriorResourceVersion, readback, desired, Outcome.APPLIED);
+ }
+ }
+
+ private CasObservation publish(
+ ApiSession operation, ConfigMapSnapshot expected, Map desired) {
+ verifyEnvironment(operation);
+ ConfigMapSnapshot before = readConfigMap(operation);
+ if (!before.uid().equals(expected.uid())) {
+ throw conflict(before);
+ }
+ if (sameAccountData(before.data(), desired)) {
+ if (before.resourceVersion().equals(expected.resourceVersion())) {
+ throw conflict(before);
+ }
+ return observation(expected, before, desired, Outcome.EXACT_REPLAY);
+ }
+ if (!before.resourceVersion().equals(expected.resourceVersion())) {
+ throw conflict(before);
+ }
+
+ byte[] patch = createMergePatch(expected, desired);
+ // Identity checks are repeated immediately before the only write call.
+ verifyEnvironment(operation);
+ ApiResponse response;
+ try {
+ response = operation.send(ApiCall.PATCH_JWKS_CONFIG_MAP, patch);
+ } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) {
+ throw new BindingRejectedException();
+ } catch (AccountJwtJwksApiBinding.ApiTransportException ex) {
+ return reconcileUnknownWrite(operation, expected, before, desired);
+ }
+ if (response.statusCode() == 409) {
+ verifyEnvironment(operation);
+ throw conflict(readConfigMap(operation));
+ }
+ if (response.statusCode() == 404) {
+ throw new ResourceMissingException();
+ }
+ if (response.statusCode() >= 500 || response.statusCode() == 408) {
+ return reconcileUnknownWrite(operation, expected, before, desired);
+ }
+ if (!isSuccess(response.statusCode())) {
+ throw new ApiFailureException(response.statusCode());
+ }
+
+ ConfigMapSnapshot readback;
+ try {
+ verifyEnvironment(operation);
+ readback = readConfigMap(operation);
+ } catch (RuntimeException ex) {
+ throw new UncertainOutcomeException();
+ }
+ requireExactPostcondition(expected, before, readback, desired);
+ return observation(expected, readback, desired, Outcome.APPLIED);
+ }
+
+ private CasObservation reconcileUnknownWrite(
+ ApiSession operation,
+ ConfigMapSnapshot expected,
+ ConfigMapSnapshot before,
+ Map desired) {
+ try {
+ verifyEnvironment(operation);
+ ConfigMapSnapshot observed = readConfigMap(operation);
+ if (observed.uid().equals(expected.uid()) && sameAccountData(observed.data(), desired)) {
+ requirePreservedUnrelatedData(before, observed);
+ if (observed.resourceVersion().equals(expected.resourceVersion())) {
+ throw new UncertainOutcomeException();
+ }
+ return observation(expected, observed, desired, Outcome.EXACT_REPLAY);
+ }
+ } catch (UncertainOutcomeException ex) {
+ throw ex;
+ } catch (RuntimeException ex) {
+ // The write outcome remains unknown when reconciliation itself is unavailable.
+ }
+ throw new UncertainOutcomeException();
+ }
+
+ private void requireExactPostcondition(
+ ConfigMapSnapshot expected,
+ ConfigMapSnapshot before,
+ ConfigMapSnapshot readback,
+ Map desired) {
+ if (!readback.uid().equals(expected.uid())
+ || readback.resourceVersion().equals(expected.resourceVersion())
+ || !sameAccountData(readback.data(), desired)) {
+ throw new UncertainOutcomeException();
+ }
+ requirePreservedUnrelatedData(before, readback);
+ }
+
+ private static void requirePreservedUnrelatedData(
+ ConfigMapSnapshot before, ConfigMapSnapshot after) {
+ Map previous = unrelatedData(before.data());
+ Map current = unrelatedData(after.data());
+ if (!previous.equals(current)) {
+ throw new UncertainOutcomeException();
+ }
+ }
+
+ private static Map unrelatedData(Map data) {
+ Map unrelated = new LinkedHashMap<>();
+ data.forEach(
+ (key, value) -> {
+ if (!ACCOUNT_DATA_KEYS.contains(key)) {
+ unrelated.put(key, value);
+ }
+ });
+ return Map.copyOf(unrelated);
+ }
+
+ private ConfigMapSnapshot readConfigMap(ApiSession operation) {
+ ApiResponse response = send(operation, ApiCall.READ_JWKS_CONFIG_MAP, null);
+ if (response.statusCode() == 404) {
+ throw new ResourceMissingException();
+ }
+ if (!isSuccess(response.statusCode())) {
+ throw new ApiFailureException(response.statusCode());
+ }
+ return parseConfigMap(response.body(), operation.binding());
+ }
+
+ private void verifyEnvironment(ApiSession operation) {
+ ParsedBinding binding = operation.binding();
+ ApiResponse selfReview =
+ send(operation, ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, SELF_SUBJECT_REVIEW_REQUEST);
+ if ((selfReview.statusCode() != 200 && selfReview.statusCode() != 201)
+ || !binding.expectedApiUsername().equals(parseAuthenticatedUsername(selfReview.body()))) {
+ throw new BindingRejectedException();
+ }
+ verifyNamespace(
+ send(operation, ApiCall.READ_KUBE_SYSTEM_NAMESPACE, null),
+ "kube-system",
+ binding.expectedClusterIncarnationUid());
+ verifyNamespace(
+ send(operation, ApiCall.READ_TARGET_NAMESPACE, null),
+ binding.namespace(),
+ binding.expectedNamespaceUid());
+ }
+
+ private void verifyNamespace(ApiResponse response, String name, String expectedUid) {
+ if (!isSuccess(response.statusCode())) {
+ if (response.statusCode() == 404) {
+ throw new BindingRejectedException();
+ }
+ throw new ApiFailureException(response.statusCode());
+ }
+ JsonNode root = parseJson(response.body());
+ JsonNode metadata = root.get("metadata");
+ JsonNode status = root.get("status");
+ if (!"v1".equals(text(root.get("apiVersion")))
+ || !"Namespace".equals(text(root.get("kind")))
+ || metadata == null
+ || !name.equals(text(metadata.get("name")))
+ || !expectedUid.equals(canonicalUid(text(metadata.get("uid"))))
+ || metadata.hasNonNull("deletionTimestamp")
+ || status == null
+ || !"Active".equals(text(status.get("phase")))) {
+ throw new BindingRejectedException();
+ }
+ }
+
+ private static String parseAuthenticatedUsername(byte[] bytes) {
+ JsonNode root = parseJson(bytes);
+ JsonNode status = root.get("status");
+ JsonNode userInfo = status == null ? null : status.get("userInfo");
+ String username = userInfo == null ? null : text(userInfo.get("username"));
+ JsonNode evaluationError = status == null ? null : status.get("evaluationError");
+ if (!"authentication.k8s.io/v1".equals(text(root.get("apiVersion")))
+ || !"SelfSubjectReview".equals(text(root.get("kind")))
+ || username == null
+ || (evaluationError != null
+ && !evaluationError.isNull()
+ && (!evaluationError.isTextual() || !evaluationError.asText().isEmpty()))) {
+ throw new BindingRejectedException();
+ }
+ return username;
+ }
+
+ private static ConfigMapSnapshot parseConfigMap(byte[] bytes, ParsedBinding binding) {
+ JsonNode root = parseJson(bytes);
+ JsonNode metadata = root.get("metadata");
+ if (!"v1".equals(text(root.get("apiVersion")))
+ || !"ConfigMap".equals(text(root.get("kind")))
+ || metadata == null
+ || !CONFIG_MAP_NAME.equals(text(metadata.get("name")))
+ || !binding.namespace().equals(text(metadata.get("namespace")))
+ || metadata.hasNonNull("deletionTimestamp")
+ || Boolean.TRUE.equals(booleanValue(root.get("immutable")))
+ || (root.has("binaryData") && !root.get("binaryData").isNull())) {
+ throw new ApiFailureException(0);
+ }
+ String uid = canonicalUid(text(metadata.get("uid")));
+ String resourceVersion = text(metadata.get("resourceVersion"));
+ if (resourceVersion == null || !RESOURCE_VERSION.matcher(resourceVersion).matches()) {
+ throw new ApiFailureException(0);
+ }
+ Map data = parseData(root.get("data"));
+ return new ConfigMapSnapshot(uid, resourceVersion, data);
+ }
+
+ private static Map parseData(JsonNode dataNode) {
+ if (dataNode == null || dataNode.isNull()) {
+ return Map.of();
+ }
+ if (!dataNode.isObject() || dataNode.size() > MAX_CONFIG_MAP_DATA_KEYS) {
+ throw new ApiFailureException(0);
+ }
+ Map data = new LinkedHashMap<>();
+ int totalBytes = 0;
+ for (Map.Entry entry : dataNode.properties()) {
+ JsonNode value = entry.getValue();
+ if (!value.isTextual()) {
+ throw new ApiFailureException(0);
+ }
+ String text = value.asText();
+ totalBytes += text.getBytes(StandardCharsets.UTF_8).length;
+ if (totalBytes > MAX_CONFIG_MAP_DATA_BYTES) {
+ throw new ApiFailureException(0);
+ }
+ data.put(entry.getKey(), text);
+ }
+ return Map.copyOf(data);
+ }
+
+ private ApiSession beginOperation() {
+ try {
+ return Objects.requireNonNull(operationSupplier.get(), "API operation is unavailable");
+ } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) {
+ throw new BindingRejectedException();
+ } catch (RuntimeException ex) {
+ throw new BindingRejectedException();
+ }
+ }
+
+ private ApiResponse send(ApiSession operation, ApiCall call, byte[] body) {
+ try {
+ return operation.send(call, body);
+ } catch (AccountJwtJwksApiBinding.BindingRejectedException ex) {
+ throw new BindingRejectedException();
+ } catch (AccountJwtJwksApiBinding.ApiTransportException ex) {
+ throw new ApiFailureException(0);
+ }
+ }
+
+ private static BindingIdentity toIdentity(ParsedBinding binding) {
+ return new BindingIdentity(
+ binding.bindingDigest(),
+ binding.configRevision(),
+ binding.environmentId(),
+ binding.clusterId(),
+ binding.namespace(),
+ binding.expectedClusterIncarnationUid(),
+ binding.expectedNamespaceUid(),
+ binding.apiServer().toString(),
+ binding.tlsServerName(),
+ binding.servingCaSha256(),
+ binding.expectedApiUsername());
+ }
+
+ private static Map validateDesiredPublicData(Map desired) {
+ if (desired == null || !desired.keySet().equals(ACCOUNT_DATA_KEYS)) {
+ throw new IllegalArgumentException("Account public JWKS data keys are invalid");
+ }
+ Map copy = new LinkedHashMap<>();
+ int total = 0;
+ for (String key : ACCOUNT_DATA_KEYS) {
+ String value = desired.get(key);
+ if (value == null || value.isBlank()) {
+ throw new IllegalArgumentException("Account public JWKS data is incomplete");
+ }
+ int length = value.getBytes(StandardCharsets.UTF_8).length;
+ if (length > MAX_DESIRED_VALUE_BYTES) {
+ throw new IllegalArgumentException("Account public JWKS data exceeds its bound");
+ }
+ total += length;
+ copy.put(key, value);
+ }
+ if (total > MAX_CONFIG_MAP_DATA_BYTES) {
+ throw new IllegalArgumentException("Account public JWKS data exceeds its bound");
+ }
+ validatePublicJwks(copy.get(JWKS_DATA_KEY));
+ return Map.copyOf(copy);
+ }
+
+ private static void validatePublicJwks(String jwks) {
+ JsonNode root = parseJson(jwks.getBytes(StandardCharsets.UTF_8));
+ JsonNode keys = root.get("keys");
+ if (!root.isObject() || root.size() != 1 || keys == null || !keys.isArray() || keys.isEmpty()) {
+ throw new IllegalArgumentException("Account public JWKS is malformed");
+ }
+ for (JsonNode key : keys) {
+ if (!key.isObject()) {
+ throw new IllegalArgumentException("Account public JWKS is malformed");
+ }
+ for (String privateField : PRIVATE_JWK_FIELDS) {
+ if (key.has(privateField)) {
+ throw new IllegalArgumentException("Account public JWKS contains private material");
+ }
+ }
+ }
+ }
+
+ private static byte[] createMergePatch(ConfigMapSnapshot expected, Map desired) {
+ Map metadata = new LinkedHashMap<>();
+ metadata.put("uid", expected.uid());
+ metadata.put("resourceVersion", expected.resourceVersion());
+ Map patch = new LinkedHashMap<>();
+ patch.put("metadata", metadata);
+ patch.put("data", desired);
+ try {
+ return STRICT_JSON.writeValueAsBytes(patch);
+ } catch (Exception ex) {
+ throw new IllegalStateException("Account public JWKS patch could not be encoded");
+ }
+ }
+
+ private static boolean sameAccountData(Map current, Map desired) {
+ return desired.get(JWKS_DATA_KEY).equals(current.get(JWKS_DATA_KEY))
+ && desired.get(GENERATION_DATA_KEY).equals(current.get(GENERATION_DATA_KEY));
+ }
+
+ private static CasObservation observation(
+ ConfigMapSnapshot expected,
+ ConfigMapSnapshot observed,
+ Map desired,
+ Outcome outcome) {
+ Map exactOutput = new LinkedHashMap<>();
+ exactOutput.put(JWKS_DATA_KEY, desired.get(JWKS_DATA_KEY));
+ exactOutput.put(GENERATION_DATA_KEY, desired.get(GENERATION_DATA_KEY));
+ return new CasObservation(
+ observed.uid(),
+ expected.resourceVersion(),
+ observed.resourceVersion(),
+ exactOutput,
+ observed.data(),
+ outcome);
+ }
+
+ private static CasObservation observationWithPrior(
+ String priorResourceVersion,
+ ConfigMapSnapshot observed,
+ Map desired,
+ Outcome outcome) {
+ Map exactOutput = new LinkedHashMap<>();
+ exactOutput.put(JWKS_DATA_KEY, desired.get(JWKS_DATA_KEY));
+ exactOutput.put(GENERATION_DATA_KEY, desired.get(GENERATION_DATA_KEY));
+ return new CasObservation(
+ observed.uid(),
+ priorResourceVersion,
+ observed.resourceVersion(),
+ exactOutput,
+ observed.data(),
+ outcome);
+ }
+
+ private static CasConflictException conflict(ConfigMapSnapshot observed) {
+ return new CasConflictException(observed.uid(), observed.resourceVersion());
+ }
+
+ private static void requireSnapshotIdentity(ConfigMapSnapshot snapshot) {
+ if (!validUid(snapshot.uid())
+ || snapshot.resourceVersion() == null
+ || !RESOURCE_VERSION.matcher(snapshot.resourceVersion()).matches()) {
+ throw new IllegalArgumentException("Expected ConfigMap snapshot identity is malformed");
+ }
+ }
+
+ private static boolean isSuccess(int statusCode) {
+ return statusCode >= 200 && statusCode < 300;
+ }
+
+ private static JsonNode parseJson(byte[] bytes) {
+ if (bytes == null || bytes.length == 0 || bytes.length > MAX_CONFIG_MAP_DATA_BYTES) {
+ throw new ApiFailureException(0);
+ }
+ try {
+ String text =
+ StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ JsonNode root = STRICT_JSON.readTree(text);
+ if (root == null || !root.isObject()) {
+ throw new ApiFailureException(0);
+ }
+ return root;
+ } catch (CharacterCodingException | RuntimeException ex) {
+ throw new ApiFailureException(0);
+ }
+ }
+
+ private static String text(JsonNode node) {
+ return node != null && node.isTextual() && !node.asText().isEmpty() ? node.asText() : null;
+ }
+
+ @SuppressFBWarnings(
+ value = "NP_BOOLEAN_RETURN_NULL",
+ justification =
+ "The parser intentionally preserves absent or malformed booleans as unknown; callers require explicit true.")
+ private static Boolean booleanValue(JsonNode node) {
+ return node != null && node.isBoolean() ? node.booleanValue() : null;
+ }
+
+ private static String canonicalUid(String value) {
+ if (!validUid(value)) {
+ throw new ApiFailureException(0);
+ }
+ return value;
+ }
+
+ private static boolean validUid(String value) {
+ return value != null
+ && UID.matcher(value).matches()
+ && !"00000000-0000-0000-0000-000000000000".equals(value);
+ }
+
+ interface ApiSession extends AutoCloseable {
+ ParsedBinding binding();
+
+ ApiResponse send(ApiCall call, byte[] body);
+
+ @Override
+ void close();
+ }
+
+ public record BindingIdentity(
+ String bindingDigest,
+ String configRevision,
+ String environmentId,
+ String clusterId,
+ String namespace,
+ String expectedClusterIncarnationUid,
+ String expectedNamespaceUid,
+ String apiServerUrl,
+ String tlsServerName,
+ String servingCaSha256,
+ String expectedApiUsername) {}
+
+ public record ConfigMapSnapshot(String uid, String resourceVersion, Map data) {
+ public ConfigMapSnapshot {
+ data = data == null ? Map.of() : Map.copyOf(data);
+ }
+ }
+
+ public record CasObservation(
+ String uid,
+ String priorResourceVersion,
+ String resourceVersion,
+ Map publishedData,
+ Map readbackData,
+ Outcome outcome) {
+ public CasObservation {
+ publishedData = Map.copyOf(publishedData);
+ readbackData = Map.copyOf(readbackData);
+ }
+ }
+
+ public enum Outcome {
+ APPLIED,
+ EXACT_REPLAY
+ }
+
+ public static class ResourceMissingException extends RuntimeException {
+ public ResourceMissingException() {
+ super("Pre-created Account public JWKS ConfigMap is unavailable");
+ }
+ }
+
+ public static class CasConflictException extends RuntimeException {
+ private final String observedUid;
+ private final String observedResourceVersion;
+
+ public CasConflictException(String observedUid, String observedResourceVersion) {
+ super("Account public JWKS ConfigMap compare-and-set conflict");
+ this.observedUid = observedUid;
+ this.observedResourceVersion = observedResourceVersion;
+ }
+
+ public String observedUid() {
+ return observedUid;
+ }
+
+ public String observedResourceVersion() {
+ return observedResourceVersion;
+ }
+ }
+
+ public static class UncertainOutcomeException extends RuntimeException {
+ public UncertainOutcomeException() {
+ super("Account public JWKS ConfigMap write outcome is uncertain");
+ }
+ }
+
+ public static class ApiFailureException extends RuntimeException {
+ private final int statusCode;
+
+ public ApiFailureException(int statusCode) {
+ super("Account public JWKS Kubernetes API request failed");
+ this.statusCode = statusCode;
+ }
+
+ public int statusCode() {
+ return statusCode;
+ }
+ }
+
+ public static class BindingRejectedException extends RuntimeException {
+ public BindingRejectedException() {
+ super("Account public JWKS API binding or identity was rejected");
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java
new file mode 100644
index 0000000000..17de38c401
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java
@@ -0,0 +1,935 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.IOException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.nio.channels.SeekableByteChannel;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.security.KeyFactory;
+import java.security.spec.RSAPublicKeySpec;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding;
+import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.MountObservation;
+import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent;
+import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.support.TransactionTemplate;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Account-owned producer for the public JWKS prepublication phase and local mounted correspondence
+ * observation.
+ *
+ * It accepts no caller-selected operation, key identity, ConfigMap name, or public bytes. The
+ * only source key is the exact current Account generation receipt. Remote CAS is outside SQL
+ * transactions and is preceded by a durable immutable intent. Neither publication nor local
+ * correspondence establishes PREPARED, COMMITTED, issuance, cache convergence, probes, or
+ * readiness.
+ */
+public final class AccountJwtJwksPrepublicationService {
+ public static final int MAX_MOUNTED_MARKER_BYTES = 16 * 1024;
+ private static final String PRIVATE_MOUNT = "/var/run/secrets/firemud/jwt";
+ private static final String PRIVATE_PENDING_BUNDLE = "pending.key";
+ private static final String PRIVATE_ACTIVE_BUNDLE = "current.key";
+ private static final String PUBLIC_MOUNT = "/var/run/secrets/firemud/jwks";
+ private static final String PUBLIC_JWKS = "jwks.json";
+ private static final String PUBLIC_MARKER = "jwt-generation.json";
+ private static final int MAX_KEYS = 64;
+ private static final int MIN_RSA_BITS = 3_072;
+ private static final int MAX_RSA_BITS = 16_384;
+ private static final Set JWKS_ROOT_FIELDS = Set.of("keys");
+ private static final Set JWK_FIELDS =
+ Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e");
+ private static final Pattern KID = Pattern.compile("[A-Za-z0-9_-]{1,64}");
+ private static final JsonMapper STRICT_JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+
+ private final AccountJwtSignerDesiredStateRepository desiredStateRepository;
+ private final AccountJwtJwksPublicationRepository publicationRepository;
+ private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding;
+ private final AccountJwtJwksConfigMapClient configMapClient;
+ private final TransactionTemplate accountTransaction;
+ private final MountedProjection mountedProjection;
+
+ /** Production instance uses only the fixed Account signer/JWKS mount paths. */
+ @SuppressFBWarnings(
+ value = "DMI_HARDCODED_ABSOLUTE_FILENAME",
+ justification =
+ "The production constructor intentionally fixes Account's protected private-signer and read-only public-JWKS mount roots.")
+ public AccountJwtJwksPrepublicationService(
+ AccountJwtSignerDesiredStateRepository desiredStateRepository,
+ AccountJwtJwksPublicationRepository publicationRepository,
+ AccountJwtSignerMaterializerTrustBinding materializerTrustBinding,
+ AccountJwtJwksConfigMapClient configMapClient,
+ PlatformTransactionManager transactionManager) {
+ this(
+ desiredStateRepository,
+ publicationRepository,
+ materializerTrustBinding,
+ configMapClient,
+ transactionManager,
+ new MountedProjection(
+ Path.of(PRIVATE_MOUNT),
+ Path.of(PRIVATE_PENDING_BUNDLE),
+ Path.of(PUBLIC_MOUNT),
+ Path.of(PUBLIC_JWKS),
+ Path.of(PUBLIC_MARKER)));
+ }
+
+ AccountJwtJwksPrepublicationService(
+ AccountJwtSignerDesiredStateRepository desiredStateRepository,
+ AccountJwtJwksPublicationRepository publicationRepository,
+ AccountJwtSignerMaterializerTrustBinding materializerTrustBinding,
+ AccountJwtJwksConfigMapClient configMapClient,
+ PlatformTransactionManager transactionManager,
+ MountedProjection mountedProjection) {
+ this.desiredStateRepository =
+ Objects.requireNonNull(desiredStateRepository, "Desired-state repository is required");
+ this.publicationRepository =
+ Objects.requireNonNull(publicationRepository, "JWKS publication repository is required");
+ this.materializerTrustBinding =
+ Objects.requireNonNull(
+ materializerTrustBinding, "Protected materializer trust is required");
+ this.configMapClient =
+ Objects.requireNonNull(configMapClient, "Protected ConfigMap client is required");
+ this.accountTransaction = new TransactionTemplate(transactionManager);
+ this.accountTransaction.setReadOnly(false);
+ this.mountedProjection = Objects.requireNonNull(mountedProjection);
+ }
+
+ /**
+ * Publishes exactly Account's current pending public JWK alongside all retained public keys.
+ * Exact retries reconcile a previously persisted intent; changed/stale ConfigMap data fail before
+ * another write.
+ */
+ public PublicationReceipt prepublishCurrentGeneration() {
+ Binding binding = requireCurrentMaterializerBinding();
+ BindingIdentity apiIdentity = requireMatchingApiIdentity(binding, configMapClient.identity());
+ CurrentGeneration current = loadCurrentGeneration(binding, apiIdentity);
+ if (current.publication().isPresent()) {
+ PublicationEvidence evidence = current.publication().orElseThrow();
+ PrepublicationIntent intent = evidence.intent();
+ requireIntentApiIdentity(intent, apiIdentity);
+ ConfigMapSnapshot snapshot = configMapClient.observe();
+ if (evidence.receipt().isPresent()) {
+ requirePublishedProjection(intent, snapshot);
+ requireUnchangedBindings(binding, apiIdentity);
+ return evidence.receipt().orElseThrow();
+ }
+ requireRetrySnapshot(intent, snapshot);
+ return publishAndRecord(binding, apiIdentity, intent, snapshot);
+ }
+
+ ConfigMapSnapshot snapshot = configMapClient.observe();
+ String sourceJwks = snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY);
+ if (sourceJwks == null || sourceJwks.isBlank()) {
+ throw new PublicationRejectedException(
+ "Pre-created Account public JWKS ConfigMap has no bounded jwks.json value");
+ }
+ String desiredJwks = appendPendingPublicKey(sourceJwks, current.result());
+ String marker = generationMarker(current.result(), current.request(), apiIdentity);
+ PrepublicationIntent intent =
+ accountTransaction.execute(
+ status -> {
+ PrepublicationIntent persisted =
+ publicationRepository.recordPrepublicationIntent(
+ binding.accountBinding(),
+ trustFence(binding),
+ current.result(),
+ current.request(),
+ apiIdentity.bindingDigest(),
+ apiIdentity.configRevision(),
+ snapshot.uid(),
+ snapshot.resourceVersion(),
+ AccountJwtJwksPublicationRepository.snapshotDigest(snapshot.data()),
+ desiredJwks,
+ marker);
+ requireUnchangedBindings(binding, apiIdentity);
+ return persisted;
+ });
+ if (intent == null) {
+ throw new PublicationRejectedException("Account JWT JWKS intent was not persisted");
+ }
+ requireIntentApiIdentity(intent, apiIdentity);
+ requireRetrySnapshot(intent, snapshot);
+ return publishAndRecord(binding, apiIdentity, intent, snapshot);
+ }
+
+ /**
+ * Observes exact mounted {@code pending.key}, {@code jwks.json}, and publication marker files.
+ * The operation must already have an exact persisted Account API readback receipt.
+ */
+ public MountObservation observeCurrentMountedCorrespondence() {
+ Binding binding = requireCurrentMaterializerBinding();
+ BindingIdentity apiIdentity = requireMatchingApiIdentity(binding, configMapClient.identity());
+ CurrentGeneration current = loadCurrentGeneration(binding, apiIdentity);
+ PublicationEvidence evidence =
+ current
+ .publication()
+ .orElseThrow(
+ () ->
+ new PublicationRejectedException(
+ "Account JWT JWKS publication evidence is not available"));
+ PrepublicationIntent intent = evidence.intent();
+ evidence
+ .receipt()
+ .orElseThrow(
+ () ->
+ new PublicationRejectedException("Account JWT JWKS API readback is not available"));
+ requireIntentApiIdentity(intent, apiIdentity);
+
+ byte[] markerBytes =
+ readMountedFile(
+ mountedProjection.publicMountRoot(),
+ mountedProjection.markerPath(),
+ MAX_MOUNTED_MARKER_BYTES);
+ byte[] jwksBytes =
+ readMountedFile(
+ mountedProjection.publicMountRoot(),
+ mountedProjection.jwksPath(),
+ AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES);
+ String marker = strictUtf8(markerBytes);
+ String mountedJwks = strictUtf8(jwksBytes);
+ if (!intent.generationMarkerJson().equals(marker)
+ || !intent.jwksJson().equals(mountedJwks)
+ || !intent
+ .publicDataDigest()
+ .equals(AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, marker))) {
+ throw new PublicationRejectedException(
+ "Mounted Account public JWT projection does not match Account's exact publication");
+ }
+
+ AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity =
+ new AccountMountedJwtSignerBundle.ExpectedIdentity(
+ binding.environmentId(),
+ binding.clusterId(),
+ binding.namespace(),
+ current.result().operationId().toString(),
+ current.result().targetGeneration(),
+ current.result().targetKid(),
+ current.result().publicKeyFingerprint());
+ AccountMountedJwtSignerBundle.LocalObservation localObservation =
+ AccountMountedJwtSignerBundle.observeMounted(
+ mountedProjection.privateMountRoot(),
+ mountedProjection.pendingBundlePath(),
+ mountedProjection.publicMountRoot(),
+ mountedProjection.jwksPath(),
+ expectedIdentity);
+
+ byte[] markerAfter =
+ readMountedFile(
+ mountedProjection.publicMountRoot(),
+ mountedProjection.markerPath(),
+ MAX_MOUNTED_MARKER_BYTES);
+ byte[] jwksAfter =
+ readMountedFile(
+ mountedProjection.publicMountRoot(),
+ mountedProjection.jwksPath(),
+ AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES);
+ if (!Arrays.equals(markerBytes, markerAfter) || !Arrays.equals(jwksBytes, jwksAfter)) {
+ throw new PublicationRejectedException(
+ "Mounted Account public JWT projection changed during correspondence observation");
+ }
+ MountObservation observation =
+ accountTransaction.execute(
+ status -> {
+ MountObservation persisted =
+ publicationRepository.recordMountedCorrespondence(
+ binding.accountBinding(),
+ trustFence(binding),
+ current.result().operationId(),
+ sha256(markerBytes),
+ AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, marker),
+ localObservation.publicKeyFingerprint());
+ requireUnchangedBindings(binding, apiIdentity);
+ return persisted;
+ });
+ if (observation == null) {
+ throw new PublicationRejectedException(
+ "Mounted Account JWT correspondence was not persisted");
+ }
+ Arrays.fill(markerBytes, (byte) 0);
+ Arrays.fill(jwksBytes, (byte) 0);
+ Arrays.fill(markerAfter, (byte) 0);
+ Arrays.fill(jwksAfter, (byte) 0);
+ return observation;
+ }
+
+ /**
+ * Observes the exact Account PREPARED operation's current private key and public projection
+ * without mutating either resource. The protected fixed Secret may already have been promoted
+ * while the public ConfigMap remains PREPUBLISHED; after an ambiguous Account-owned CAS, the
+ * exact ACTIVE projection is also accepted for forward reconciliation.
+ */
+ public ConfigMapSnapshot observePreparedCurrentKeyCorrespondence(
+ PromotionOperationEvidence promotion) {
+ Objects.requireNonNull(promotion, "Account PREPARED promotion is required");
+ Binding binding = requireCurrentMaterializerBinding();
+ BindingIdentity apiIdentity = requireMatchingApiIdentity(binding, configMapClient.identity());
+ TrustFence trust = trustFence(binding);
+ if (!promotion.binding().equals(binding.accountBinding())
+ || !promotion.trustFence().equals(trust)
+ || !promotion.apiBindingDigest().equals(apiIdentity.bindingDigest())
+ || !promotion.apiConfigRevision().equals(apiIdentity.configRevision())
+ || !"PREPARED".equals(promotion.status())
+ || !promotion.privatePromotionDispatched()
+ || promotion.privatePromotionReceiptDigest().isEmpty()
+ || !promotion.expectedPreviousActive().equals(promotion.expectedPublishedActive())) {
+ throw new PublicationRejectedException(
+ "Prepared Account JWT operation no longer matches protected bindings");
+ }
+
+ var publication =
+ accountTransaction.execute(
+ status ->
+ publicationRepository.readPreparedPublicationForRecovery(
+ binding.accountBinding(), trust));
+ if (publication == null
+ || !publication.intent().operationId().equals(promotion.generationOperationId())
+ || !publication.intent().intentDigest().equals(promotion.prepublicationIntentDigest())
+ || !publication.receipt().receiptDigest().equals(promotion.prepublicationReceiptDigest())
+ || !publication.intent().configMapUid().equals(promotion.publicConfigMapUid())
+ || !publication
+ .receipt()
+ .observedResourceVersion()
+ .equals(promotion.expectedPublicResourceVersion())
+ || !publication.intent().jwksJson().equals(promotion.expectedPublicJwksJson())) {
+ throw new PublicationRejectedException(
+ "Prepared Account JWT operation has no exact public publication evidence");
+ }
+
+ ConfigMapSnapshot snapshot = configMapClient.observe();
+ String mountedJwks = snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY);
+ String apiMarker =
+ snapshot.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY);
+ boolean prepublished = publication.intent().generationMarkerJson().equals(apiMarker);
+ boolean active = promotion.expectedActiveMarkerJson().equals(apiMarker);
+ if (!promotion.publicConfigMapUid().equals(snapshot.uid())
+ || !promotion.expectedPublicJwksJson().equals(mountedJwks)
+ || (!prepublished && !active)
+ || (prepublished
+ && !promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion()))
+ || (active
+ && promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion()))) {
+ throw new PublicationRejectedException(
+ "Live Account public JWT projection is not the exact PREPARED or ACTIVE value");
+ }
+ if (promotion.activeJwksReceiptDigest().isPresent()) {
+ if (!active
+ || !promotion
+ .activeJwksObservedResourceVersion()
+ .filter(snapshot.resourceVersion()::equals)
+ .isPresent()
+ || !promotion
+ .activeJwksPublicDataDigest()
+ .filter(
+ AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, apiMarker)
+ ::equals)
+ .isPresent()) {
+ throw new PublicationRejectedException(
+ "Live Account ACTIVE JWT projection differs from its durable receipt");
+ }
+ }
+
+ byte[] markerBefore =
+ readMountedFile(
+ mountedProjection.publicMountRoot(),
+ mountedProjection.markerPath(),
+ MAX_MOUNTED_MARKER_BYTES);
+ byte[] jwksBefore =
+ readMountedFile(
+ mountedProjection.publicMountRoot(),
+ mountedProjection.jwksPath(),
+ AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES);
+ byte[] markerAfter = null;
+ byte[] jwksAfter = null;
+ try {
+ if (!apiMarker.equals(strictUtf8(markerBefore))
+ || !mountedJwks.equals(strictUtf8(jwksBefore))) {
+ throw new PublicationRejectedException(
+ "Mounted Account public JWT projection has not caught up to its exact API value");
+ }
+ AccountMountedJwtSignerBundle.ExpectedIdentity expectedIdentity =
+ new AccountMountedJwtSignerBundle.ExpectedIdentity(
+ binding.environmentId(),
+ binding.clusterId(),
+ binding.namespace(),
+ promotion.generationOperationId().toString(),
+ promotion.targetGeneration(),
+ promotion.targetKid(),
+ promotion.targetPublicKeyFingerprint());
+ AccountMountedJwtSignerBundle.LocalObservation local =
+ AccountMountedJwtSignerBundle.observeMounted(
+ mountedProjection.privateMountRoot(),
+ Path.of(PRIVATE_ACTIVE_BUNDLE),
+ mountedProjection.publicMountRoot(),
+ mountedProjection.jwksPath(),
+ expectedIdentity);
+ if (!local.expectedIdentity().equals(expectedIdentity)) {
+ throw new PublicationRejectedException(
+ "Mounted Account current JWT key does not match the PREPARED operation");
+ }
+ markerAfter =
+ readMountedFile(
+ mountedProjection.publicMountRoot(),
+ mountedProjection.markerPath(),
+ MAX_MOUNTED_MARKER_BYTES);
+ jwksAfter =
+ readMountedFile(
+ mountedProjection.publicMountRoot(),
+ mountedProjection.jwksPath(),
+ AccountMountedJwtSignerBundle.MAX_PUBLIC_JWKS_BYTES);
+ if (!Arrays.equals(markerBefore, markerAfter) || !Arrays.equals(jwksBefore, jwksAfter)) {
+ throw new PublicationRejectedException(
+ "Mounted Account public JWT projection changed during current-key correspondence");
+ }
+ requireUnchangedBindings(binding, apiIdentity);
+ return snapshot;
+ } finally {
+ Arrays.fill(markerBefore, (byte) 0);
+ Arrays.fill(jwksBefore, (byte) 0);
+ if (markerAfter != null) {
+ Arrays.fill(markerAfter, (byte) 0);
+ }
+ if (jwksAfter != null) {
+ Arrays.fill(jwksAfter, (byte) 0);
+ }
+ }
+ }
+
+ private PublicationReceipt publishAndRecord(
+ Binding binding,
+ BindingIdentity apiIdentity,
+ PrepublicationIntent intent,
+ ConfigMapSnapshot expectedSnapshot) {
+ requireUnchangedBindings(binding, apiIdentity);
+ Map desiredData = desiredData(intent);
+ ConfigMapSnapshot intentCasSnapshot =
+ new ConfigMapSnapshot(
+ intent.configMapUid(), intent.expectedResourceVersion(), expectedSnapshot.data());
+ CasObservation observation = configMapClient.publish(intentCasSnapshot, desiredData);
+ if (!intent.configMapUid().equals(observation.uid())
+ || !intent.expectedResourceVersion().equals(observation.priorResourceVersion())
+ || !observation.publishedData().equals(desiredData)
+ || !desiredData.entrySet().stream()
+ .allMatch(
+ entry -> entry.getValue().equals(observation.readbackData().get(entry.getKey())))
+ || intent.expectedResourceVersion().equals(observation.resourceVersion())) {
+ throw new PublicationRejectedException(
+ "Protected Account public JWKS client returned a non-exact readback");
+ }
+ requireUnchangedBindings(binding, apiIdentity);
+ PublicationReceipt persisted =
+ accountTransaction.execute(
+ status -> {
+ PublicationReceipt receipt =
+ publicationRepository.recordPublicationReceipt(
+ binding.accountBinding(),
+ trustFence(binding),
+ intent.operationId(),
+ apiIdentity.bindingDigest(),
+ apiIdentity.configRevision(),
+ observation.uid(),
+ observation.resourceVersion(),
+ intent.jwksJson(),
+ intent.generationMarkerJson());
+ requireUnchangedBindings(binding, apiIdentity);
+ return receipt;
+ });
+ if (persisted == null) {
+ throw new PublicationRejectedException("Account JWT JWKS API receipt was not persisted");
+ }
+ return persisted;
+ }
+
+ private CurrentGeneration loadCurrentGeneration(Binding binding, BindingIdentity apiIdentity) {
+ CurrentGeneration current =
+ accountTransaction.execute(
+ status -> {
+ GenerationResult result =
+ desiredStateRepository.readCurrentGenerationResult(
+ binding.accountBinding(), trustFence(binding));
+ GenerationRequest request =
+ desiredStateRepository.readCurrentGenerationRequest(
+ binding.accountBinding(), trustFence(binding));
+ Optional publication =
+ publicationRepository.readCurrentPublication(
+ binding.accountBinding(), trustFence(binding));
+ if (!result.binding().equals(binding.accountBinding())
+ || !result.trustFence().equals(trustFence(binding))
+ || !request.operationId().equals(result.operationId())
+ || !request.generationReceiptDigest().equals(result.receiptDigest())) {
+ throw new PublicationRejectedException(
+ "Account JWT generation receipt does not match the current protected binding");
+ }
+ requireUnchangedBindings(binding, apiIdentity);
+ return new CurrentGeneration(result, request, publication);
+ });
+ if (current == null) {
+ throw new PublicationRejectedException("Current Account JWT generation is unavailable");
+ }
+ return current;
+ }
+
+ private Binding requireCurrentMaterializerBinding() {
+ Binding current = materializerTrustBinding.current().orElse(null);
+ if (current == null) {
+ throw new PublicationRejectedException(
+ "Protected Account JWT materializer binding is unavailable");
+ }
+ return current;
+ }
+
+ private static BindingIdentity requireMatchingApiIdentity(
+ Binding materializerBinding, BindingIdentity apiIdentity) {
+ if (apiIdentity == null
+ || !materializerBinding.environmentId().equals(apiIdentity.environmentId())
+ || !materializerBinding.clusterId().equals(apiIdentity.clusterId())
+ || !materializerBinding.namespace().equals(apiIdentity.namespace())
+ || !materializerBinding
+ .expectedClusterIncarnationUid()
+ .equals(apiIdentity.expectedClusterIncarnationUid())
+ || !materializerBinding.expectedNamespaceUid().equals(apiIdentity.expectedNamespaceUid())
+ || apiIdentity.bindingDigest() == null
+ || apiIdentity.configRevision() == null) {
+ throw new PublicationRejectedException(
+ "Protected Account materializer and ConfigMap API bindings disagree");
+ }
+ return apiIdentity;
+ }
+
+ private void requireUnchangedBindings(Binding expected, BindingIdentity expectedApiIdentity) {
+ if (materializerTrustBinding.current().filter(expected::equals).isEmpty()
+ || !expectedApiIdentity.equals(configMapClient.identity())) {
+ throw new PublicationRejectedException(
+ "Protected Account JWT publication trust changed during the operation");
+ }
+ }
+
+ private static void requireIntentApiIdentity(
+ PrepublicationIntent intent, BindingIdentity apiIdentity) {
+ if (!intent.apiBindingDigest().equals(apiIdentity.bindingDigest())
+ || !intent.apiConfigRevision().equals(apiIdentity.configRevision())) {
+ throw new PublicationRejectedException(
+ "Protected Account ConfigMap API trust changed for the current JWT operation");
+ }
+ }
+
+ private static void requirePublishedProjection(
+ PrepublicationIntent intent, ConfigMapSnapshot snapshot) {
+ if (!intent.configMapUid().equals(snapshot.uid())
+ || !intent
+ .jwksJson()
+ .equals(snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY))
+ || !intent
+ .generationMarkerJson()
+ .equals(
+ snapshot
+ .data()
+ .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY))) {
+ throw new PublicationRejectedException(
+ "Current public JWT ConfigMap no longer matches Account's immutable receipt");
+ }
+ }
+
+ private static void requireRetrySnapshot(
+ PrepublicationIntent intent, ConfigMapSnapshot snapshot) {
+ if (!intent.configMapUid().equals(snapshot.uid())) {
+ throw new PublicationRejectedException(
+ "Account public JWKS ConfigMap UID changed after intent creation");
+ }
+ if (intent
+ .jwksJson()
+ .equals(snapshot.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY))
+ && intent
+ .generationMarkerJson()
+ .equals(
+ snapshot
+ .data()
+ .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY))) {
+ return;
+ }
+ if (!intent.expectedResourceVersion().equals(snapshot.resourceVersion())
+ || !intent
+ .expectedSnapshotDigest()
+ .equals(AccountJwtJwksPublicationRepository.snapshotDigest(snapshot.data()))) {
+ throw new PublicationRejectedException(
+ "Account public JWKS ConfigMap changed after immutable intent creation");
+ }
+ }
+
+ private static Map desiredData(PrepublicationIntent intent) {
+ Map data = new LinkedHashMap<>();
+ data.put(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY, intent.jwksJson());
+ data.put(
+ AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY,
+ intent.generationMarkerJson());
+ return Map.copyOf(data);
+ }
+
+ private static String appendPendingPublicKey(String sourceJwks, GenerationResult result) {
+ JsonNode root = parseStrictJson(sourceJwks, AccountJwtJwksPublicationRepository.MAX_JWKS_BYTES);
+ boolean supportedRoot = root.size() == JWKS_ROOT_FIELDS.size();
+ for (Map.Entry field : root.properties()) {
+ supportedRoot &= JWKS_ROOT_FIELDS.contains(field.getKey());
+ }
+ if (!supportedRoot) {
+ throw new PublicationRejectedException("Existing Account JWKS has an unsupported shape");
+ }
+ JsonNode keys = root.get("keys");
+ if (keys == null || !keys.isArray() || keys.size() >= MAX_KEYS) {
+ throw new PublicationRejectedException(
+ "Existing Account JWKS is missing or at its key limit");
+ }
+ Set kids = new HashSet<>();
+ List canonicalKeys = new ArrayList<>(keys.size() + 1);
+ for (JsonNode jwk : keys) {
+ validateRetainedJwk(jwk);
+ String kid = jwk.get("kid").textValue();
+ if (!kids.add(kid) || kid.equals(result.targetKid())) {
+ throw new PublicationRejectedException(
+ "Existing Account JWKS has a duplicate or conflicting key identifier");
+ }
+ canonicalKeys.add(canonicalJson(jwk.toString()));
+ }
+ JsonNode pending = parseStrictJson(result.publicJwkJson(), 8 * 1024);
+ validateRetainedJwk(pending);
+ if (!result.targetKid().equals(pending.get("kid").textValue())
+ || !kids.add(result.targetKid())) {
+ throw new PublicationRejectedException(
+ "Account generation receipt has a conflicting public key identifier");
+ }
+ canonicalKeys.add(canonicalJson(result.publicJwkJson()));
+ String jwks = "{\"keys\":[" + String.join(",", canonicalKeys) + "]}";
+ if (jwks.getBytes(StandardCharsets.UTF_8).length
+ > AccountJwtJwksPublicationRepository.MAX_JWKS_BYTES) {
+ throw new PublicationRejectedException("Account public JWKS exceeds its storage bound");
+ }
+ return jwks;
+ }
+
+ private static void validateRetainedJwk(JsonNode jwk) {
+ if (jwk == null || !jwk.isObject() || jwk.size() < 6 || jwk.size() > 7) {
+ throw new PublicationRejectedException("Existing Account JWKS contains a malformed key");
+ }
+ for (Map.Entry field : jwk.properties()) {
+ if (!JWK_FIELDS.contains(field.getKey())) {
+ throw new PublicationRejectedException(
+ "Existing Account JWKS contains an unsupported or private key field");
+ }
+ }
+ String kty = requiredText(jwk, "kty", 8);
+ String use = requiredText(jwk, "use", 8);
+ String alg = requiredText(jwk, "alg", 8);
+ String kid = requiredText(jwk, "kid", 64);
+ String n = requiredText(jwk, "n", 4096);
+ String e = requiredText(jwk, "e", 16);
+ if (!"RSA".equals(kty)
+ || !"sig".equals(use)
+ || !"RS256".equals(alg)
+ || !KID.matcher(kid).matches()) {
+ throw new PublicationRejectedException("Existing Account JWKS contains an unsupported key");
+ }
+ JsonNode keyOps = jwk.get("key_ops");
+ if (keyOps != null
+ && (!keyOps.isArray()
+ || keyOps.size() != 1
+ || !keyOps.get(0).isTextual()
+ || !"verify".equals(keyOps.get(0).textValue()))) {
+ throw new PublicationRejectedException("Existing Account JWKS key operations are malformed");
+ }
+ byte[] modulus = decodeBase64Url(n, 2048);
+ byte[] exponent = decodeBase64Url(e, 8);
+ try {
+ if (modulus.length == 0 || modulus[0] == 0 || exponent.length == 0 || exponent[0] == 0) {
+ throw new PublicationRejectedException(
+ "Existing Account JWKS RSA parameters are malformed");
+ }
+ BigInteger modulusValue = new BigInteger(1, modulus);
+ BigInteger exponentValue = new BigInteger(1, exponent);
+ if (modulusValue.bitLength() < MIN_RSA_BITS
+ || modulusValue.bitLength() > MAX_RSA_BITS
+ || !modulusValue.testBit(0)
+ || !BigInteger.valueOf(65_537).equals(exponentValue)) {
+ throw new PublicationRejectedException(
+ "Existing Account JWKS RSA parameters are unsupported");
+ }
+ KeyFactory.getInstance("RSA")
+ .generatePublic(new RSAPublicKeySpec(modulusValue, exponentValue));
+ } catch (Exception ex) {
+ if (ex instanceof PublicationRejectedException rejected) {
+ throw rejected;
+ }
+ throw new PublicationRejectedException("Existing Account JWKS RSA parameters are invalid");
+ } finally {
+ Arrays.fill(modulus, (byte) 0);
+ Arrays.fill(exponent, (byte) 0);
+ }
+ }
+
+ private static String generationMarker(
+ GenerationResult result, GenerationRequest request, BindingIdentity apiIdentity) {
+ Map marker = new LinkedHashMap<>();
+ marker.put("schemaVersion", 1);
+ marker.put("phase", "PREPUBLISHED");
+ marker.put("operationId", result.operationId().toString());
+ marker.put("operationDigest", result.operationDigest());
+ marker.put("generationRequestDigest", result.generationRequestDigest());
+ marker.put("generationReceiptDigest", result.receiptDigest());
+ Map binding = new LinkedHashMap<>();
+ binding.put("environmentId", result.binding().environmentId());
+ binding.put("clusterId", result.binding().clusterId());
+ binding.put("namespace", result.binding().namespace());
+ binding.put(
+ "expectedClusterIncarnationUid", result.trustFence().expectedClusterIncarnationUid());
+ binding.put("expectedNamespaceUid", result.trustFence().expectedNamespaceUid());
+ binding.put("trustBindingDigest", result.trustFence().bindingDigest());
+ binding.put("trustConfigRevision", result.trustFence().configRevision());
+ binding.put("apiBindingDigest", apiIdentity.bindingDigest());
+ binding.put("apiConfigRevision", apiIdentity.configRevision());
+ marker.put("binding", binding);
+ marker.put("publicConfigMap", Map.of("name", "jwt-jwks"));
+ marker.put("expectedDurableActive", activeMarker(request.expectedActive()));
+ marker.put("expectedPublishedActive", activeMarker(request.expectedPublishedActive()));
+ Map pending = new LinkedHashMap<>();
+ pending.put("generation", result.targetGeneration());
+ pending.put("kid", result.targetKid());
+ pending.put("algorithm", result.targetAlgorithm());
+ pending.put("publicKeyFingerprint", result.publicKeyFingerprint());
+ marker.put("pending", pending);
+ return canonicalJson(marker);
+ }
+
+ private static Map activeMarker(
+ Optional active) {
+ Map marker = new LinkedHashMap<>();
+ marker.put("present", active.isPresent());
+ active.ifPresent(
+ signer -> {
+ marker.put("generation", signer.generation());
+ marker.put("kid", signer.kid());
+ });
+ return marker;
+ }
+
+ private static JsonNode parseStrictJson(String json, int maxBytes) {
+ if (json == null || json.isBlank() || json.getBytes(StandardCharsets.UTF_8).length > maxBytes) {
+ throw new PublicationRejectedException("Account public JWT JSON is missing or oversized");
+ }
+ try {
+ JsonNode node = STRICT_JSON.readTree(json);
+ if (node == null || !node.isObject()) {
+ throw new PublicationRejectedException("Account public JWT JSON has an unsupported shape");
+ }
+ return node;
+ } catch (PublicationRejectedException ex) {
+ throw ex;
+ } catch (Exception ex) {
+ throw new PublicationRejectedException("Account public JWT JSON is malformed");
+ }
+ }
+
+ private static String requiredText(JsonNode object, String field, int maxLength) {
+ JsonNode value = object.get(field);
+ if (value == null
+ || !value.isTextual()
+ || value.textValue().isEmpty()
+ || value.textValue().length() > maxLength) {
+ throw new PublicationRejectedException("Existing Account JWKS key is malformed");
+ }
+ return value.textValue();
+ }
+
+ private static byte[] decodeBase64Url(String value, int maxBytes) {
+ if (value == null
+ || value.isEmpty()
+ || value.contains("=")
+ || !value.matches("[A-Za-z0-9_-]+")) {
+ throw new PublicationRejectedException("Existing Account JWKS RSA parameters are malformed");
+ }
+ try {
+ byte[] decoded = Base64.getUrlDecoder().decode(value);
+ if (decoded.length > maxBytes
+ || !Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(value)) {
+ Arrays.fill(decoded, (byte) 0);
+ throw new PublicationRejectedException(
+ "Existing Account JWKS RSA parameters are malformed");
+ }
+ return decoded;
+ } catch (IllegalArgumentException ex) {
+ throw new PublicationRejectedException("Existing Account JWKS RSA parameters are malformed");
+ }
+ }
+
+ private static String canonicalJson(String json) {
+ try {
+ return new String(Rfc8785CanonicalJson.canonicalizeUtf8(json), StandardCharsets.UTF_8);
+ } catch (IOException ex) {
+ throw new PublicationRejectedException("Account public JWT JSON canonicalization failed");
+ }
+ }
+
+ private static String canonicalJson(Object value) {
+ try {
+ return canonicalJson(STRICT_JSON.writeValueAsString(value));
+ } catch (Exception ex) {
+ throw new PublicationRejectedException("Account public JWT marker encoding failed");
+ }
+ }
+
+ private static byte[] readMountedFile(Path configuredRoot, Path relativePath, int maxBytes) {
+ try {
+ if (configuredRoot == null
+ || relativePath == null
+ || relativePath.isAbsolute()
+ || relativePath.normalize().startsWith("..")) {
+ throw new IOException("Mounted file path is invalid");
+ }
+ Path root = configuredRoot.toRealPath();
+ if (!Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS)) {
+ throw new IOException("Mounted root is unavailable");
+ }
+ Path unresolved = root.resolve(relativePath).normalize();
+ if (!unresolved.startsWith(root)) {
+ throw new IOException("Mounted file escapes its projection");
+ }
+ Path file = unresolved.toRealPath();
+ if (!file.startsWith(root) || !Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) {
+ throw new IOException("Mounted file is unavailable");
+ }
+ BasicFileAttributes before =
+ Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+ if (before.size() <= 0 || before.size() > maxBytes) {
+ throw new IOException("Mounted file size is invalid");
+ }
+ byte[] bytes = new byte[(int) before.size()];
+ try (SeekableByteChannel channel =
+ Files.newByteChannel(file, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
+ ByteBuffer buffer = ByteBuffer.wrap(bytes);
+ while (buffer.hasRemaining()) {
+ if (channel.read(buffer) < 0) {
+ throw new IOException("Mounted file changed while being read");
+ }
+ }
+ if (channel.read(ByteBuffer.allocate(1)) != -1) {
+ throw new IOException("Mounted file changed while being read");
+ }
+ }
+ BasicFileAttributes after =
+ Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
+ if (!after.isRegularFile()
+ || !Objects.equals(before.fileKey(), after.fileKey())
+ || before.size() != after.size()
+ || !before.lastModifiedTime().equals(after.lastModifiedTime())) {
+ Arrays.fill(bytes, (byte) 0);
+ throw new IOException("Mounted file changed while being read");
+ }
+ return bytes;
+ } catch (IOException | RuntimeException ex) {
+ throw new PublicationRejectedException(
+ "Mounted Account JWT public projection is unavailable or invalid");
+ }
+ }
+
+ private static String strictUtf8(byte[] bytes) {
+ try {
+ return StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(bytes))
+ .toString();
+ } catch (CharacterCodingException ex) {
+ throw new PublicationRejectedException("Mounted Account JWT public projection is not UTF-8");
+ }
+ }
+
+ private static String sha256(byte[] value) {
+ try {
+ return java.util.HexFormat.of()
+ .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(value));
+ } catch (java.security.NoSuchAlgorithmException ex) {
+ throw new IllegalStateException("SHA-256 is unavailable", ex);
+ }
+ }
+
+ private static TrustFence trustFence(Binding binding) {
+ return new TrustFence(
+ binding.expectedClusterIncarnationUid(),
+ binding.expectedNamespaceUid(),
+ binding.bindingDigest(),
+ binding.configRevision());
+ }
+
+ private record CurrentGeneration(
+ GenerationResult result,
+ GenerationRequest request,
+ Optional publication) {}
+
+ /** Fixed filesystem projections; production paths are not request inputs. */
+ record MountedProjection(
+ Path privateMountRoot,
+ Path pendingBundlePath,
+ Path publicMountRoot,
+ Path jwksPath,
+ Path markerPath) {
+ MountedProjection {
+ Objects.requireNonNull(privateMountRoot);
+ Objects.requireNonNull(pendingBundlePath);
+ Objects.requireNonNull(publicMountRoot);
+ Objects.requireNonNull(jwksPath);
+ Objects.requireNonNull(markerPath);
+ if (pendingBundlePath.isAbsolute()
+ || jwksPath.isAbsolute()
+ || markerPath.isAbsolute()
+ || pendingBundlePath.normalize().startsWith("..")
+ || jwksPath.normalize().startsWith("..")
+ || markerPath.normalize().startsWith("..")) {
+ throw new IllegalArgumentException("JWT mounted projection paths must be relative");
+ }
+ }
+ }
+
+ /** Safe generic failure; never includes a key, ConfigMap response body, or mounted path. */
+ public static final class PublicationRejectedException extends IllegalStateException {
+ public PublicationRejectedException(String message) {
+ super(message);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java
new file mode 100644
index 0000000000..4742f95fed
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java
@@ -0,0 +1,761 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HexFormat;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding;
+import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PrepublicationIntent;
+import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository.PublicationReceipt;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveSigner;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot;
+import net.firedevops.firemud.common.json.Rfc8785CanonicalJson;
+import net.firedevops.firemud.common.security.AccountPublicJwksCache;
+import net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot;
+import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity;
+import net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceUnavailableException;
+import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Account-owned authenticated read adapter for the current public JWKS publication.
+ *
+ * The cache pin is derived from Account's root-protected Kubernetes API binding and exact
+ * Account-owned publication evidence. The first receipt-backed PREPUBLISHED key can be served to
+ * readiness probes before a signer is committed, but is never represented as active authority.
+ * During ordinary prepublication of a next key, the prior committed key remains the only active
+ * signer while the exact new public set may be served for validation overlap. PREPARED and
+ * unexplained resource changes deny. This adapter exposes only public JWKS bytes and grants no
+ * signing, registry, readiness, or admission authority.
+ */
+public final class AccountJwtJwksTrustedSource
+ implements AccountPublicJwksCache.TrustedPublicJwksSource {
+ private static final int MAX_JWKS_BYTES = 256 * 1024;
+ private static final int MAX_MARKER_BYTES = 16 * 1024;
+ private static final String ACCOUNT_SERVICE_USERNAME_PREFIX = "system:serviceaccount:";
+ private static final String ACCOUNT_SERVICE_NAME = "account-service";
+ private static final int MAX_KEYS = 64;
+ private static final java.util.Set JWKS_FIELDS = java.util.Set.of("keys");
+ private static final java.util.Set JWK_FIELDS =
+ java.util.Set.of("kty", "use", "alg", "kid", "key_ops", "n", "e");
+ private static final JsonMapper STRICT_JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+
+ private final AccountJwtJwksConfigMapClient configMapClient;
+ private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding;
+ private final AccountJwtSignerDesiredStateRepository desiredStateRepository;
+ private final AccountJwtJwksPublicationRepository publicationRepository;
+ private final TransactionTemplate accountTransaction;
+ private final Object pinMonitor = new Object();
+
+ private volatile TrustedPin trustedPin;
+
+ /** Constructs an inactive adapter over Account's real protected API and owner-recorded state. */
+ public AccountJwtJwksTrustedSource(
+ AccountJwtJwksConfigMapClient configMapClient,
+ AccountJwtSignerMaterializerTrustBinding materializerTrustBinding,
+ AccountJwtSignerDesiredStateRepository desiredStateRepository,
+ AccountJwtJwksPublicationRepository publicationRepository,
+ PlatformTransactionManager transactionManager) {
+ this.configMapClient =
+ Objects.requireNonNull(configMapClient, "Account ConfigMap client is required");
+ this.materializerTrustBinding =
+ Objects.requireNonNull(materializerTrustBinding, "Protected Account trust is required");
+ this.desiredStateRepository =
+ Objects.requireNonNull(desiredStateRepository, "Account signer repository is required");
+ this.publicationRepository =
+ Objects.requireNonNull(publicationRepository, "Account publication repository is required");
+ this.accountTransaction =
+ new TransactionTemplate(
+ Objects.requireNonNull(transactionManager, "Account transaction manager is required"));
+ this.accountTransaction.setReadOnly(false);
+ }
+
+ /**
+ * Establishes the immutable cache pin from a coherent, protected Account read. A cache owner
+ * obtains its expected source identity here; it is not accepted as caller-supplied evidence.
+ */
+ public SourceIdentity sourceIdentity() {
+ TrustedPin current = trustedPin;
+ if (current != null) {
+ return current.sourceIdentity();
+ }
+ synchronized (pinMonitor) {
+ current = trustedPin;
+ if (current == null) {
+ VerifiedSource verified = readVerifiedSource();
+ current = verified.pin();
+ trustedPin = current;
+ }
+ }
+ return current.sourceIdentity();
+ }
+
+ /**
+ * Derives one key's RFC 7638 fingerprint from a snapshot already loaded through this trusted
+ * source. It compares the immutable pin and grants no signer, registry, or token authority.
+ */
+ static Optional publicKeyFingerprint(
+ PublicJwksSnapshot snapshot, SourceIdentity expectedSourceIdentity, String kid) {
+ if (snapshot == null
+ || expectedSourceIdentity == null
+ || !expectedSourceIdentity.equals(snapshot.sourceIdentity())
+ || kid == null
+ || !kid.matches("[A-Za-z0-9_-]{1,64}")) {
+ throw rejected();
+ }
+ Map fingerprints =
+ publicKeyFingerprints(new String(snapshot.jwksBytes(), StandardCharsets.UTF_8));
+ return Optional.ofNullable(fingerprints.get(kid));
+ }
+
+ /**
+ * Loads one exact public JWKS snapshot after checking Account trust and receipt readback twice.
+ */
+ @Override
+ public PublicJwksSnapshot load() {
+ TrustedPin expected = trustedPin;
+ if (expected == null) {
+ throw rejected();
+ }
+ VerifiedSource verified = readVerifiedSource();
+ if (!expected.equals(verified.pin())) {
+ throw rejected();
+ }
+ return new PublicJwksSnapshot(expected.sourceIdentity(), verified.jwksBytes());
+ }
+
+ private VerifiedSource readVerifiedSource() {
+ Binding materializerBefore = currentMaterializerBinding();
+ BindingIdentity apiBefore = currentApiIdentity();
+ requireBindingsAgree(materializerBefore, apiBefore);
+ TrustedPin alreadyPinned = trustedPin;
+ if (alreadyPinned != null
+ && (!alreadyPinned.materializerBinding().equals(materializerBefore)
+ || !alreadyPinned.apiIdentity().equals(apiBefore))) {
+ throw rejected();
+ }
+
+ OwnerProjection ownerBefore = currentOwnerProjection(materializerBefore, apiBefore);
+ SourceIdentity pinnedIdentity =
+ sourceIdentity(materializerBefore, apiBefore, ownerBefore.projection().configMapUid());
+ if (alreadyPinned != null && !alreadyPinned.sourceIdentity().equals(pinnedIdentity)) {
+ throw rejected();
+ }
+
+ ConfigMapSnapshot live;
+ try {
+ live = configMapClient.observe();
+ } catch (AccountJwtJwksConfigMapClient.ResourceMissingException unavailable) {
+ requireUnchangedProtectedTrust(materializerBefore, apiBefore);
+ throw unavailable();
+ } catch (AccountJwtJwksConfigMapClient.ApiFailureException failure) {
+ requireUnchangedProtectedTrust(materializerBefore, apiBefore);
+ if (isTemporaryApiFailure(failure.statusCode())) {
+ throw unavailable();
+ }
+ throw rejected();
+ } catch (AccountJwtJwksConfigMapClient.BindingRejectedException trustRejected) {
+ throw rejected();
+ } catch (RuntimeException unexpected) {
+ throw rejected();
+ }
+
+ Binding materializerAfter = currentMaterializerBinding();
+ BindingIdentity apiAfter = currentApiIdentity();
+ if (!materializerBefore.equals(materializerAfter) || !apiBefore.equals(apiAfter)) {
+ throw rejected();
+ }
+
+ OwnerProjection ownerAfter = currentOwnerProjection(materializerAfter, apiAfter);
+ if (!ownerBefore.equals(ownerAfter)) {
+ // A concurrent Account lifecycle/publication change is not a coherent source snapshot.
+ throw unavailable();
+ }
+ requireExactReadback(ownerAfter.projection(), live);
+
+ byte[] jwks =
+ live.data()
+ .get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY)
+ .getBytes(StandardCharsets.UTF_8);
+ if (jwks.length == 0 || jwks.length > MAX_JWKS_BYTES) {
+ throw rejected();
+ }
+ TrustedPin pin = new TrustedPin(materializerBefore, apiBefore, pinnedIdentity);
+ return new VerifiedSource(pin, jwks);
+ }
+
+ private Binding currentMaterializerBinding() {
+ return materializerTrustBinding.current().orElseThrow(AccountJwtJwksTrustedSource::rejected);
+ }
+
+ private BindingIdentity currentApiIdentity() {
+ try {
+ return Objects.requireNonNull(configMapClient.identity());
+ } catch (RuntimeException rejectedBinding) {
+ throw rejected();
+ }
+ }
+
+ private OwnerProjection currentOwnerProjection(Binding binding, BindingIdentity api) {
+ if (TransactionSynchronizationManager.isActualTransactionActive()) {
+ throw rejected();
+ }
+ try {
+ OwnerProjection result =
+ accountTransaction.execute(
+ status -> {
+ DesiredState enrolled =
+ desiredStateRepository
+ .readEnrollmentState(binding.accountBinding())
+ .orElseThrow(AccountJwtJwksTrustedSource::unavailable);
+ if (enrolled.durableActive().isEmpty() && enrolled.publishedActive().isEmpty()) {
+ return initialPrepublicationProjection(enrolled, binding, api);
+ }
+ CommittedSignerEvidence committed =
+ desiredStateRepository
+ .readCurrentCommittedSigner(
+ binding.accountBinding(),
+ trustFence(binding),
+ api.bindingDigest(),
+ api.configRevision())
+ .orElseThrow(AccountJwtJwksTrustedSource::unavailable);
+ ActiveSigner currentActive =
+ new ActiveSigner(
+ committed.promotion().targetGeneration(),
+ committed.promotion().targetKid());
+ PublishedProjection projection = committedProjection(committed);
+ if (committed.desiredState().generationOperationId().isEmpty()) {
+ return new OwnerProjection(committed, projection);
+ }
+
+ var request =
+ desiredStateRepository.readCurrentGenerationRequest(
+ binding.accountBinding(), trustFence(binding));
+ if (request.phase()
+ != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED) {
+ return new OwnerProjection(committed, projection);
+ }
+ Optional currentPublication =
+ publicationRepository.readCurrentPublication(
+ binding.accountBinding(), trustFence(binding));
+ if (currentPublication.isEmpty()
+ || currentPublication.orElseThrow().receipt().isEmpty()) {
+ return new OwnerProjection(committed, projection);
+ }
+ PublicationEvidence evidence = currentPublication.orElseThrow();
+ requirePublicationBinding(evidence, binding, api);
+ PrepublicationIntent intent = evidence.intent();
+ var receipt = evidence.receipt().orElseThrow();
+ if (!intent.operationId().equals(request.operationId())
+ || !intent.operationDigest().equals(request.operationDigest())
+ || !intent.generationRequestDigest().equals(request.generationRequestDigest())
+ || !intent.generationReceiptDigest().equals(request.generationReceiptDigest())
+ || !intent.targetGeneration().equals(request.targetGeneration())
+ || !intent.targetKid().equals(request.targetKid())
+ || !intent.publicKeyFingerprint().equals(request.publicKeyFingerprint())
+ || !intent.expectedDurableActive().equals(Optional.of(currentActive))
+ || !intent.expectedPublishedActive().equals(Optional.of(currentActive))
+ || !intent.configMapUid().equals(committed.promotion().publicConfigMapUid())
+ || !receipt.configMapUid().equals(committed.promotion().publicConfigMapUid())
+ || !intent.apiBindingDigest().equals(api.bindingDigest())
+ || !intent.apiConfigRevision().equals(api.configRevision())) {
+ throw rejected();
+ }
+ requireRetainedPublicKeySet(committed, intent);
+ return new OwnerProjection(
+ committed,
+ new PublishedProjection(
+ intent.configMapUid(),
+ receipt.observedResourceVersion(),
+ intent.jwksJson(),
+ intent.generationMarkerJson(),
+ receipt.publicDataDigest()));
+ });
+ if (result == null) {
+ throw unavailable();
+ }
+ return result;
+ } catch (RuntimeException ownerStateUnavailable) {
+ if (ownerStateUnavailable instanceof SourceUnavailableException unavailable) {
+ throw unavailable;
+ }
+ if (ownerStateUnavailable instanceof IllegalStateException
+ && ownerStateUnavailable.getMessage() != null
+ && ownerStateUnavailable.getMessage().contains("Account trusted public JWKS source")) {
+ throw ownerStateUnavailable;
+ }
+ throw rejected();
+ }
+ }
+
+ /**
+ * The first exact Account-receipted PREPUBLISHED set is visible to validator probes before any
+ * signer is committed. It is never represented as an active signer and remains unavailable during
+ * PREPARED or after any active fence appears.
+ */
+ private OwnerProjection initialPrepublicationProjection(
+ DesiredState enrolled, Binding binding, BindingIdentity api) {
+ if (!enrolled.binding().equals(binding.accountBinding())
+ || enrolled.preparedOperationId().isPresent()
+ || enrolled.generationOperationId().isEmpty()
+ || enrolled.enrollmentIdentity().isEmpty()) {
+ throw rejected();
+ }
+ EnrollmentIdentity enrollment = enrolled.enrollmentIdentity().orElseThrow();
+ if (!enrollment.expectedClusterIncarnationUid().equals(binding.expectedClusterIncarnationUid())
+ || !enrollment.expectedNamespaceUid().equals(binding.expectedNamespaceUid())
+ || !enrollment.materializerTrustBindingDigest().equals(binding.bindingDigest())
+ || !enrollment.materializerTrustConfigRevision().equals(binding.configRevision())
+ || !enrollment.apiBindingDigest().equals(api.bindingDigest())
+ || !enrollment.apiConfigRevision().equals(api.configRevision())) {
+ throw rejected();
+ }
+
+ GenerationRequest request =
+ desiredStateRepository.readCurrentGenerationRequest(
+ binding.accountBinding(), trustFence(binding));
+ GenerationResult result =
+ desiredStateRepository.readCurrentGenerationResult(
+ binding.accountBinding(), trustFence(binding));
+ if (request.phase()
+ != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED
+ || !request.expectedActive().isEmpty()
+ || !request.expectedPublishedActive().isEmpty()
+ || !enrolled.generationOperationId().equals(Optional.of(request.operationId()))
+ || !request.binding().equals(binding.accountBinding())
+ || !request.trustFence().equals(trustFence(binding))
+ || !result.binding().equals(binding.accountBinding())
+ || !result.trustFence().equals(trustFence(binding))
+ || request.desiredStateVersion() != result.desiredStateVersion()
+ || !request.operationId().equals(result.operationId())
+ || !request.operationDigest().equals(result.operationDigest())
+ || !request.generationRequestDigest().equals(result.generationRequestDigest())
+ || !request.targetGeneration().equals(result.targetGeneration())
+ || !request.targetKid().equals(result.targetKid())
+ || !request.publicKeyFingerprint().equals(result.publicKeyFingerprint())
+ || !request.publicJwkJson().equals(result.publicJwkJson())
+ || !"RS256".equals(result.targetAlgorithm())) {
+ throw rejected();
+ }
+
+ PublicationEvidence evidence =
+ publicationRepository
+ .readCurrentPublication(binding.accountBinding(), trustFence(binding))
+ .orElseThrow(AccountJwtJwksTrustedSource::unavailable);
+ requirePublicationBinding(evidence, binding, api);
+ PrepublicationIntent intent = evidence.intent();
+ var receipt = evidence.receipt().orElseThrow(AccountJwtJwksTrustedSource::unavailable);
+ if (!intent.operationId().equals(result.operationId())
+ || !intent.operationDigest().equals(result.operationDigest())
+ || !intent.generationRequestDigest().equals(result.generationRequestDigest())
+ || !intent.generationReceiptDigest().equals(result.receiptDigest())
+ || intent.desiredStateVersion() != result.desiredStateVersion()
+ || !intent.expectedDurableActive().isEmpty()
+ || !intent.expectedPublishedActive().isEmpty()
+ || !intent.configMapUid().equals(enrollment.publicConfigMapUid())
+ || !receipt.configMapUid().equals(enrollment.publicConfigMapUid())
+ || !intent.apiBindingDigest().equals(enrollment.apiBindingDigest())
+ || !intent.apiConfigRevision().equals(enrollment.apiConfigRevision())
+ || !intent.targetGeneration().equals(result.targetGeneration())
+ || !intent.targetKid().equals(result.targetKid())
+ || !intent.publicKeyFingerprint().equals(result.publicKeyFingerprint())) {
+ throw rejected();
+ }
+ Map publicKeys = publicKeyFingerprints(intent.jwksJson());
+ if (publicKeys.size() != 1
+ || !result.publicKeyFingerprint().equals(publicKeys.get(result.targetKid()))) {
+ throw rejected();
+ }
+ requireInitialPrepublicationMarker(intent, result, binding, api);
+ return new OwnerProjection(
+ null,
+ new PublishedProjection(
+ intent.configMapUid(),
+ receipt.observedResourceVersion(),
+ intent.jwksJson(),
+ intent.generationMarkerJson(),
+ receipt.publicDataDigest()));
+ }
+
+ private static void requireInitialPrepublicationMarker(
+ PrepublicationIntent intent, GenerationResult result, Binding binding, BindingIdentity api) {
+ try {
+ JsonNode marker = STRICT_JSON.readTree(intent.generationMarkerJson());
+ JsonNode markerBinding = marker == null ? null : marker.get("binding");
+ JsonNode publicConfigMap = marker == null ? null : marker.get("publicConfigMap");
+ JsonNode pending = marker == null ? null : marker.get("pending");
+ JsonNode durable = marker == null ? null : marker.get("expectedDurableActive");
+ JsonNode published = marker == null ? null : marker.get("expectedPublishedActive");
+ if (marker == null
+ || !marker.isObject()
+ || !hasExactFields(
+ marker,
+ java.util.Set.of(
+ "schemaVersion",
+ "phase",
+ "operationId",
+ "operationDigest",
+ "generationRequestDigest",
+ "generationReceiptDigest",
+ "binding",
+ "publicConfigMap",
+ "expectedDurableActive",
+ "expectedPublishedActive",
+ "pending"))
+ || !marker.get("schemaVersion").isIntegralNumber()
+ || marker.get("schemaVersion").intValue() != 1
+ || !"PREPUBLISHED".equals(requiredText(marker, "phase"))
+ || !intent.operationId().toString().equals(requiredText(marker, "operationId"))
+ || !intent.operationDigest().equals(requiredText(marker, "operationDigest"))
+ || !intent
+ .generationRequestDigest()
+ .equals(requiredText(marker, "generationRequestDigest"))
+ || !intent
+ .generationReceiptDigest()
+ .equals(requiredText(marker, "generationReceiptDigest"))
+ || !hasExactFields(
+ markerBinding,
+ java.util.Set.of(
+ "environmentId",
+ "clusterId",
+ "namespace",
+ "expectedClusterIncarnationUid",
+ "expectedNamespaceUid",
+ "trustBindingDigest",
+ "trustConfigRevision",
+ "apiBindingDigest",
+ "apiConfigRevision"))
+ || !binding.environmentId().equals(requiredText(markerBinding, "environmentId"))
+ || !binding.clusterId().equals(requiredText(markerBinding, "clusterId"))
+ || !binding.namespace().equals(requiredText(markerBinding, "namespace"))
+ || !binding
+ .expectedClusterIncarnationUid()
+ .equals(requiredText(markerBinding, "expectedClusterIncarnationUid"))
+ || !binding
+ .expectedNamespaceUid()
+ .equals(requiredText(markerBinding, "expectedNamespaceUid"))
+ || !binding.bindingDigest().equals(requiredText(markerBinding, "trustBindingDigest"))
+ || !binding.configRevision().equals(requiredText(markerBinding, "trustConfigRevision"))
+ || !api.bindingDigest().equals(requiredText(markerBinding, "apiBindingDigest"))
+ || !api.configRevision().equals(requiredText(markerBinding, "apiConfigRevision"))
+ || !hasExactFields(publicConfigMap, java.util.Set.of("name"))
+ || !AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME.equals(
+ requiredText(publicConfigMap, "name"))
+ || !hasExactFields(
+ pending, java.util.Set.of("generation", "kid", "algorithm", "publicKeyFingerprint"))
+ || !result.targetGeneration().equals(requiredText(pending, "generation"))
+ || !result.targetKid().equals(requiredText(pending, "kid"))
+ || !"RS256".equals(requiredText(pending, "algorithm"))
+ || !result.publicKeyFingerprint().equals(requiredText(pending, "publicKeyFingerprint"))
+ || !inactiveMarker(durable)
+ || !inactiveMarker(published)) {
+ throw rejected();
+ }
+ } catch (RuntimeException malformed) {
+ throw rejected();
+ }
+ }
+
+ private static boolean inactiveMarker(JsonNode marker) {
+ return hasExactFields(marker, java.util.Set.of("present"))
+ && marker.get("present").isBoolean()
+ && !marker.get("present").booleanValue();
+ }
+
+ private static void requireBindingsAgree(Binding materializer, BindingIdentity api) {
+ if (!materializer.environmentId().equals(api.environmentId())
+ || !materializer.clusterId().equals(api.clusterId())
+ || !materializer.namespace().equals(api.namespace())
+ || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid())
+ || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid())
+ || api.bindingDigest() == null
+ || api.configRevision() == null
+ || api.expectedApiUsername() == null
+ || !api.expectedApiUsername()
+ .equals(
+ ACCOUNT_SERVICE_USERNAME_PREFIX
+ + materializer.namespace()
+ + ":"
+ + ACCOUNT_SERVICE_NAME)) {
+ throw rejected();
+ }
+ URI endpoint;
+ try {
+ endpoint = URI.create(api.apiServerUrl());
+ } catch (RuntimeException malformedEndpoint) {
+ throw rejected();
+ }
+ if (!"https".equalsIgnoreCase(endpoint.getScheme())
+ || endpoint.getHost() == null
+ || endpoint.getPort() <= 0
+ || endpoint.getRawUserInfo() != null
+ || endpoint.getRawQuery() != null
+ || endpoint.getRawFragment() != null
+ || (endpoint.getRawPath() != null
+ && !endpoint.getRawPath().isEmpty()
+ && !"/".equals(endpoint.getRawPath()))
+ || api.tlsServerName() == null
+ || !endpoint.getHost().equalsIgnoreCase(api.tlsServerName())
+ || api.servingCaSha256() == null) {
+ throw rejected();
+ }
+ }
+
+ private static void requirePublicationBinding(
+ PublicationEvidence evidence, Binding materializer, BindingIdentity api) {
+ PrepublicationIntent intent = evidence.intent();
+ if (!intent.binding().equals(materializer.accountBinding())
+ || !intent.trustFence().equals(trustFence(materializer))
+ || !AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME.equals(intent.configMapName())
+ || !intent.apiBindingDigest().equals(api.bindingDigest())
+ || !intent.apiConfigRevision().equals(api.configRevision())
+ || !AccountJwtJwksPublicationRepository.publicDataDigest(
+ intent.jwksJson(), intent.generationMarkerJson())
+ .equals(intent.publicDataDigest())) {
+ throw rejected();
+ }
+ PublicationReceipt receipt = evidence.receipt().orElse(null);
+ if (receipt != null
+ && (!receipt.operationId().equals(intent.operationId())
+ || !receipt.binding().equals(materializer.accountBinding())
+ || !receipt.intentDigest().equals(intent.intentDigest())
+ || !receipt.configMapUid().equals(intent.configMapUid())
+ || !receipt.publicDataDigest().equals(intent.publicDataDigest())
+ || !receipt.expectedResourceVersion().equals(intent.expectedResourceVersion()))) {
+ throw rejected();
+ }
+ }
+
+ private static PublishedProjection committedProjection(CommittedSignerEvidence committed) {
+ PromotionOperationEvidence promotion = committed.promotion();
+ var receipt = committed.publicReceipt();
+ String dataDigest =
+ AccountJwtJwksPublicationRepository.publicDataDigest(
+ promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson());
+ if (!promotion.publicConfigMapUid().equals(receipt.configMapUid())
+ || !promotion
+ .activeJwksObservedResourceVersion()
+ .orElseThrow()
+ .equals(receipt.observedResourceVersion())
+ || !promotion.activeJwksPublicDataDigest().orElseThrow().equals(dataDigest)
+ || !receipt.publicDataDigest().equals(dataDigest)) {
+ throw rejected();
+ }
+ return new PublishedProjection(
+ receipt.configMapUid(),
+ receipt.observedResourceVersion(),
+ promotion.expectedPublicJwksJson(),
+ promotion.expectedActiveMarkerJson(),
+ dataDigest);
+ }
+
+ private static void requireRetainedPublicKeySet(
+ CommittedSignerEvidence committed, PrepublicationIntent intent) {
+ Map previousKeys =
+ publicKeyFingerprints(committed.promotion().expectedPublicJwksJson());
+ Map currentKeys = publicKeyFingerprints(intent.jwksJson());
+ if (previousKeys.isEmpty() || currentKeys.size() < previousKeys.size()) {
+ throw rejected();
+ }
+ if (new BigInteger(intent.targetGeneration())
+ .compareTo(new BigInteger(committed.promotion().targetGeneration()))
+ <= 0) {
+ throw rejected();
+ }
+ for (Map.Entry previous : previousKeys.entrySet()) {
+ if (!previous.getValue().equals(currentKeys.get(previous.getKey()))) {
+ throw rejected();
+ }
+ }
+ if (!intent.publicKeyFingerprint().equals(currentKeys.get(intent.targetKid()))
+ || !committed
+ .promotion()
+ .targetPublicKeyFingerprint()
+ .equals(currentKeys.get(committed.promotion().targetKid()))) {
+ throw rejected();
+ }
+ }
+
+ private static Map publicKeyFingerprints(String jwksJson) {
+ try {
+ if (jwksJson == null
+ || jwksJson.isBlank()
+ || jwksJson.getBytes(StandardCharsets.UTF_8).length > MAX_JWKS_BYTES) {
+ throw new IllegalArgumentException();
+ }
+ JsonNode root = STRICT_JSON.readTree(jwksJson);
+ if (root == null || !root.isObject() || !hasExactFields(root, JWKS_FIELDS)) {
+ throw new IllegalArgumentException();
+ }
+ JsonNode keys = root.get("keys");
+ if (keys == null || !keys.isArray() || keys.isEmpty() || keys.size() > MAX_KEYS) {
+ throw new IllegalArgumentException();
+ }
+ Map fingerprints = new LinkedHashMap<>();
+ for (JsonNode key : keys) {
+ if (key == null || !key.isObject() || !hasExactFields(key, JWK_FIELDS)) {
+ throw new IllegalArgumentException();
+ }
+ String kty = requiredText(key, "kty");
+ String use = requiredText(key, "use");
+ String alg = requiredText(key, "alg");
+ String kid = requiredText(key, "kid");
+ String modulus = requiredText(key, "n");
+ String exponent = requiredText(key, "e");
+ JsonNode keyOps = key.get("key_ops");
+ if (!"RSA".equals(kty)
+ || !"sig".equals(use)
+ || !"RS256".equals(alg)
+ || !kid.matches("[A-Za-z0-9_-]{1,64}")
+ || keyOps == null
+ || !keyOps.isArray()
+ || keyOps.size() != 1
+ || !keyOps.get(0).isTextual()
+ || !"verify".equals(keyOps.get(0).textValue())) {
+ throw new IllegalArgumentException();
+ }
+ String preimage =
+ new String(
+ Rfc8785CanonicalJson.canonicalizeUtf8(
+ STRICT_JSON.writeValueAsString(
+ Map.of("e", exponent, "kty", kty, "n", modulus))),
+ StandardCharsets.UTF_8);
+ String fingerprint =
+ HexFormat.of()
+ .formatHex(
+ MessageDigest.getInstance("SHA-256")
+ .digest(preimage.getBytes(StandardCharsets.UTF_8)));
+ if (fingerprints.putIfAbsent(kid, fingerprint) != null) {
+ throw new IllegalArgumentException();
+ }
+ }
+ return Map.copyOf(fingerprints);
+ } catch (IOException | NoSuchAlgorithmException | RuntimeException malformed) {
+ throw rejected();
+ }
+ }
+
+ private static String requiredText(JsonNode object, String field) {
+ JsonNode value = object.get(field);
+ if (value == null || !value.isTextual() || value.textValue().isEmpty()) {
+ throw new IllegalArgumentException();
+ }
+ return value.textValue();
+ }
+
+ private static boolean hasExactFields(JsonNode object, java.util.Set expected) {
+ if (object == null || !object.isObject() || object.size() != expected.size()) {
+ return false;
+ }
+ for (Map.Entry property : object.properties()) {
+ if (!expected.contains(property.getKey())) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static void requireExactReadback(PublishedProjection projection, ConfigMapSnapshot live) {
+ String jwks = live.data().get(AccountJwtJwksPublicationRepository.JWKS_DATA_KEY);
+ String marker = live.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY);
+ if (!projection.configMapUid().equals(live.uid())
+ || !projection.resourceVersion().equals(live.resourceVersion())
+ || !projection.jwksJson().equals(jwks)
+ || !projection.markerJson().equals(marker)
+ || marker == null
+ || marker.getBytes(StandardCharsets.UTF_8).length > MAX_MARKER_BYTES
+ || !AccountJwtJwksPublicationRepository.publicDataDigest(jwks, marker)
+ .equals(projection.publicDataDigest())) {
+ throw rejected();
+ }
+ }
+
+ private static SourceIdentity sourceIdentity(
+ Binding materializer, BindingIdentity api, String configMapUid) {
+ try {
+ return new SourceIdentity(
+ materializer.environmentId(),
+ materializer.clusterId(),
+ materializer.expectedClusterIncarnationUid(),
+ materializer.namespace(),
+ materializer.expectedNamespaceUid(),
+ configMapUid,
+ api.configRevision(),
+ api.apiServerUrl(),
+ api.servingCaSha256());
+ } catch (RuntimeException invalidIdentity) {
+ throw rejected();
+ }
+ }
+
+ private void requireUnchangedProtectedTrust(Binding expected, BindingIdentity expectedApi) {
+ Binding currentMaterializer = currentMaterializerBinding();
+ BindingIdentity currentApi = currentApiIdentity();
+ if (!expected.equals(currentMaterializer) || !expectedApi.equals(currentApi)) {
+ throw rejected();
+ }
+ }
+
+ private static boolean isTemporaryApiFailure(int statusCode) {
+ return statusCode == 0 || statusCode == 408 || statusCode == 429 || statusCode >= 500;
+ }
+
+ private static TrustFence trustFence(Binding binding) {
+ return new TrustFence(
+ binding.expectedClusterIncarnationUid(),
+ binding.expectedNamespaceUid(),
+ binding.bindingDigest(),
+ binding.configRevision());
+ }
+
+ private static SourceUnavailableException unavailable() {
+ return new SourceUnavailableException();
+ }
+
+ private static IllegalStateException rejected() {
+ return new IllegalStateException("Account trusted public JWKS source was rejected");
+ }
+
+ private record TrustedPin(
+ Binding materializerBinding, BindingIdentity apiIdentity, SourceIdentity sourceIdentity) {}
+
+ private record OwnerProjection(
+ CommittedSignerEvidence committedSigner, PublishedProjection projection) {}
+
+ private record PublishedProjection(
+ String configMapUid,
+ String resourceVersion,
+ String jwksJson,
+ String markerJson,
+ String publicDataDigest) {}
+
+ private record VerifiedSource(TrustedPin pin, byte[] jwksBytes) {}
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java
new file mode 100644
index 0000000000..c001802deb
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java
@@ -0,0 +1,554 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.DeliveryClaim;
+import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ExpectedPod;
+import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.OwnerProbeEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry;
+import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState;
+import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessProbePlan;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtReadinessReceiverInvocationPort.AuthenticatedAcceptance;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext;
+import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ExpectedIdentity;
+import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ProbeKind;
+import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.ReadinessProbeSigningSpec;
+import net.firedevops.firemud.accountservice.service.session.AccountMountedJwtSignerBundle.SignedProbeDigest;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Dormant, owner-internal producer for durable Account readiness-probe plans and constrained
+ * pending-key signatures.
+ *
+ * This class is intentionally not a Spring component. Its per-invocation callback receives the
+ * exact compact probe only for the duration of the call; this producer persists only its hash. The
+ * caller must supply the already-persisted one-shot delivery claim. The separate readiness route
+ * may record an authenticated non-authorizing observation, but neither path can promote a signer.
+ */
+public final class AccountJwtReadinessProbeService {
+ private static final Path PRIVATE_MOUNT = privateSignerMount();
+
+ private static final Path PRIVATE_PENDING_BUNDLE = Path.of("pending.key");
+
+ private static final Path PUBLIC_MOUNT = publicJwksMount();
+
+ private static final Path PUBLIC_JWKS = Path.of("jwks.json");
+
+ @SuppressFBWarnings(
+ value = "DMI_HARDCODED_ABSOLUTE_FILENAME",
+ justification =
+ "The interim private signer projection is intentionally fixed to Account's protected read-only mount.")
+ private static Path privateSignerMount() {
+ return Path.of("/var/run/secrets/firemud/jwt");
+ }
+
+ @SuppressFBWarnings(
+ value = "DMI_HARDCODED_ABSOLUTE_FILENAME",
+ justification =
+ "The public JWKS projection is intentionally fixed to Account's read-only validator-consumed mount.")
+ private static Path publicJwksMount() {
+ return Path.of("/var/run/secrets/firemud/jwks");
+ }
+
+ private final AccountJwtReadinessProbeRepository repository;
+ private final TransactionTemplate accountTransaction;
+ private final Clock clock;
+ private final AccountJwtValidatorInventorySource inventorySource;
+ private final Path privateMount;
+ private final Path privateBundle;
+ private final Path publicMount;
+ private final Path publicJwks;
+
+ public AccountJwtReadinessProbeService(
+ AccountJwtReadinessProbeRepository repository,
+ TransactionTemplate accountTransaction,
+ Clock clock) {
+ this(
+ repository,
+ accountTransaction,
+ clock,
+ PRIVATE_MOUNT,
+ PRIVATE_PENDING_BUNDLE,
+ PUBLIC_MOUNT,
+ PUBLIC_JWKS);
+ }
+
+ AccountJwtReadinessProbeService(
+ AccountJwtReadinessProbeRepository repository,
+ TransactionTemplate accountTransaction,
+ Clock clock,
+ Path privateMount,
+ Path privateBundle,
+ Path publicMount,
+ Path publicJwks) {
+ this(
+ repository,
+ accountTransaction,
+ clock,
+ privateMount,
+ privateBundle,
+ publicMount,
+ publicJwks,
+ null);
+ }
+
+ public AccountJwtReadinessProbeService(
+ AccountJwtReadinessProbeRepository repository,
+ TransactionTemplate accountTransaction,
+ Clock clock,
+ AccountJwtValidatorInventorySource inventorySource) {
+ this(
+ repository,
+ accountTransaction,
+ clock,
+ PRIVATE_MOUNT,
+ PRIVATE_PENDING_BUNDLE,
+ PUBLIC_MOUNT,
+ PUBLIC_JWKS,
+ Objects.requireNonNull(inventorySource));
+ }
+
+ private AccountJwtReadinessProbeService(
+ AccountJwtReadinessProbeRepository repository,
+ TransactionTemplate accountTransaction,
+ Clock clock,
+ Path privateMount,
+ Path privateBundle,
+ Path publicMount,
+ Path publicJwks,
+ AccountJwtValidatorInventorySource inventorySource) {
+ this.repository = Objects.requireNonNull(repository);
+ this.accountTransaction = Objects.requireNonNull(accountTransaction);
+ this.clock = Objects.requireNonNull(clock);
+ this.privateMount = Objects.requireNonNull(privateMount);
+ this.privateBundle = Objects.requireNonNull(privateBundle);
+ this.publicMount = Objects.requireNonNull(publicMount);
+ this.publicJwks = Objects.requireNonNull(publicJwks);
+ this.inventorySource = inventorySource;
+ }
+
+ /** Plans the current Account-selected generation operation; no signing occurs in this method. */
+ public ReadinessProbePlan planCurrent(Binding binding, TrustFence trust) {
+ if (inventorySource == null) {
+ return inTransaction(
+ () -> repository.planCurrent(binding, trust, Instant.ofEpochSecond(nowEpochSecond())));
+ }
+ ObservationContext observationContext =
+ inTransaction(() -> repository.readCurrentInventoryObservationContext(binding, trust));
+ AccountJwtValidatorInventorySource.InventorySnapshot snapshot =
+ inventorySource.observe(observationContext);
+ return inTransaction(
+ () ->
+ repository.planCurrent(
+ binding, trust, Instant.ofEpochSecond(nowEpochSecond()), snapshot));
+ }
+
+ /** Rereads protected live inventory before opening the exact receiver target-read transaction. */
+ public List readCurrentExpectedPods(
+ Binding binding, TrustFence trust, ProbeEntry entry) {
+ AccountJwtValidatorInventorySource.InventorySnapshot snapshot =
+ observeCurrentInventory(binding, trust, entry.rotationOperationId());
+ return inTransaction(() -> repository.readCurrentExpectedPods(binding, trust, entry, snapshot));
+ }
+
+ /**
+ * Reads one exact V2 receiver owner row after observing protected Kubernetes inventory outside
+ * the short SQL transaction.
+ */
+ public OwnerProbeEvidence readCurrentProbeOwner(
+ Binding binding,
+ TrustFence trust,
+ AccountJwtReadinessProbeOwnerSelector selector,
+ String authenticatedWorkloadNamespace) {
+ AccountJwtValidatorInventorySource.InventorySnapshot snapshot =
+ observeCurrentInventory(binding, trust, selector.rotationOperationId());
+ if (!snapshot.namespace().equals(authenticatedWorkloadNamespace)) {
+ throw new AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException();
+ }
+ return inTransaction(
+ () ->
+ repository.readCurrentProbeOwner(
+ binding, trust, selector, snapshot, authenticatedWorkloadNamespace));
+ }
+
+ /** Rereads protected live inventory before committing one immutable per-Pod receipt. */
+ public ProbeEntry recordPodAcceptance(
+ Binding binding,
+ TrustFence trust,
+ ProbeEntry entry,
+ ExpectedPod expectedPod,
+ AuthenticatedAcceptance acceptance) {
+ AccountJwtValidatorInventorySource.InventorySnapshot snapshot =
+ observeCurrentInventory(binding, trust, entry.rotationOperationId());
+ return inTransaction(
+ () ->
+ repository.recordPodAcceptance(
+ binding, trust, entry, expectedPod, acceptance, snapshot));
+ }
+
+ /**
+ * Fresh owner observation for promotion callers; never performs I/O while SQL rows are locked.
+ */
+ public AccountJwtValidatorInventorySource.InventorySnapshot observeCurrentInventory() {
+ if (inventorySource == null) {
+ throw new AccountJwtValidatorInventorySource.InventoryUnavailableException();
+ }
+ return inventorySource.observe();
+ }
+
+ /** Reads only an owner-derived current V2 operation context for the Pod-local receiver proof. */
+ ObservationContext readCurrentInventoryObservationContext(Binding binding, TrustFence trust) {
+ return inTransaction(() -> repository.readCurrentInventoryObservationContext(binding, trust));
+ }
+
+ /** Reads only an owner-derived current V2 operation context for the Pod-local receiver proof. */
+ ObservationContext readCurrentInventoryObservationContext(
+ Binding binding, TrustFence trust, UUID operationId) {
+ return inTransaction(
+ () -> repository.readCurrentInventoryObservationContext(binding, trust, operationId));
+ }
+
+ private AccountJwtValidatorInventorySource.InventorySnapshot observeCurrentInventory(
+ Binding binding, TrustFence trust, UUID operationId) {
+ if (inventorySource == null) {
+ throw new AccountJwtValidatorInventorySource.InventoryUnavailableException();
+ }
+ ObservationContext observationContext =
+ readCurrentInventoryObservationContext(binding, trust, operationId);
+ return inventorySource.observe(observationContext);
+ }
+
+ /** Reads the exact durable operation and latest receipt state without creating evidence. */
+ ReadinessProbePlan readCurrentPlan(Binding binding, TrustFence trust, UUID operationId) {
+ return inTransaction(() -> repository.readCurrentPlan(binding, trust, operationId));
+ }
+
+ /**
+ * Delivers each exact current planned probe once. The compact-token hash and ISSUED transition
+ * are durably read back before transient delivery, so an authenticated validator can consume the
+ * current entry synchronously. A persisted signing-attempt hash without ISSUED is ambiguous and
+ * causes same-operation quarantine rather than token remint or replay.
+ */
+ List issueCurrentPlan(
+ Binding binding,
+ TrustFence trust,
+ UUID operationId,
+ DeliveryClaim claim,
+ OwnerInternalProbeDelivery delivery) {
+ ReadinessProbePlan plan =
+ inTransaction(() -> repository.readCurrentPlan(binding, trust, operationId));
+ if (nowEpochSecond() < plan.notBeforeEpochSecond()) {
+ throw new AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException();
+ }
+ if (nowEpochSecond() >= plan.expiresAtEpochSecond()) {
+ return expireAndClean(binding, trust, operationId);
+ }
+ Objects.requireNonNull(claim, "Persisted one-shot delivery claim is required");
+ Objects.requireNonNull(delivery, "Per-invocation internal delivery is required");
+ DeliveryClaim persistedClaim =
+ inTransaction(
+ () ->
+ repository.requireCurrentDeliveryClaim(
+ binding, trust, plan, claim, Instant.ofEpochSecond(nowEpochSecond())));
+ if (persistedClaim == null || !persistedClaim.equals(claim)) {
+ throw new AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException();
+ }
+ List output = new ArrayList<>();
+ for (ProbeEntry planned : plan.entries()) {
+ ProbeEntry current = currentEntry(binding, trust, operationId, planned);
+ if (current.state() == ProbeState.ISSUED) {
+ output.add(current);
+ continue;
+ }
+ if (current.state() == ProbeState.PLANNED && current.compactTokenSha256().isPresent()) {
+ output.addAll(quarantineCurrent(binding, trust, operationId));
+ break;
+ }
+ if (current.state() != ProbeState.PLANNED) {
+ output.add(current);
+ continue;
+ }
+
+ long now = nowEpochSecond();
+ if (now < current.plannedIssuedAtEpochSecond()) {
+ throw new AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException();
+ }
+ if (now >= current.expiresAtEpochSecond()) {
+ output.addAll(expireAndClean(binding, trust, operationId));
+ break;
+ }
+
+ ExpectedIdentity identity =
+ new ExpectedIdentity(
+ binding.environmentId(),
+ binding.clusterId(),
+ binding.namespace(),
+ operationId.toString(),
+ current.targetGeneration(),
+ current.targetKid(),
+ plan.targetPublicKeyFingerprint());
+ ReadinessProbeSigningSpec spec =
+ new ReadinessProbeSigningSpec(
+ current.validatorId(),
+ current.probeKind(),
+ current.tokenProfile(),
+ current.audience(),
+ current.jti(),
+ current.targetGeneration(),
+ current.targetKid(),
+ current.plannedIssuedAtEpochSecond(),
+ current.expiresAtEpochSecond());
+
+ SignedProbeDigest signed;
+ try {
+ signed =
+ AccountMountedJwtSignerBundle.signReadinessProbeDigest(
+ privateMount,
+ privateBundle,
+ publicMount,
+ publicJwks,
+ identity,
+ spec,
+ (digest, exactCompactJwt) -> {
+ try {
+ pinBeforeDelivery(binding, trust, digest);
+ ProbeEntry issued =
+ inTransaction(
+ () ->
+ repository.recordIssued(
+ binding,
+ trust,
+ digest,
+ Instant.ofEpochSecond(nowEpochSecond())));
+ DeliveryMetadata metadata = DeliveryMetadata.from(plan, issued, digest);
+ delivery.deliver(metadata, exactCompactJwt);
+ if (!sha256(exactCompactJwt).equals(metadata.compactTokenSha256())) {
+ throw new IllegalStateException(
+ "Transient readiness probe bytes changed in delivery");
+ }
+ } catch (RuntimeException ignored) {
+ abortAfterDeliveryFailure(binding, trust, operationId);
+ throw new DeliveryQuarantinedException();
+ }
+ });
+ } catch (DeliveryQuarantinedException ex) {
+ throw ex;
+ }
+ try {
+ ProbeEntry delivered = currentEntry(binding, trust, operationId, current);
+ if (!exactSignedReadback(plan, current, delivered, signed)
+ || (delivered.state() != ProbeState.ISSUED
+ && delivered.state() != ProbeState.VERIFIED)) {
+ throw new IllegalStateException("Readiness delivery result did not read back exactly");
+ }
+ output.add(delivered);
+ } catch (RuntimeException ignored) {
+ abortAfterDeliveryFailure(binding, trust, operationId);
+ throw new DeliveryQuarantinedException();
+ }
+ }
+ return List.copyOf(output);
+ }
+
+ /** Aborts only the named current operation and retains hashes/evidence. */
+ public List abortCurrentPlan(Binding binding, TrustFence trust, UUID operationId) {
+ return quarantineCurrent(binding, trust, operationId);
+ }
+
+ /** Expires due entries and performs bounded cleanup for only the named operation. */
+ public List expireAndClean(Binding binding, TrustFence trust, UUID operationId) {
+ return inTransaction(
+ () -> {
+ repository.expireCurrent(
+ binding, trust, operationId, Instant.ofEpochSecond(nowEpochSecond()));
+ return repository.cleanTerminalEntries(
+ operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION);
+ });
+ }
+
+ /** Bounded terminal cleanup never scans outside this explicit operation ID. */
+ public List cleanTerminalEntries(UUID operationId) {
+ return inTransaction(
+ () ->
+ repository.cleanTerminalEntries(
+ operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION));
+ }
+
+ private void pinBeforeDelivery(Binding binding, TrustFence trust, SignedProbeDigest digest) {
+ try {
+ inTransaction(
+ () ->
+ repository.recordSigningAttempt(
+ binding, trust, digest, Instant.ofEpochSecond(nowEpochSecond())));
+ } catch (RuntimeException failure) {
+ throw new SigningAttemptConflict();
+ }
+ }
+
+ private void abortAfterDeliveryFailure(Binding binding, TrustFence trust, UUID operationId) {
+ try {
+ quarantineCurrent(binding, trust, operationId);
+ } catch (RuntimeException ignored) {
+ // The durable pre-delivery hash remains a quarantine marker for same-operation recovery.
+ }
+ }
+
+ private static boolean exactSignedReadback(
+ ReadinessProbePlan plan, ProbeEntry expected, ProbeEntry readback, SignedProbeDigest signed) {
+ long issuedEntryVersion = expected.entryVersion() + 2L;
+ long resultEntryVersion =
+ readback.state() == ProbeState.VERIFIED ? issuedEntryVersion + 1L : issuedEntryVersion;
+ return readback.rotationOperationId().equals(plan.operationId())
+ && readback.planDigest().equals(plan.planDigest())
+ && expected.planDigest().equals(plan.planDigest())
+ && signed.operationId().equals(plan.operationId().toString())
+ && readback.jti().equals(expected.jti())
+ && signed.jti().equals(expected.jti())
+ && readback.validatorId().equals(expected.validatorId())
+ && signed.validatorId().equals(expected.validatorId())
+ && readback.tokenProfile().equals(expected.tokenProfile())
+ && signed.tokenProfile().equals(expected.tokenProfile())
+ && readback.audience().equals(expected.audience())
+ && signed.audience().equals(expected.audience())
+ && readback.probeKind() == expected.probeKind()
+ && signed.probeKind() == expected.probeKind()
+ && readback.targetGeneration().equals(plan.targetGeneration())
+ && signed.targetGeneration().equals(plan.targetGeneration())
+ && readback.targetKid().equals(plan.targetKid())
+ && signed.targetKid().equals(plan.targetKid())
+ && signed.publicKeyFingerprint().equals(plan.targetPublicKeyFingerprint())
+ && readback.plannedIssuedAtEpochSecond() == signed.issuedAtEpochSecond()
+ && readback.expiresAtEpochSecond() == signed.expiresAtEpochSecond()
+ && readback.signingAttemptedAtEpochSecond().isPresent()
+ && readback.entryVersion() == resultEntryVersion
+ && (readback.state() != ProbeState.VERIFIED
+ || readback
+ .verificationReceipt()
+ .filter(
+ receipt ->
+ receipt.sourceEntryVersion() == issuedEntryVersion
+ && receipt.resultEntryVersion() == resultEntryVersion)
+ .isPresent())
+ && readback.compactTokenSha256().equals(java.util.Optional.of(signed.compactTokenSha256()));
+ }
+
+ private List quarantineCurrent(Binding binding, TrustFence trust, UUID operationId) {
+ return inTransaction(
+ () -> {
+ repository.abortCurrent(
+ binding, trust, operationId, Instant.ofEpochSecond(nowEpochSecond()));
+ return repository.cleanTerminalEntries(
+ operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION);
+ });
+ }
+
+ private ProbeEntry currentEntry(
+ Binding binding, TrustFence trust, UUID operationId, ProbeEntry expected) {
+ ReadinessProbePlan plan =
+ inTransaction(() -> repository.readCurrentPlan(binding, trust, operationId));
+ return plan.entries().stream()
+ .filter(entry -> entry.jti().equals(expected.jti()))
+ .findFirst()
+ .orElseThrow(
+ () ->
+ new AccountJwtReadinessProbeRepository.QuarantinedStateException(
+ "Readiness probe entry disappeared from its immutable plan"));
+ }
+
+ private long nowEpochSecond() {
+ long value = clock.instant().getEpochSecond();
+ if (value <= 0L) {
+ throw new IllegalStateException("Readiness producer clock is invalid");
+ }
+ return value;
+ }
+
+ private static String sha256(byte[] bytes) {
+ try {
+ return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
+ } catch (NoSuchAlgorithmException ex) {
+ throw new IllegalStateException("SHA-256 is unavailable");
+ }
+ }
+
+ private T inTransaction(java.util.function.Supplier operation) {
+ return accountTransaction.execute(status -> operation.get());
+ }
+
+ /**
+ * Per-invocation owner-internal sink. This is not a Spring component contract or an authority
+ * input; callback success is not validation evidence. Only an exact owner readback of a receipt
+ * independently recorded by the authenticated validator is.
+ */
+ @FunctionalInterface
+ interface OwnerInternalProbeDelivery {
+ void deliver(DeliveryMetadata metadata, byte[] exactCompactJwt);
+ }
+
+ /** Non-secret operation identity passed alongside the transient probe bytes. */
+ public record DeliveryMetadata(
+ UUID operationId,
+ String planDigest,
+ int planVersion,
+ String validatorId,
+ String tokenProfile,
+ String audience,
+ ProbeKind probeKind,
+ UUID jti,
+ String targetGeneration,
+ String targetKid,
+ Optional expectedActiveGeneration,
+ Optional expectedActiveKid,
+ int registryVersion,
+ long entryVersion,
+ long issuedAtEpochSecond,
+ long expiresAtEpochSecond,
+ String compactTokenSha256) {
+ private static DeliveryMetadata from(
+ ReadinessProbePlan plan, ProbeEntry entry, SignedProbeDigest digest) {
+ return new DeliveryMetadata(
+ plan.operationId(),
+ plan.planDigest(),
+ plan.planVersion(),
+ entry.validatorId(),
+ entry.tokenProfile(),
+ entry.audience(),
+ entry.probeKind(),
+ entry.jti(),
+ entry.targetGeneration(),
+ entry.targetKid(),
+ entry.expectedActive().map(value -> value.generation()),
+ entry.expectedActive().map(value -> value.kid()),
+ entry.registryVersion(),
+ entry.entryVersion(),
+ entry.plannedIssuedAtEpochSecond(),
+ entry.expiresAtEpochSecond(),
+ digest.compactTokenSha256());
+ }
+ }
+
+ private static final class SigningAttemptConflict extends IllegalStateException {
+ private SigningAttemptConflict() {
+ super("Readiness signing attempt could not be durably pinned");
+ }
+ }
+
+ private static final class DeliveryQuarantinedException extends IllegalStateException {
+ private DeliveryQuarantinedException() {
+ super("Readiness probe delivery was ambiguous; the operation was quarantined");
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java
new file mode 100644
index 0000000000..4e5ab7a257
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java
@@ -0,0 +1,1122 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding;
+import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding.Binding;
+import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ReadinessPromotionProof;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionObservation;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.ActiveJwksPromotionReceipt;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CommittedSignerEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.DesiredState;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.EnrollmentIdentity;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationPhase;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedGenerationEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PreparedPromotion;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionObservation;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PrivatePromotionReceipt;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionOperationEvidence;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.PromotionPreparation;
+import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.BindingIdentity;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.CasObservation;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient.ConfigMapSnapshot;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.InventorySnapshot;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationContext;
+import net.firedevops.firemud.accountservice.service.session.AccountJwtValidatorInventorySource.ObservationPurpose;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.transaction.support.TransactionTemplate;
+
+/**
+ * Explicit Account-owned enrollment and durable-generation reconciliation for interim JWT signer
+ * materialization.
+ *
+ * This coordinator is not scheduled or run at application startup. Enrollment derives only from
+ * Account's protected materializer binding, protected JWKS API binding, and a live observation of
+ * the fixed public ConfigMap. Enrollment initializes the short Account state row without selecting
+ * a generation request. Durable-generation reconciliation reads only an already selected request.
+ * Those two bootstrap paths do not commit signer promotion or treat mounted correspondence as
+ * validator readiness; the separate prepared-promotion path below requires the private receipt and
+ * complete current readiness evidence before it owns the public ACTIVE CAS and durable commit.
+ */
+public final class AccountJwtSignerBootstrapCoordinator {
+ private static final String JWKS_DATA_KEY = AccountJwtJwksPublicationRepository.JWKS_DATA_KEY;
+
+ private final AccountJwtSignerMaterializerTrustBinding materializerTrustBinding;
+ private final AccountJwtJwksConfigMapClient configMapClient;
+ private final AccountJwtSignerDesiredStateRepository desiredStateRepository;
+ private final AccountJwtJwksPrepublicationService prepublicationService;
+ private final AccountJwtReadinessProbeRepository readinessRepository;
+ private final ObjectProvider inventorySourceProvider;
+ private final TransactionTemplate accountTransaction;
+
+ public AccountJwtSignerBootstrapCoordinator(
+ AccountJwtSignerMaterializerTrustBinding materializerTrustBinding,
+ AccountJwtJwksConfigMapClient configMapClient,
+ AccountJwtSignerDesiredStateRepository desiredStateRepository,
+ AccountJwtJwksPrepublicationService prepublicationService,
+ TransactionTemplate accountTransaction) {
+ this(
+ materializerTrustBinding,
+ configMapClient,
+ desiredStateRepository,
+ prepublicationService,
+ null,
+ null,
+ accountTransaction);
+ }
+
+ @SuppressFBWarnings(
+ value = "EI_EXPOSE_REP2",
+ justification =
+ "The Account readiness repository is a live Spring owner used for transactional proof reads.")
+ public AccountJwtSignerBootstrapCoordinator(
+ AccountJwtSignerMaterializerTrustBinding materializerTrustBinding,
+ AccountJwtJwksConfigMapClient configMapClient,
+ AccountJwtSignerDesiredStateRepository desiredStateRepository,
+ AccountJwtJwksPrepublicationService prepublicationService,
+ AccountJwtReadinessProbeRepository readinessRepository,
+ ObjectProvider inventorySourceProvider,
+ TransactionTemplate accountTransaction) {
+ this.materializerTrustBinding =
+ Objects.requireNonNull(
+ materializerTrustBinding, "Protected materializer trust is required");
+ this.configMapClient =
+ Objects.requireNonNull(configMapClient, "Protected JWKS client is required");
+ this.desiredStateRepository =
+ Objects.requireNonNull(desiredStateRepository, "Account signer repository is required");
+ this.prepublicationService =
+ Objects.requireNonNull(prepublicationService, "Account prepublication owner is required");
+ this.readinessRepository = readinessRepository;
+ this.inventorySourceProvider = inventorySourceProvider;
+ this.accountTransaction =
+ Objects.requireNonNull(accountTransaction, "Account transaction template is required");
+ this.accountTransaction.setReadOnly(false);
+ }
+
+ /**
+ * Performs only the authenticated, finite enrollment step. It does not select a generation
+ * request, advance a signer phase, publish JWKS, or inspect mounted private material.
+ */
+ public EnrollmentAcknowledgement enrollOnce() {
+ EnrollmentSources sources = captureEnrollmentSources();
+ DesiredState initialized = initializeEnrollment(sources);
+ EnrollmentIdentity enrolled =
+ initialized
+ .enrollmentIdentity()
+ .orElseThrow(
+ () -> new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS));
+ return acknowledgement(sources.materializerBinding(), sources.apiIdentity(), enrolled);
+ }
+
+ /**
+ * Reconciles publication and mounted correspondence for the exact current generated receipt. The
+ * authenticated RPC owner calls this only after its short generation-read transaction has
+ * returned {@code GENERATION_RECORDED}; this method never creates a new operation.
+ */
+ public BootstrapProgress reconcileCurrentGenerationOnce(UUID expectedOperationId) {
+ Objects.requireNonNull(expectedOperationId, "Expected generation operation is required");
+ EnrollmentSources sources = captureEnrollmentSources();
+ GenerationRequest request = readCurrentGenerationRequest(sources);
+ if (!expectedOperationId.equals(request.operationId())
+ || request.phase() != GenerationPhase.GENERATION_RECORDED) {
+ throw new BootstrapOperationException(FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH);
+ }
+ return reconcileSelectedGeneration(sources, request);
+ }
+
+ /**
+ * Enters PREPARED only for the exact current durable generation after refreshed publication,
+ * mounted correspondence, and owner-verified live validator closure. The materializer's
+ * authenticated promotion-request RPC is the only production caller. All API, filesystem, and
+ * Kubernetes reads finish before the short Account transaction that obtains the private proof and
+ * performs the owner CAS.
+ */
+ public Optional prepareCurrentPromotionOnce() {
+ if (readinessRepository == null || inventorySourceProvider == null) {
+ throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE);
+ }
+ EnrollmentSources sources = captureEnrollmentSources();
+ DesiredState enrolled = readEnrollmentState(sources);
+ if (enrolled.generationOperationId().isEmpty()) {
+ requireUnselectedInitialEnrollment(enrolled, sources);
+ requireUnchangedProtectedBindings(sources);
+ return Optional.empty();
+ }
+ GenerationRequest request = readCurrentGenerationRequest(sources);
+ if (request.phase() != GenerationPhase.GENERATION_RECORDED) {
+ if (request.phase() == GenerationPhase.OBSERVE_PRIVATE_SECRET
+ || request.phase() == GenerationPhase.GENERATE_PENDING) {
+ requireUnchangedProtectedBindings(sources);
+ return Optional.empty();
+ }
+ throw new BootstrapOperationException(FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH);
+ }
+
+ BootstrapProgress refreshed = reconcileSelectedGeneration(sources, request);
+ if (refreshed.stage() != Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE
+ || !refreshed.publicKeyPrepublished()
+ || !refreshed.mountedKeyCorrespondence()) {
+ return Optional.empty();
+ }
+
+ InventorySnapshot liveInventory = observeCurrentValidatorInventory(sources, request);
+ requireUnchangedProtectedBindings(sources);
+ PreparedPromotion prepared =
+ accountTransaction.execute(
+ status -> {
+ requireUnchangedProtectedBindings(sources);
+ var proof =
+ readinessRepository.readCurrentPromotionPrerequisites(
+ sources.materializerBinding().accountBinding(),
+ trustFence(sources.materializerBinding()),
+ request.operationId(),
+ liveInventory);
+ if (proof.isEmpty()) {
+ return null;
+ }
+ ReadinessPromotionProof verifiedProof = proof.orElseThrow();
+ DesiredState state =
+ desiredStateRepository.read(sources.materializerBinding().accountBinding());
+ EnrollmentIdentity enrollment =
+ state
+ .enrollmentIdentity()
+ .orElseThrow(
+ () ->
+ new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS));
+ var publication = verifiedProof.publication();
+ PromotionPreparation preparation =
+ new PromotionPreparation(
+ verifiedProof.generationResult().operationId(),
+ verifiedProof.generationResult(),
+ enrollment,
+ publication.intent().apiBindingDigest(),
+ publication.intent().apiConfigRevision(),
+ publication.intent().configMapUid(),
+ publication.receipt().observedResourceVersion(),
+ publication.intent().intentDigest(),
+ publication.receipt().receiptDigest(),
+ publication.mountedCorrespondence().observationDigest(),
+ verifiedProof.plan().planDigest(),
+ verifiedProof.readinessEvidenceDigest(),
+ publication.intent().jwksJson());
+ PreparedPromotion persisted =
+ desiredStateRepository.prepareCurrentGeneration(
+ sources.materializerBinding().accountBinding(),
+ trustFence(sources.materializerBinding()),
+ preparation,
+ verifiedProof);
+ PreparedGenerationEvidence readback =
+ desiredStateRepository.readPreparedGenerationForRecovery(
+ sources.materializerBinding().accountBinding(),
+ trustFence(sources.materializerBinding()));
+ if (!readback.promotion().operationId().equals(persisted.operationId())
+ || !readback.promotion().requestDigest().equals(persisted.requestDigest())
+ || !readback.promotion().generationOperationId().equals(request.operationId())
+ || !readback.generationResult().equals(verifiedProof.generationResult())
+ || !"PREPARED".equals(persisted.status())) {
+ throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS);
+ }
+ requireUnchangedProtectedBindings(sources);
+ return persisted;
+ });
+ if (prepared == null) {
+ return Optional.empty();
+ }
+ requireUnchangedProtectedBindings(sources);
+ return Optional.of(prepared);
+ }
+
+ /**
+ * Completes only the exact Account PREPARED operation whose authenticated private-slot receipt
+ * has already been recorded. Account owns the public ConfigMap ACTIVE CAS and terminal durable
+ * commit; this finite call is never started at boot or by a scheduler.
+ */
+ public void reconcilePreparedPromotionOnce(
+ PrivatePromotionObservation observation, PrivatePromotionReceipt expectedReceipt) {
+ Objects.requireNonNull(observation, "Exact private promotion observation is required");
+ Objects.requireNonNull(expectedReceipt, "Durable private promotion receipt is required");
+ Binding binding = currentMaterializerBinding();
+ BindingIdentity apiIdentity = currentApiIdentity();
+ requireMatchingProtectedPins(binding, apiIdentity);
+ requireReceiptIdentity(observation, expectedReceipt);
+
+ PromotionOwnerSnapshot start =
+ readPromotionOwnerSnapshot(binding, apiIdentity, observation, expectedReceipt);
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+ if (!expectedReceipt.equals(start.privateReceipt())) {
+ throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException(
+ "Account private promotion receipt changed during reconciliation");
+ }
+ if (start.committedEvidence() != null) {
+ return;
+ }
+ if (readinessRepository == null) {
+ throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE);
+ }
+
+ PreparedGenerationEvidence prepared = start.preparedEvidence();
+ PromotionOperationEvidence promotion = prepared.promotion();
+ ObservationContext context = observationContext(promotion);
+ InventorySnapshot beforeInventory = observePreparedInventory(context);
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+
+ ConfigMapSnapshot observedConfigMap =
+ prepublicationService.observePreparedCurrentKeyCorrespondence(promotion);
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+
+ readPreparedPromotionProof(
+ binding, apiIdentity, observation, expectedReceipt, promotion, beforeInventory);
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+ requireExpectedPublicSnapshot(promotion, observedConfigMap);
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+
+ CasObservation activeReadback =
+ configMapClient.publishActiveProjection(
+ observedConfigMap,
+ promotion.expectedPublicResourceVersion(),
+ java.util.Map.of(
+ JWKS_DATA_KEY,
+ promotion.expectedPublicJwksJson(),
+ AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY,
+ promotion.expectedActiveMarkerJson()));
+ requireExactActiveReadback(promotion, activeReadback);
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+
+ ActiveJwksPromotionObservation activeObservation =
+ new ActiveJwksPromotionObservation(
+ activeReadback.uid(),
+ activeReadback.priorResourceVersion(),
+ activeReadback.resourceVersion(),
+ promotion.expectedPublicJwksJson(),
+ promotion.expectedActiveMarkerJson());
+ ActiveJwksPromotionReceipt activeReceipt =
+ accountTransaction.execute(
+ status -> {
+ PrivatePromotionReceipt currentPrivateReceipt =
+ desiredStateRepository.recordPrivatePromotionResult(
+ binding.accountBinding(), trustFence(binding), observation);
+ if (!expectedReceipt.equals(currentPrivateReceipt)) {
+ throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException(
+ "Original private promotion receipt changed before ACTIVE readback recording");
+ }
+ return desiredStateRepository.recordActiveJwksPromotionResult(
+ binding.accountBinding(), trustFence(binding), activeObservation);
+ });
+ if (activeReceipt == null) {
+ throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException(
+ "Account ACTIVE JWKS receipt is unavailable");
+ }
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+ if (!activeReceipt.promotionOperationId().equals(promotion.operationId())
+ || !activeReceipt.configMapUid().equals(promotion.publicConfigMapUid())
+ || !activeReceipt.priorResourceVersion().equals(promotion.expectedPublicResourceVersion())
+ || !activeReceipt.observedResourceVersion().equals(activeReadback.resourceVersion())
+ || !activeReceipt
+ .publicDataDigest()
+ .equals(
+ AccountJwtJwksPublicationRepository.publicDataDigest(
+ promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson()))) {
+ throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException(
+ "Account ACTIVE JWKS receipt did not match its exact CAS readback");
+ }
+
+ PreparedGenerationEvidence afterActiveReceipt =
+ accountTransaction.execute(
+ status ->
+ desiredStateRepository.readPreparedGenerationForRecovery(
+ binding.accountBinding(), trustFence(binding)));
+ if (afterActiveReceipt == null) {
+ throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException(
+ "Prepared Account promotion evidence is unavailable after ACTIVE readback");
+ }
+ PromotionOperationEvidence promotionWithActiveReceipt = afterActiveReceipt.promotion();
+ requirePromotionIdentity(promotion, promotionWithActiveReceipt, observation, expectedReceipt);
+ if (!promotionWithActiveReceipt
+ .activeJwksReceiptDigest()
+ .equals(Optional.of(activeReceipt.receiptDigest()))
+ || !promotionWithActiveReceipt
+ .activeJwksPublicDataDigest()
+ .equals(Optional.of(activeReceipt.publicDataDigest()))
+ || !promotionWithActiveReceipt
+ .activeJwksObservedResourceVersion()
+ .equals(Optional.of(activeReceipt.observedResourceVersion()))) {
+ throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException(
+ "Account ACTIVE JWKS receipt is not bound to the current PREPARED operation");
+ }
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+
+ InventorySnapshot beforeCommitInventory = observePreparedInventory(context);
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+ prepublicationService.observePreparedCurrentKeyCorrespondence(promotionWithActiveReceipt);
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+ CommittedSignerEvidence committed =
+ commitPreparedPromotion(
+ binding,
+ apiIdentity,
+ observation,
+ expectedReceipt,
+ promotionWithActiveReceipt,
+ beforeCommitInventory);
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+ if (committed == null
+ || !promotion.operationId().equals(committed.promotion().operationId())
+ || !"COMMITTED".equals(committed.promotion().status())) {
+ throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException(
+ "Account ACTIVE signer commit did not read back exactly");
+ }
+ // The final commit obtains a separate readiness proof from the independent post-CAS inventory
+ // observation.
+ }
+
+ private PromotionOwnerSnapshot readPromotionOwnerSnapshot(
+ Binding binding,
+ BindingIdentity apiIdentity,
+ PrivatePromotionObservation observation,
+ PrivatePromotionReceipt expectedReceipt) {
+ TrustFence trust = trustFence(binding);
+ PromotionOwnerSnapshot snapshot =
+ accountTransaction.execute(
+ status -> {
+ PrivatePromotionReceipt receipt =
+ desiredStateRepository.recordPrivatePromotionResult(
+ binding.accountBinding(), trust, observation);
+ if (!expectedReceipt.equals(receipt)) {
+ throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException(
+ "Private promotion receipt changed before Account reconciliation");
+ }
+ try {
+ PreparedGenerationEvidence prepared =
+ desiredStateRepository.readPreparedGenerationForRecovery(
+ binding.accountBinding(), trust);
+ requirePreparedReceipt(prepared, observation, receipt);
+ return new PromotionOwnerSnapshot(prepared, null, receipt);
+ } catch (AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException done) {
+ CommittedSignerEvidence committed =
+ desiredStateRepository
+ .readCurrentCommittedSigner(
+ binding.accountBinding(),
+ trust,
+ apiIdentity.bindingDigest(),
+ apiIdentity.configRevision())
+ .orElseThrow(
+ () ->
+ new AccountJwtSignerDesiredStateRepository
+ .PromotionPrerequisitesIncompleteException(
+ "Private promotion is neither PREPARED nor currently committed"));
+ if (!committed.privateReceipt().equals(receipt)
+ || !committed
+ .promotion()
+ .operationId()
+ .equals(observation.promotionOperationId())) {
+ throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException(
+ "Committed private promotion retry differs from Account evidence");
+ }
+ return new PromotionOwnerSnapshot(null, committed, receipt);
+ }
+ });
+ if (snapshot == null) {
+ throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException(
+ "Account signer promotion evidence is unavailable");
+ }
+ return snapshot;
+ }
+
+ private ReadinessPromotionProof readPreparedPromotionProof(
+ Binding binding,
+ BindingIdentity apiIdentity,
+ PrivatePromotionObservation observation,
+ PrivatePromotionReceipt expectedReceipt,
+ PromotionOperationEvidence expectedPromotion,
+ InventorySnapshot liveInventory) {
+ TrustFence trust = trustFence(binding);
+ ReadinessPromotionProof proof =
+ accountTransaction.execute(
+ status -> {
+ PrivatePromotionReceipt receipt =
+ desiredStateRepository.recordPrivatePromotionResult(
+ binding.accountBinding(), trust, observation);
+ if (!expectedReceipt.equals(receipt)) {
+ throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException(
+ "Private promotion receipt changed before ACTIVE publication");
+ }
+ PreparedGenerationEvidence current =
+ desiredStateRepository.readPreparedGenerationForRecovery(
+ binding.accountBinding(), trust);
+ requireSamePreparedPromotion(current, expectedPromotion, observation, receipt);
+ return readinessRepository
+ .readPromotionProof(
+ binding.accountBinding(),
+ trust,
+ expectedPromotion.generationOperationId(),
+ liveInventory)
+ .orElseThrow(
+ () ->
+ new AccountJwtSignerDesiredStateRepository
+ .PromotionPrerequisitesIncompleteException(
+ "Fresh complete Account readiness proof is unavailable"));
+ });
+ if (proof == null) {
+ throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException(
+ "Account readiness proof is unavailable");
+ }
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+ return proof;
+ }
+
+ private CommittedSignerEvidence commitPreparedPromotion(
+ Binding binding,
+ BindingIdentity apiIdentity,
+ PrivatePromotionObservation observation,
+ PrivatePromotionReceipt expectedReceipt,
+ PromotionOperationEvidence expectedPromotion,
+ InventorySnapshot liveInventory) {
+ TrustFence trust = trustFence(binding);
+ CommittedSignerEvidence committed =
+ accountTransaction.execute(
+ status -> {
+ PrivatePromotionReceipt receipt =
+ desiredStateRepository.recordPrivatePromotionResult(
+ binding.accountBinding(), trust, observation);
+ if (!expectedReceipt.equals(receipt)) {
+ throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException(
+ "Original private promotion observation no longer matches Account evidence");
+ }
+ PreparedGenerationEvidence current =
+ desiredStateRepository.readPreparedGenerationForRecovery(
+ binding.accountBinding(), trust);
+ requireSamePreparedPromotion(current, expectedPromotion, observation, receipt);
+ ReadinessPromotionProof proof =
+ readinessRepository
+ .readPromotionProof(
+ binding.accountBinding(),
+ trust,
+ expectedPromotion.generationOperationId(),
+ liveInventory)
+ .orElseThrow(
+ () ->
+ new AccountJwtSignerDesiredStateRepository
+ .PromotionPrerequisitesIncompleteException(
+ "Post-CAS complete Account readiness proof is unavailable"));
+ return desiredStateRepository.commitPreparedPromotion(
+ binding.accountBinding(), trust, expectedPromotion.operationId(), proof);
+ });
+ if (committed == null) {
+ throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException(
+ "Account signer promotion commit is unavailable");
+ }
+ requireUnchangedProtectedBindings(binding, apiIdentity);
+ return committed;
+ }
+
+ private InventorySnapshot observePreparedInventory(ObservationContext context) {
+ if (inventorySourceProvider == null) {
+ throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE);
+ }
+ AccountJwtValidatorInventorySource source = inventorySourceProvider.getIfAvailable();
+ if (source == null) {
+ throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE);
+ }
+ try {
+ return source.observe(context);
+ } catch (RuntimeException unavailableOrAmbiguous) {
+ throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE);
+ }
+ }
+
+ private static ObservationContext observationContext(PromotionOperationEvidence promotion) {
+ if (!promotion.expectedPreviousActive().equals(promotion.expectedPublishedActive())) {
+ throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException(
+ "Prepared Account active signer fence is inconsistent");
+ }
+ return new ObservationContext(
+ promotion.expectedPreviousActive().isEmpty()
+ ? ObservationPurpose.INITIAL_NO_ACTIVE_SIGNER_CANDIDATES
+ : ObservationPurpose.STRICT_READY,
+ promotion.generationOperationId(),
+ promotion.generationOperationDigest());
+ }
+
+ private static void requireReceiptIdentity(
+ PrivatePromotionObservation observation, PrivatePromotionReceipt receipt) {
+ if (!observation.promotionOperationId().equals(receipt.promotionOperationId())
+ || !observation.generationOperationId().equals(receipt.generationOperationId())
+ || !observation.observedResourceVersion().equals(receipt.observedResourceVersion())) {
+ throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException(
+ "Private promotion result does not match the exact Account receipt");
+ }
+ }
+
+ private static void requirePreparedReceipt(
+ PreparedGenerationEvidence prepared,
+ PrivatePromotionObservation observation,
+ PrivatePromotionReceipt receipt) {
+ requireSamePreparedPromotion(prepared, prepared.promotion(), observation, receipt);
+ }
+
+ private static void requireSamePreparedPromotion(
+ PreparedGenerationEvidence prepared,
+ PromotionOperationEvidence expected,
+ PrivatePromotionObservation observation,
+ PrivatePromotionReceipt receipt) {
+ PromotionOperationEvidence current = prepared.promotion();
+ if (!current.equals(expected)
+ || !current.operationId().equals(observation.promotionOperationId())
+ || !current.generationOperationId().equals(observation.generationOperationId())
+ || !current.generationOperationDigest().equals(observation.generationOperationDigest())
+ || !current.requestDigest().equals(observation.promotionRequestDigest())
+ || !current.privatePromotionDispatched()
+ || !current.privatePromotionReceiptDigest().equals(Optional.of(receipt.receiptDigest()))) {
+ throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException(
+ "Private promotion receipt does not match the exact current PREPARED operation");
+ }
+ }
+
+ private static void requirePromotionIdentity(
+ PromotionOperationEvidence expected,
+ PromotionOperationEvidence current,
+ PrivatePromotionObservation observation,
+ PrivatePromotionReceipt receipt) {
+ if (!current.operationId().equals(expected.operationId())
+ || !current.requestDigest().equals(expected.requestDigest())
+ || current.expectedRecordVersion() != expected.expectedRecordVersion()
+ || !current.binding().equals(expected.binding())
+ || !current.expectedPreviousActive().equals(expected.expectedPreviousActive())
+ || !current
+ .expectedPreviousPublicKeyFingerprint()
+ .equals(expected.expectedPreviousPublicKeyFingerprint())
+ || !current.expectedPublishedActive().equals(expected.expectedPublishedActive())
+ || !current.targetAlgorithm().equals(expected.targetAlgorithm())
+ || !current.trustFence().equals(expected.trustFence())
+ || !current.generationOperationId().equals(expected.generationOperationId())
+ || !current.generationOperationDigest().equals(expected.generationOperationDigest())
+ || !current.generationReceiptDigest().equals(expected.generationReceiptDigest())
+ || !current.targetGeneration().equals(expected.targetGeneration())
+ || !current.targetKid().equals(expected.targetKid())
+ || !current.targetPublicKeyFingerprint().equals(expected.targetPublicKeyFingerprint())
+ || !current.secretUid().equals(expected.secretUid())
+ || !current
+ .expectedPrivateResourceVersion()
+ .equals(expected.expectedPrivateResourceVersion())
+ || !current.apiBindingDigest().equals(expected.apiBindingDigest())
+ || !current.apiConfigRevision().equals(expected.apiConfigRevision())
+ || !current.publicConfigMapUid().equals(expected.publicConfigMapUid())
+ || !current.expectedPublicResourceVersion().equals(expected.expectedPublicResourceVersion())
+ || !current.prepublicationIntentDigest().equals(expected.prepublicationIntentDigest())
+ || !current.prepublicationReceiptDigest().equals(expected.prepublicationReceiptDigest())
+ || !current.mountedObservationDigest().equals(expected.mountedObservationDigest())
+ || !current.readinessPlanDigest().equals(expected.readinessPlanDigest())
+ || !current.readinessEvidenceDigest().equals(expected.readinessEvidenceDigest())
+ || !current.expectedPublicJwksJson().equals(expected.expectedPublicJwksJson())
+ || !current.expectedActiveMarkerJson().equals(expected.expectedActiveMarkerJson())
+ || !"PREPARED".equals(current.status())
+ || !current.operationId().equals(observation.promotionOperationId())
+ || !current.generationOperationId().equals(observation.generationOperationId())
+ || !current.privatePromotionDispatched()
+ || !current.privatePromotionReceiptDigest().equals(Optional.of(receipt.receiptDigest()))) {
+ throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException(
+ "Account PREPARED operation changed during ACTIVE publication");
+ }
+ }
+
+ private static void requireExpectedPublicSnapshot(
+ PromotionOperationEvidence promotion, ConfigMapSnapshot snapshot) {
+ String marker =
+ snapshot.data().get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY);
+ boolean active = promotion.expectedActiveMarkerJson().equals(marker);
+ if (!promotion.publicConfigMapUid().equals(snapshot.uid())
+ || !promotion.expectedPublicJwksJson().equals(snapshot.data().get(JWKS_DATA_KEY))
+ || (!promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion())
+ && !active)
+ || (promotion.expectedPublicResourceVersion().equals(snapshot.resourceVersion())
+ && active)) {
+ throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException(
+ "Account public ConfigMap changed before its exact ACTIVE CAS");
+ }
+ }
+
+ private static void requireExactActiveReadback(
+ PromotionOperationEvidence promotion, CasObservation observation) {
+ if (!promotion.publicConfigMapUid().equals(observation.uid())
+ || !promotion.expectedPublicResourceVersion().equals(observation.priorResourceVersion())
+ || !promotion
+ .expectedPublicJwksJson()
+ .equals(observation.publishedData().get(JWKS_DATA_KEY))
+ || !promotion
+ .expectedActiveMarkerJson()
+ .equals(
+ observation
+ .publishedData()
+ .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY))
+ || !promotion.expectedPublicJwksJson().equals(observation.readbackData().get(JWKS_DATA_KEY))
+ || !promotion
+ .expectedActiveMarkerJson()
+ .equals(
+ observation
+ .readbackData()
+ .get(AccountJwtJwksPublicationRepository.GENERATION_MARKER_DATA_KEY))
+ || promotion.expectedPublicResourceVersion().equals(observation.resourceVersion())) {
+ throw new AccountJwtSignerDesiredStateRepository.QuarantinedStateException(
+ "Account ACTIVE ConfigMap CAS did not return its exact immutable readback");
+ }
+ }
+
+ private InventorySnapshot observeCurrentValidatorInventory(
+ EnrollmentSources sources, GenerationRequest request) {
+ try {
+ AccountJwtValidatorInventorySource source = inventorySourceProvider.getIfAvailable();
+ if (source == null) {
+ throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE);
+ }
+ ObservationContext context =
+ accountTransaction.execute(
+ status -> {
+ requireUnchangedProtectedBindings(sources);
+ ObservationContext selected =
+ readinessRepository.readCurrentInventoryObservationContext(
+ sources.materializerBinding().accountBinding(),
+ trustFence(sources.materializerBinding()),
+ request.operationId());
+ requireUnchangedProtectedBindings(sources);
+ return selected;
+ });
+ if (context == null) {
+ throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE);
+ }
+ return source.observe(context);
+ } catch (BootstrapOperationException failure) {
+ throw failure;
+ } catch (RuntimeException unavailableOrAmbiguous) {
+ throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE);
+ }
+ }
+
+ private BootstrapProgress reconcileSelectedGeneration(
+ EnrollmentSources sources, GenerationRequest request) {
+ try {
+ AccountJwtJwksPublicationRepository.PublicationReceipt publication =
+ prepublicationService.prepublishCurrentGeneration();
+ requireUnchangedProtectedBindings(sources);
+ if (!request.operationId().equals(publication.operationId())) {
+ return progress(
+ Stage.PREPUBLICATION_BLOCKED,
+ request,
+ false,
+ false,
+ FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH);
+ }
+ } catch (BootstrapOperationException failure) {
+ throw failure;
+ } catch (RuntimeException ambiguousOrRejected) {
+ return progress(
+ Stage.PREPUBLICATION_BLOCKED,
+ request,
+ false,
+ false,
+ FailureCode.ACCOUNT_PREPUBLICATION_UNAVAILABLE);
+ }
+
+ try {
+ AccountJwtJwksPublicationRepository.MountObservation mount =
+ prepublicationService.observeCurrentMountedCorrespondence();
+ requireUnchangedProtectedBindings(sources);
+ if (!request.operationId().equals(mount.operationId())) {
+ return progress(
+ Stage.MOUNT_CORRESPONDENCE_BLOCKED,
+ request,
+ true,
+ false,
+ FailureCode.ACCOUNT_OWNER_OPERATION_MISMATCH);
+ }
+ } catch (BootstrapOperationException failure) {
+ throw failure;
+ } catch (RuntimeException unavailableOrRejected) {
+ return progress(
+ Stage.MOUNT_CORRESPONDENCE_BLOCKED,
+ request,
+ true,
+ false,
+ FailureCode.ACCOUNT_MOUNT_CORRESPONDENCE_UNAVAILABLE);
+ }
+
+ return progress(
+ Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE,
+ request,
+ true,
+ true,
+ FailureCode.VALIDATOR_ACCEPTANCE_INCOMPLETE);
+ }
+
+ private DesiredState initializeEnrollment(EnrollmentSources sources) {
+ AccountJwtSignerDesiredStateRepository.Binding accountBinding =
+ sources.materializerBinding().accountBinding();
+ try {
+ DesiredState initialized =
+ accountTransaction.execute(
+ status -> {
+ requireUnchangedProtectedBindings(sources);
+ DesiredState persisted =
+ desiredStateRepository.initialize(accountBinding, sources.enrollmentIdentity());
+ requireUnchangedProtectedBindings(sources);
+ return persisted;
+ });
+ if (initialized == null) {
+ throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS);
+ }
+ requireUnchangedProtectedBindings(sources);
+ return initialized;
+ } catch (BootstrapOperationException failure) {
+ throw failure;
+ } catch (RuntimeException unavailableOrAmbiguous) {
+ throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS);
+ }
+ }
+
+ private DesiredState readEnrollmentState(EnrollmentSources sources) {
+ AccountJwtSignerDesiredStateRepository.Binding accountBinding =
+ sources.materializerBinding().accountBinding();
+ try {
+ Optional state =
+ accountTransaction.execute(
+ status -> {
+ requireUnchangedProtectedBindings(sources);
+ Optional current =
+ desiredStateRepository.readEnrollmentState(accountBinding);
+ requireUnchangedProtectedBindings(sources);
+ return current;
+ });
+ if (state == null || state.isEmpty()) {
+ throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS);
+ }
+ DesiredState current = state.orElseThrow();
+ EnrollmentIdentity enrollment =
+ current
+ .enrollmentIdentity()
+ .orElseThrow(
+ () -> new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS));
+ if (!enrollment.sameStablePins(sources.enrollmentIdentity())) {
+ throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_MISMATCH);
+ }
+ requireUnchangedProtectedBindings(sources);
+ return current;
+ } catch (BootstrapOperationException failure) {
+ throw failure;
+ } catch (RuntimeException unavailableOrAmbiguous) {
+ throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS);
+ }
+ }
+
+ private static void requireUnselectedInitialEnrollment(
+ DesiredState state, EnrollmentSources sources) {
+ if (state.recordVersion() != 1
+ || state.durableActive().isPresent()
+ || state.publishedActive().isPresent()
+ || state.preparedOperationId().isPresent()
+ || state.generationOperationId().isPresent()
+ || state.enrollmentIdentity().isEmpty()
+ || !state.enrollmentIdentity().orElseThrow().sameStablePins(sources.enrollmentIdentity())) {
+ throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS);
+ }
+ }
+
+ private GenerationRequest readCurrentGenerationRequest(EnrollmentSources sources) {
+ AccountJwtSignerDesiredStateRepository.Binding accountBinding =
+ sources.materializerBinding().accountBinding();
+ TrustFence trustFence = trustFence(sources.materializerBinding());
+ try {
+ GenerationRequest request =
+ accountTransaction.execute(
+ status -> {
+ requireUnchangedProtectedBindings(sources);
+ GenerationRequest current =
+ desiredStateRepository.readCurrentGenerationRequest(accountBinding, trustFence);
+ requireUnchangedProtectedBindings(sources);
+ return current;
+ });
+ if (request == null) {
+ throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS);
+ }
+ requireUnchangedProtectedBindings(sources);
+ return request;
+ } catch (BootstrapOperationException failure) {
+ throw failure;
+ } catch (RuntimeException unavailableOrAmbiguous) {
+ throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS);
+ }
+ }
+
+ private static EnrollmentAcknowledgement acknowledgement(
+ Binding materializer,
+ AccountJwtJwksConfigMapClient.BindingIdentity api,
+ EnrollmentIdentity enrollment) {
+ return new EnrollmentAcknowledgement(
+ materializer.environmentId(),
+ materializer.clusterId(),
+ materializer.namespace(),
+ enrollment.expectedClusterIncarnationUid(),
+ enrollment.expectedNamespaceUid(),
+ enrollment.materializerTrustBindingDigest(),
+ enrollment.materializerTrustConfigRevision(),
+ enrollment.apiBindingDigest(),
+ enrollment.apiConfigRevision(),
+ api.apiServerUrl(),
+ api.tlsServerName(),
+ api.servingCaSha256(),
+ api.expectedApiUsername(),
+ AccountJwtSignerDesiredStateRepository.PRIVATE_SECRET_NAME,
+ AccountJwtSignerDesiredStateRepository.PUBLIC_JWKS_CONFIG_MAP_NAME,
+ enrollment.publicConfigMapUid(),
+ enrollment.publicConfigMapResourceVersion(),
+ enrollment.publicConfigMapSnapshotDigest());
+ }
+
+ private EnrollmentSources captureEnrollmentSources() {
+ Binding materializerBefore = currentMaterializerBinding();
+ AccountJwtJwksConfigMapClient.BindingIdentity apiBefore = currentApiIdentity();
+ requireMatchingProtectedPins(materializerBefore, apiBefore);
+
+ AccountJwtJwksConfigMapClient.ConfigMapSnapshot publicConfigMap;
+ try {
+ publicConfigMap = Objects.requireNonNull(configMapClient.observe());
+ } catch (RuntimeException unavailableOrAmbiguous) {
+ throw new BootstrapOperationException(FailureCode.PUBLIC_CONFIG_MAP_UNAVAILABLE);
+ }
+
+ Binding materializerAfter = currentMaterializerBinding();
+ AccountJwtJwksConfigMapClient.BindingIdentity apiAfter = currentApiIdentity();
+ if (!materializerBefore.equals(materializerAfter) || !apiBefore.equals(apiAfter)) {
+ throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_CHANGED);
+ }
+ requireMatchingProtectedPins(materializerAfter, apiAfter);
+ String initialJwks = publicConfigMap.data().get(JWKS_DATA_KEY);
+ if (initialJwks == null || initialJwks.isBlank()) {
+ throw new BootstrapOperationException(FailureCode.PUBLIC_CONFIG_MAP_INCOMPLETE);
+ }
+
+ try {
+ EnrollmentIdentity enrollment =
+ new EnrollmentIdentity(
+ materializerAfter.expectedClusterIncarnationUid(),
+ materializerAfter.expectedNamespaceUid(),
+ materializerAfter.bindingDigest(),
+ materializerAfter.configRevision(),
+ apiAfter.bindingDigest(),
+ apiAfter.configRevision(),
+ publicConfigMap.uid(),
+ publicConfigMap.resourceVersion(),
+ AccountJwtJwksPublicationRepository.snapshotDigest(publicConfigMap.data()));
+ return new EnrollmentSources(materializerAfter, apiAfter, enrollment);
+ } catch (RuntimeException malformedSource) {
+ throw new BootstrapOperationException(FailureCode.PUBLIC_CONFIG_MAP_INCOMPLETE);
+ }
+ }
+
+ private Binding currentMaterializerBinding() {
+ try {
+ return materializerTrustBinding
+ .current()
+ .orElseThrow(
+ () -> new BootstrapOperationException(FailureCode.PROTECTED_BINDING_UNAVAILABLE));
+ } catch (BootstrapOperationException failure) {
+ throw failure;
+ } catch (RuntimeException unavailable) {
+ throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_UNAVAILABLE);
+ }
+ }
+
+ private AccountJwtJwksConfigMapClient.BindingIdentity currentApiIdentity() {
+ try {
+ return Objects.requireNonNull(configMapClient.identity());
+ } catch (RuntimeException unavailable) {
+ throw new BootstrapOperationException(FailureCode.PROTECTED_API_BINDING_UNAVAILABLE);
+ }
+ }
+
+ private void requireUnchangedProtectedBindings(EnrollmentSources sources) {
+ Binding currentMaterializer = currentMaterializerBinding();
+ AccountJwtJwksConfigMapClient.BindingIdentity currentApi = currentApiIdentity();
+ if (!sources.materializerBinding().equals(currentMaterializer)
+ || !sources.apiIdentity().equals(currentApi)) {
+ throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_CHANGED);
+ }
+ requireMatchingProtectedPins(currentMaterializer, currentApi);
+ }
+
+ private void requireUnchangedProtectedBindings(
+ Binding expectedMaterializer, BindingIdentity expectedApiIdentity) {
+ Binding currentMaterializer = currentMaterializerBinding();
+ BindingIdentity currentApi = currentApiIdentity();
+ if (!expectedMaterializer.equals(currentMaterializer)
+ || !expectedApiIdentity.equals(currentApi)) {
+ throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_CHANGED);
+ }
+ requireMatchingProtectedPins(currentMaterializer, currentApi);
+ }
+
+ private static void requireMatchingProtectedPins(
+ Binding materializer, AccountJwtJwksConfigMapClient.BindingIdentity api) {
+ if (!materializer.environmentId().equals(api.environmentId())
+ || !materializer.clusterId().equals(api.clusterId())
+ || !materializer.namespace().equals(api.namespace())
+ || !materializer.expectedClusterIncarnationUid().equals(api.expectedClusterIncarnationUid())
+ || !materializer.expectedNamespaceUid().equals(api.expectedNamespaceUid())) {
+ throw new BootstrapOperationException(FailureCode.PROTECTED_BINDING_MISMATCH);
+ }
+ }
+
+ private static TrustFence trustFence(Binding binding) {
+ return new TrustFence(
+ binding.expectedClusterIncarnationUid(),
+ binding.expectedNamespaceUid(),
+ binding.bindingDigest(),
+ binding.configRevision());
+ }
+
+ private static BootstrapProgress progress(
+ Stage stage,
+ GenerationRequest request,
+ boolean prepublished,
+ boolean mountedCorrespondence,
+ FailureCode failure) {
+ boolean validatorAcceptanceComplete = false;
+ List blockers = List.of(failure);
+ if (stage == Stage.BLOCKED_FOR_VALIDATOR_ACCEPTANCE) {
+ blockers =
+ List.of(
+ FailureCode.VALIDATOR_ACCEPTANCE_INCOMPLETE,
+ FailureCode.SIGNER_PROMOTION_NOT_ATTEMPTED);
+ }
+ return new BootstrapProgress(
+ stage,
+ EnrollmentSource.PROTECTED_BINDINGS_AND_LIVE_FIXED_JWKS_CONFIG_MAP,
+ true,
+ true,
+ request.operationId(),
+ request.phase(),
+ request.targetGeneration(),
+ request.targetKid(),
+ request.phase() == GenerationPhase.GENERATION_RECORDED,
+ prepublished,
+ mountedCorrespondence,
+ AccountJwtReadinessProbeRepository.INVENTORY_STATUS,
+ validatorAcceptanceComplete,
+ false,
+ false,
+ blockers);
+ }
+
+ private record EnrollmentSources(
+ Binding materializerBinding,
+ AccountJwtJwksConfigMapClient.BindingIdentity apiIdentity,
+ EnrollmentIdentity enrollmentIdentity) {}
+
+ private record PromotionOwnerSnapshot(
+ PreparedGenerationEvidence preparedEvidence,
+ CommittedSignerEvidence committedEvidence,
+ PrivatePromotionReceipt privateReceipt) {}
+
+ /** Closed, non-secret identity acknowledgment for one idempotent durable enrollment. */
+ public record EnrollmentAcknowledgement(
+ String environmentId,
+ String clusterId,
+ String namespace,
+ String expectedClusterIncarnationUid,
+ String expectedNamespaceUid,
+ String materializerTrustBindingDigest,
+ String materializerTrustConfigRevision,
+ String apiBindingDigest,
+ String apiConfigRevision,
+ String apiServerUrl,
+ String apiTlsServerName,
+ String apiServingCaSha256,
+ String apiExpectedUsername,
+ String privateSecretName,
+ String publicConfigMapName,
+ String publicConfigMapUid,
+ String publicConfigMapResourceVersion,
+ String publicConfigMapSnapshotDigest) {}
+
+ public enum Stage {
+ PREPUBLICATION_BLOCKED,
+ MOUNT_CORRESPONDENCE_BLOCKED,
+ BLOCKED_FOR_VALIDATOR_ACCEPTANCE
+ }
+
+ public enum EnrollmentSource {
+ PROTECTED_BINDINGS_AND_LIVE_FIXED_JWKS_CONFIG_MAP
+ }
+
+ /** Non-secret progress; `false` readiness fields are deliberate until fleet proof exists. */
+ public record BootstrapProgress(
+ Stage stage,
+ EnrollmentSource enrollmentSource,
+ boolean enrollmentInitialized,
+ boolean generationRequestSelected,
+ UUID operationId,
+ GenerationPhase generationPhase,
+ String targetGeneration,
+ String targetKid,
+ boolean generationReadbackComplete,
+ boolean publicKeyPrepublished,
+ boolean mountedKeyCorrespondence,
+ String validatorInventoryStatus,
+ boolean validatorAcceptanceComplete,
+ boolean signerPromotionCommitted,
+ boolean issuanceReady,
+ List blockers) {
+ public BootstrapProgress {
+ Objects.requireNonNull(stage);
+ Objects.requireNonNull(enrollmentSource);
+ Objects.requireNonNull(operationId);
+ Objects.requireNonNull(generationPhase);
+ Objects.requireNonNull(targetGeneration);
+ Objects.requireNonNull(targetKid);
+ Objects.requireNonNull(validatorInventoryStatus);
+ blockers = List.copyOf(blockers);
+ if (validatorAcceptanceComplete || signerPromotionCommitted || issuanceReady) {
+ throw new IllegalArgumentException(
+ "Signer bootstrap progress cannot claim validator acceptance, promotion, or readiness");
+ }
+ if (!enrollmentInitialized || !generationRequestSelected) {
+ throw new IllegalArgumentException(
+ "Signer bootstrap progress requires completed Account enrollment and request selection");
+ }
+ }
+ }
+
+ public enum FailureCode {
+ PROTECTED_BINDING_UNAVAILABLE,
+ PROTECTED_API_BINDING_UNAVAILABLE,
+ PROTECTED_BINDING_MISMATCH,
+ PROTECTED_BINDING_CHANGED,
+ PUBLIC_CONFIG_MAP_UNAVAILABLE,
+ PUBLIC_CONFIG_MAP_INCOMPLETE,
+ SIGNER_PROMOTION_NOT_ATTEMPTED,
+ ACCOUNT_STATE_AMBIGUOUS,
+ ACCOUNT_OWNER_OPERATION_MISMATCH,
+ ACCOUNT_PREPUBLICATION_UNAVAILABLE,
+ ACCOUNT_MOUNT_CORRESPONDENCE_UNAVAILABLE,
+ VALIDATOR_INVENTORY_UNAVAILABLE,
+ VALIDATOR_ACCEPTANCE_INCOMPLETE
+ }
+
+ public static final class BootstrapOperationException extends IllegalStateException {
+ private final FailureCode failureCode;
+
+ public BootstrapOperationException(FailureCode failureCode) {
+ super("Account JWT signer bootstrap is quarantined: " + failureCode);
+ this.failureCode = Objects.requireNonNull(failureCode);
+ }
+
+ public FailureCode failureCode() {
+ return failureCode;
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java
new file mode 100644
index 0000000000..1772d03532
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyring.java
@@ -0,0 +1,221 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Objects;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationReferenceFingerprint.ReferenceKind;
+
+/**
+ * Explicit Account-owned active/retained key snapshot for operator-reference fingerprints.
+ *
+ * This class has no key source implementation, default key, or provisioning behavior. The caller
+ * supplies an owner-controlled source and an explicit post-expiry reconciliation window; every
+ * fingerprint operation reloads that source and fails closed for a missing, withdrawn, or
+ * insufficiently retained key.
+ */
+public final class AccountOperatorAuthorizationFingerprintKeyring {
+ private static final int MAX_RETAINED_KEYS = 8;
+ private static final Pattern FINGERPRINT =
+ Pattern.compile("arfp/v1/([A-Za-z0-9_-]{1,64})/([0-9a-f]{64})");
+ private static final String HMAC_ALGORITHM = "HmacSHA256";
+
+ private final OwnerKeySource source;
+ private final Clock clock;
+ private final Duration requiredPostExpiryRetention;
+
+ public AccountOperatorAuthorizationFingerprintKeyring(
+ OwnerKeySource source, Clock clock, Duration requiredPostExpiryRetention) {
+ this.source = Objects.requireNonNull(source, "explicit Account operator key source required");
+ this.clock = Objects.requireNonNull(clock, "clock is required");
+ this.requiredPostExpiryRetention =
+ Objects.requireNonNull(requiredPostExpiryRetention, "retention policy is required");
+ if (requiredPostExpiryRetention.isNegative() || requiredPostExpiryRetention.isZero()) {
+ throw new IllegalArgumentException("Explicit positive reconciliation retention is required");
+ }
+ }
+
+ /** Computes a new issuance fingerprint only with the currently declared active key. */
+ public String fingerprintForIssue(ReferenceKind referenceKind, byte[] exactReferenceBytes) {
+ Objects.requireNonNull(referenceKind, "reference kind is required");
+ Snapshot current = requireSnapshot();
+ return current.activeKey().calculator().fingerprint(referenceKind, exactReferenceBytes);
+ }
+
+ /**
+ * Recomputes the original fingerprint using its exact stored key ID and verifies the supplied
+ * value in constant time. Retired keys must remain available past both immutable expiries and the
+ * explicitly configured reconciliation window.
+ */
+ public boolean matchesOriginal(
+ ReferenceKind referenceKind,
+ byte[] exactReferenceBytes,
+ String originalFingerprint,
+ Instant referenceExpiresAt,
+ Instant responseEnvelopeExpiresAt) {
+ Objects.requireNonNull(referenceKind, "reference kind is required");
+ Objects.requireNonNull(referenceExpiresAt, "reference expiry is required");
+ Objects.requireNonNull(responseEnvelopeExpiresAt, "response expiry is required");
+ if (!responseEnvelopeExpiresAt.isAfter(referenceExpiresAt)) {
+ throw new IllegalArgumentException("Original response expiry must follow reference expiry");
+ }
+ Matcher matcher = originalFingerprint == null ? null : FINGERPRINT.matcher(originalFingerprint);
+ if (matcher == null || !matcher.matches()) {
+ throw new IllegalArgumentException("Original Account reference fingerprint is malformed");
+ }
+
+ Snapshot current = requireSnapshot();
+ String keyId = matcher.group(1);
+ KeyMaterial key = current.keyFor(keyId);
+ if (key == null) {
+ throw new KeyUnavailableException();
+ }
+ if (key != current.activeKey()) {
+ Instant now = clock.instant();
+ if (!now.isBefore(key.retainedUntil())) {
+ throw new KeyUnavailableException();
+ }
+ Instant requiredUntil;
+ try {
+ requiredUntil = responseEnvelopeExpiresAt.plus(requiredPostExpiryRetention);
+ } catch (RuntimeException invalidHorizon) {
+ throw new KeyUnavailableException();
+ }
+ if (!key.retainedUntil().isAfter(requiredUntil)) {
+ throw new KeyUnavailableException();
+ }
+ }
+ String actual = key.calculator().fingerprint(referenceKind, exactReferenceBytes);
+ return MessageDigest.isEqual(
+ actual.getBytes(StandardCharsets.US_ASCII),
+ originalFingerprint.getBytes(StandardCharsets.US_ASCII));
+ }
+
+ private Snapshot requireSnapshot() {
+ try {
+ return Objects.requireNonNull(source.readCurrent(), "owner key snapshot is required");
+ } catch (KeyUnavailableException unavailable) {
+ throw unavailable;
+ } catch (RuntimeException unavailable) {
+ throw new KeyUnavailableException();
+ }
+ }
+
+ @FunctionalInterface
+ public interface OwnerKeySource {
+ /** Reads the owner-controlled active and retained key snapshot afresh for this operation. */
+ Snapshot readCurrent();
+ }
+
+ /** One active key and at most eight explicitly retained prior keys. */
+ public record Snapshot(KeyMaterial activeKey, List retainedKeys) {
+ public Snapshot {
+ Objects.requireNonNull(activeKey, "one active Account operator key is required");
+ if (activeKey.retainedUntil() != null) {
+ throw new IllegalArgumentException("Active Account operator key cannot be marked retained");
+ }
+ retainedKeys =
+ List.copyOf(Objects.requireNonNull(retainedKeys, "retained keys are required"));
+ if (retainedKeys.size() > MAX_RETAINED_KEYS) {
+ throw new IllegalArgumentException("Retained Account operator keys exceed their bound");
+ }
+ Set keyIds = new HashSet<>();
+ if (!keyIds.add(activeKey.keyId())) {
+ throw new IllegalArgumentException("Active Account operator key ID is duplicated");
+ }
+ for (KeyMaterial retained : retainedKeys) {
+ Objects.requireNonNull(retained, "retained Account operator key is required");
+ if (retained.retainedUntil() == null || !keyIds.add(retained.keyId())) {
+ throw new IllegalArgumentException("Retained Account operator key is malformed");
+ }
+ }
+ }
+
+ private KeyMaterial keyFor(String keyId) {
+ if (activeKey.keyId().equals(keyId)) {
+ return activeKey;
+ }
+ return retainedKeys.stream()
+ .filter(value -> value.keyId().equals(keyId))
+ .findFirst()
+ .orElse(null);
+ }
+
+ @Override
+ public String toString() {
+ return "AccountOperatorAuthorizationFingerprintKeyring.Snapshot[key material redacted]";
+ }
+ }
+
+ /** Secret material remains private; only its bounded identifier is exposed. */
+ public static final class KeyMaterial {
+ private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}");
+
+ private final String keyId;
+ private final AccountOperatorAuthorizationReferenceFingerprint calculator;
+ private final Instant retainedUntil;
+
+ public KeyMaterial(String keyId, SecretKey secretKey) {
+ this(keyId, secretKey, null);
+ }
+
+ public KeyMaterial(String keyId, SecretKey secretKey, Instant retainedUntil) {
+ if (keyId == null || !KEY_ID.matcher(keyId).matches()) {
+ throw new IllegalArgumentException("Unsupported Account operator key ID");
+ }
+ Objects.requireNonNull(secretKey, "explicit Account operator key material is required");
+ if (!HMAC_ALGORITHM.equalsIgnoreCase(secretKey.getAlgorithm())) {
+ throw new IllegalArgumentException("Unsupported Account operator key algorithm");
+ }
+ byte[] encoded = secretKey.getEncoded();
+ if (encoded == null || encoded.length == 0 || encoded.length > 4096) {
+ throw new IllegalArgumentException("Unsupported Account operator key material");
+ }
+ byte[] copy = encoded.clone();
+ try {
+ SecretKey immutableCopy = new SecretKeySpec(copy, HMAC_ALGORITHM);
+ calculator = new AccountOperatorAuthorizationReferenceFingerprint(keyId, immutableCopy);
+ } finally {
+ java.util.Arrays.fill(copy, (byte) 0);
+ }
+ if (retainedUntil != null && retainedUntil.toEpochMilli() <= 0L) {
+ throw new IllegalArgumentException("Retained Account operator key expiry is invalid");
+ }
+ this.keyId = keyId;
+ this.retainedUntil = retainedUntil;
+ }
+
+ public String keyId() {
+ return keyId;
+ }
+
+ private AccountOperatorAuthorizationReferenceFingerprint calculator() {
+ return calculator;
+ }
+
+ private Instant retainedUntil() {
+ return retainedUntil;
+ }
+
+ @Override
+ public String toString() {
+ return "AccountOperatorAuthorizationFingerprintKeyring.KeyMaterial[key material redacted]";
+ }
+ }
+
+ /** Fail-closed result for an absent, withdrawn, expired, or insufficiently retained key. */
+ public static final class KeyUnavailableException extends RuntimeException {
+ public KeyUnavailableException() {
+ super("Account operator authorization fingerprint key is unavailable");
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java
new file mode 100644
index 0000000000..588b7bc6b2
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprint.java
@@ -0,0 +1,102 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.util.Arrays;
+import java.util.HexFormat;
+import java.util.Objects;
+import java.util.regex.Pattern;
+import javax.crypto.Mac;
+import javax.crypto.SecretKey;
+import javax.crypto.spec.SecretKeySpec;
+
+/** Account-owned HMAC identity for the exact bytes of an operator authorization reference. */
+public final class AccountOperatorAuthorizationReferenceFingerprint {
+ private static final String HMAC_ALGORITHM = "HmacSHA256";
+ private static final String DOMAIN = "FireMUD/authorizationReferenceFingerprint/v1";
+ private static final String OUTPUT_PREFIX = "arfp/v1/";
+ private static final int MAX_KEY_ID_BYTES = 64;
+ private static final int MAX_KEY_BYTES = 4096;
+ private static final int MAX_REFERENCE_BYTES = 4096;
+ private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}");
+
+ private final String keyId;
+ private final SecretKey key;
+
+ /**
+ * Creates a calculator with an explicitly supplied HMAC key and its bounded public identifier.
+ *
+ * No key is generated, discovered, or loaded implicitly by this class.
+ */
+ public AccountOperatorAuthorizationReferenceFingerprint(String keyId, SecretKey key) {
+ if (keyId == null || keyId.length() > MAX_KEY_ID_BYTES || !KEY_ID.matcher(keyId).matches()) {
+ throw new IllegalArgumentException("Unsupported authorization-reference fingerprint key ID");
+ }
+ if (key == null || !HMAC_ALGORITHM.equalsIgnoreCase(key.getAlgorithm())) {
+ throw new IllegalArgumentException("Unsupported authorization-reference fingerprint key");
+ }
+
+ byte[] encoded = key.getEncoded();
+ if (encoded == null || encoded.length == 0 || encoded.length > MAX_KEY_BYTES) {
+ throw new IllegalArgumentException("Unsupported authorization-reference fingerprint key");
+ }
+
+ byte[] keyCopy = encoded.clone();
+ try {
+ this.key = new SecretKeySpec(keyCopy, HMAC_ALGORITHM);
+ } finally {
+ Arrays.fill(keyCopy, (byte) 0);
+ }
+ this.keyId = keyId;
+ }
+
+ /** Returns the canonical fingerprint for the supplied exact opaque reference bytes. */
+ public String fingerprint(ReferenceKind referenceKind, byte[] referenceBytes) {
+ if (referenceKind == null) {
+ throw new IllegalArgumentException("Unsupported operator authorization-reference kind");
+ }
+ if (referenceBytes == null
+ || referenceBytes.length == 0
+ || referenceBytes.length > MAX_REFERENCE_BYTES) {
+ throw new IllegalArgumentException("Invalid operator authorization-reference bytes");
+ }
+
+ byte[] referenceCopy = referenceBytes.clone();
+ try {
+ Mac mac = Mac.getInstance(HMAC_ALGORITHM);
+ mac.init(key);
+ updateSegment(mac, DOMAIN.getBytes(StandardCharsets.UTF_8));
+ updateSegment(mac, keyId.getBytes(StandardCharsets.UTF_8));
+ updateSegment(mac, referenceKind.wireValue.getBytes(StandardCharsets.UTF_8));
+ updateSegment(mac, referenceCopy);
+ return OUTPUT_PREFIX + keyId + "/" + HexFormat.of().formatHex(mac.doFinal());
+ } catch (GeneralSecurityException exception) {
+ throw new IllegalStateException("HMAC-SHA-256 is unavailable", exception);
+ } finally {
+ Arrays.fill(referenceCopy, (byte) 0);
+ }
+ }
+
+ private static void updateSegment(Mac mac, byte[] value) {
+ byte[] prefix = (Integer.toString(value.length) + ":").getBytes(StandardCharsets.US_ASCII);
+ mac.update(prefix);
+ mac.update(value);
+ }
+
+ @Override
+ public String toString() {
+ return "AccountOperatorAuthorizationReferenceFingerprint";
+ }
+
+ /** The only reference kinds accepted by ADR 0047. */
+ public enum ReferenceKind {
+ HUMAN_OPERATOR("human_operator"),
+ AUTOMATION_OPERATOR("automation_operator");
+
+ private final String wireValue;
+
+ ReferenceKind(String wireValue) {
+ this.wireValue = Objects.requireNonNull(wireValue);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java
new file mode 100644
index 0000000000..7122b4dc2c
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptography.java
@@ -0,0 +1,403 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.security.GeneralSecurityException;
+import java.security.SecureRandom;
+import java.time.Clock;
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.regex.Pattern;
+import javax.crypto.AEADBadTagException;
+import javax.crypto.Cipher;
+import javax.crypto.spec.GCMParameterSpec;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+/** Account-owned AEAD primitive for exact, bounded response-byte recovery. */
+@Component
+public final class AccountResponseEnvelopeCryptography {
+ static final int NONCE_BYTES = 12;
+ static final int TAG_BITS = 128;
+ static final int TAG_BYTES = TAG_BITS / Byte.SIZE;
+ static final int MAX_RESPONSE_BYTES = 64 * 1024;
+ static final int MAX_BINDING_BYTES = 16 * 1024;
+ private static final byte[] MAGIC = {'F', 'R', 'E', 'A'};
+ private static final byte FORMAT_VERSION = 1;
+ private static final int FIXED_HEADER_BYTES = MAGIC.length + 1 + 1 + Long.BYTES + NONCE_BYTES;
+ private static final int MAX_HEADER_BYTES = FIXED_HEADER_BYTES + 32;
+ static final int MAX_ENVELOPE_BYTES = MAX_HEADER_BYTES + MAX_RESPONSE_BYTES + TAG_BYTES;
+ private static final byte[] AAD_DOMAIN =
+ "firemud/account-response-envelope/aad/v1".getBytes(StandardCharsets.US_ASCII);
+ private static final byte[] BINDING_DOMAIN =
+ "firemud/account-response-envelope/binding/v1".getBytes(StandardCharsets.US_ASCII);
+ private static final Pattern SAFE_IDENTIFIER = Pattern.compile("[A-Za-z0-9._:/@+-]{1,256}");
+
+ private final AccountResponseEnvelopeKeyring keyring;
+ private final Clock clock;
+ private final SecureRandom secureRandom;
+
+ @Autowired
+ public AccountResponseEnvelopeCryptography(AccountResponseEnvelopeKeyring keyring) {
+ this(keyring, Clock.systemUTC(), new SecureRandom());
+ }
+
+ AccountResponseEnvelopeCryptography(
+ AccountResponseEnvelopeKeyring keyring, Clock clock, SecureRandom secureRandom) {
+ this.keyring = Objects.requireNonNull(keyring, "keyring");
+ this.clock = Objects.requireNonNull(clock, "clock");
+ this.secureRandom = Objects.requireNonNull(secureRandom, "secureRandom");
+ }
+
+ /** Encrypts exact response bytes under the current active key and immutable operation expiry. */
+ public EncryptedResponseEnvelope encrypt(
+ Binding binding, byte[] exactResponseBytes, Instant immutableRecoveryExpiry) {
+ Objects.requireNonNull(binding, "binding");
+ validateResponse(exactResponseBytes);
+ long expiryMillis = exactEpochMillis(immutableRecoveryExpiry);
+ if (!clock.instant().isBefore(immutableRecoveryExpiry)) {
+ throw new IllegalArgumentException("Recovery expiry must be in the future when sealing");
+ }
+
+ AccountResponseEnvelopeKeyring.KeyEntry active = keyring.readCurrent().activeKey();
+ byte[] nonce = new byte[NONCE_BYTES];
+ secureRandom.nextBytes(nonce);
+ byte[] header = encodeHeader(active.keyId(), expiryMillis, nonce);
+ byte[] bindingBytes = canonicalBinding(binding);
+ try {
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ cipher.init(Cipher.ENCRYPT_MODE, active.secretKey(), new GCMParameterSpec(TAG_BITS, nonce));
+ cipher.updateAAD(associatedData(header, bindingBytes));
+ byte[] ciphertext = cipher.doFinal(exactResponseBytes);
+ if (ciphertext.length != exactResponseBytes.length + TAG_BYTES) {
+ throw new CryptographyUnavailableException();
+ }
+ return new EncryptedResponseEnvelope(concatenate(header, ciphertext));
+ } catch (GeneralSecurityException ex) {
+ throw new CryptographyUnavailableException();
+ }
+ }
+
+ /**
+ * Decrypts only for the exact immutable owner binding and expiry read from the durable operation.
+ * The caller must establish current authorization and postconditions before invoking this method.
+ */
+ public byte[] decrypt(
+ EncryptedResponseEnvelope envelope, Binding expectedBinding, Instant expectedRecoveryExpiry) {
+ Objects.requireNonNull(envelope, "envelope");
+ Objects.requireNonNull(expectedBinding, "expectedBinding");
+ long expectedExpiryMillis = exactEpochMillis(expectedRecoveryExpiry);
+ byte[] encoded = envelope.bytes();
+ Header header = parseHeader(encoded);
+ if (header.expiryMillis() != expectedExpiryMillis) {
+ throw new IntegrityException();
+ }
+ Instant now = clock.instant();
+ if (!now.isBefore(expectedRecoveryExpiry)) {
+ throw new ResponseRecoveryExpiredException();
+ }
+
+ AccountResponseEnvelopeKeyring.KeyEntry key =
+ keyring.readCurrent().decryptionKey(header.keyId(), now);
+ byte[] ciphertext = Arrays.copyOfRange(encoded, header.headerLength(), encoded.length);
+ byte[] bindingBytes = canonicalBinding(expectedBinding);
+ try {
+ Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
+ cipher.init(
+ Cipher.DECRYPT_MODE, key.secretKey(), new GCMParameterSpec(TAG_BITS, header.nonce()));
+ cipher.updateAAD(associatedData(Arrays.copyOf(encoded, header.headerLength()), bindingBytes));
+ return cipher.doFinal(ciphertext);
+ } catch (AEADBadTagException ex) {
+ throw new IntegrityException();
+ } catch (GeneralSecurityException ex) {
+ throw new CryptographyUnavailableException();
+ }
+ }
+
+ private static byte[] encodeHeader(String keyId, long expiryMillis, byte[] nonce) {
+ byte[] keyIdBytes = keyId.getBytes(StandardCharsets.US_ASCII);
+ if (keyIdBytes.length == 0 || keyIdBytes.length > 32 || nonce.length != NONCE_BYTES) {
+ throw new CryptographyUnavailableException();
+ }
+ ByteBuffer header = ByteBuffer.allocate(FIXED_HEADER_BYTES + keyIdBytes.length);
+ header.put(MAGIC);
+ header.put(FORMAT_VERSION);
+ header.put((byte) keyIdBytes.length);
+ header.put(keyIdBytes);
+ header.putLong(expiryMillis);
+ header.put(nonce);
+ return header.array();
+ }
+
+ private static Header parseHeader(byte[] encoded) {
+ if (encoded == null
+ || encoded.length < FIXED_HEADER_BYTES + 1 + TAG_BYTES + 1
+ || encoded.length > MAX_ENVELOPE_BYTES) {
+ throw new IntegrityException();
+ }
+ ByteBuffer input = ByteBuffer.wrap(encoded);
+ byte[] magic = new byte[MAGIC.length];
+ input.get(magic);
+ if (!Arrays.equals(magic, MAGIC) || input.get() != FORMAT_VERSION) {
+ throw new IntegrityException();
+ }
+ int keyIdLength = Byte.toUnsignedInt(input.get());
+ if (keyIdLength < 1
+ || keyIdLength > 32
+ || input.remaining() < keyIdLength + Long.BYTES + NONCE_BYTES + TAG_BYTES + 1) {
+ throw new IntegrityException();
+ }
+ byte[] keyIdBytes = new byte[keyIdLength];
+ input.get(keyIdBytes);
+ for (byte value : keyIdBytes) {
+ if (Byte.toUnsignedInt(value) > 0x7e || Byte.toUnsignedInt(value) < 0x21) {
+ throw new IntegrityException();
+ }
+ }
+ String keyId = new String(keyIdBytes, StandardCharsets.US_ASCII);
+ if (!keyId.matches("[A-Za-z0-9_-]{1,32}")) {
+ throw new IntegrityException();
+ }
+ long expiryMillis = input.getLong();
+ if (expiryMillis <= 0) {
+ throw new IntegrityException();
+ }
+ byte[] nonce = new byte[NONCE_BYTES];
+ input.get(nonce);
+ int ciphertextBytes = input.remaining();
+ if (ciphertextBytes < TAG_BYTES + 1 || ciphertextBytes > MAX_RESPONSE_BYTES + TAG_BYTES) {
+ throw new IntegrityException();
+ }
+ return new Header(keyId, expiryMillis, nonce, input.position());
+ }
+
+ private static byte[] canonicalBinding(Binding binding) {
+ ByteArrayOutputStream bytes = new ByteArrayOutputStream();
+ try (DataOutputStream output = new DataOutputStream(bytes)) {
+ output.write(BINDING_DOMAIN);
+ writeString(output, binding.operation());
+ writeString(output, binding.requestId());
+ writeBytes(output, binding.requestDigest());
+ writeString(output, binding.callerWorkload());
+ writeString(output, binding.bindingId());
+ writeOptionalString(output, binding.lineageId());
+ writeOptionalString(output, binding.replacementId());
+ writeOptionalString(output, binding.leaseId());
+ output.writeLong(binding.issuanceFence());
+ writeBytes(output, binding.authorityTupleCanonicalBytes());
+ writeBytes(output, binding.membershipVersionMapCanonicalBytes());
+ writeBytes(output, binding.authorityEvidenceBundleCanonicalBytes());
+ } catch (IOException ex) {
+ throw new IntegrityException();
+ }
+ byte[] encoded = bytes.toByteArray();
+ if (encoded.length > MAX_BINDING_BYTES) {
+ throw new IllegalArgumentException("Response-envelope binding exceeds its size bound");
+ }
+ return encoded;
+ }
+
+ private static void writeOptionalString(DataOutputStream output, Optional value)
+ throws IOException {
+ output.writeBoolean(value.isPresent());
+ if (value.isPresent()) {
+ writeString(output, value.orElseThrow());
+ }
+ }
+
+ private static void writeString(DataOutputStream output, String value) throws IOException {
+ byte[] encoded = value.getBytes(StandardCharsets.US_ASCII);
+ output.writeInt(encoded.length);
+ output.write(encoded);
+ }
+
+ private static void writeBytes(DataOutputStream output, byte[] value) throws IOException {
+ output.writeInt(value.length);
+ output.write(value);
+ }
+
+ private static byte[] associatedData(byte[] header, byte[] binding) {
+ ByteBuffer aad =
+ ByteBuffer.allocate(AAD_DOMAIN.length + Integer.BYTES * 2 + header.length + binding.length);
+ aad.put(AAD_DOMAIN);
+ aad.putInt(header.length);
+ aad.put(header);
+ aad.putInt(binding.length);
+ aad.put(binding);
+ return aad.array();
+ }
+
+ private static byte[] concatenate(byte[] header, byte[] ciphertext) {
+ if (header.length + ciphertext.length > MAX_ENVELOPE_BYTES) {
+ throw new IllegalArgumentException("Response envelope exceeds its size bound");
+ }
+ byte[] result = Arrays.copyOf(header, header.length + ciphertext.length);
+ System.arraycopy(ciphertext, 0, result, header.length, ciphertext.length);
+ return result;
+ }
+
+ private static void validateResponse(byte[] response) {
+ if (response == null || response.length == 0 || response.length > MAX_RESPONSE_BYTES) {
+ throw new IllegalArgumentException("Response bytes are empty or exceed their size bound");
+ }
+ }
+
+ private static long exactEpochMillis(Instant instant) {
+ Objects.requireNonNull(instant, "immutableRecoveryExpiry");
+ try {
+ long millis = instant.toEpochMilli();
+ if (!Instant.ofEpochMilli(millis).equals(instant) || millis <= 0) {
+ throw new IllegalArgumentException("Recovery expiry must be a positive exact millisecond");
+ }
+ return millis;
+ } catch (ArithmeticException ex) {
+ throw new IllegalArgumentException("Recovery expiry is outside the supported range");
+ }
+ }
+
+ private static void validateIdentifier(String value, String fieldName) {
+ if (value == null || !SAFE_IDENTIFIER.matcher(value).matches()) {
+ throw new IllegalArgumentException(fieldName + " is not a canonical identifier");
+ }
+ }
+
+ private static void validateOptional(Optional value, String fieldName) {
+ Objects.requireNonNull(value, fieldName);
+ value.ifPresent(item -> validateIdentifier(item, fieldName));
+ }
+
+ private record Header(String keyId, long expiryMillis, byte[] nonce, int headerLength) {}
+
+ /**
+ * Immutable, typed operation binding. The owner must derive every field from durable evidence.
+ */
+ public record Binding(
+ String operation,
+ String requestId,
+ byte[] requestDigest,
+ String callerWorkload,
+ String bindingId,
+ Optional lineageId,
+ Optional replacementId,
+ Optional leaseId,
+ long issuanceFence,
+ byte[] authorityTupleCanonicalBytes,
+ byte[] membershipVersionMapCanonicalBytes,
+ byte[] authorityEvidenceBundleCanonicalBytes) {
+ public Binding {
+ validateIdentifier(operation, "operation");
+ validateIdentifier(requestId, "requestId");
+ validateIdentifier(callerWorkload, "callerWorkload");
+ validateIdentifier(bindingId, "bindingId");
+ validateOptional(lineageId, "lineageId");
+ validateOptional(replacementId, "replacementId");
+ validateOptional(leaseId, "leaseId");
+ if (requestDigest == null || requestDigest.length != 32) {
+ throw new IllegalArgumentException("requestDigest must contain exactly 32 bytes");
+ }
+ if (authorityTupleCanonicalBytes == null
+ || authorityTupleCanonicalBytes.length == 0
+ || authorityTupleCanonicalBytes.length > 8 * 1024) {
+ throw new IllegalArgumentException("authority tuple bytes are empty or exceed their bound");
+ }
+ if (membershipVersionMapCanonicalBytes == null
+ || membershipVersionMapCanonicalBytes.length == 0
+ || membershipVersionMapCanonicalBytes.length > 4 * 1024) {
+ throw new IllegalArgumentException(
+ "membership version map bytes are empty or exceed their bound");
+ }
+ if (authorityEvidenceBundleCanonicalBytes == null
+ || authorityEvidenceBundleCanonicalBytes.length == 0
+ || authorityEvidenceBundleCanonicalBytes.length > 8 * 1024) {
+ throw new IllegalArgumentException(
+ "authority evidence bundle bytes are empty or exceed their bound");
+ }
+ if (issuanceFence <= 0) {
+ throw new IllegalArgumentException("issuanceFence must be positive");
+ }
+ requestDigest = requestDigest.clone();
+ authorityTupleCanonicalBytes = authorityTupleCanonicalBytes.clone();
+ membershipVersionMapCanonicalBytes = membershipVersionMapCanonicalBytes.clone();
+ authorityEvidenceBundleCanonicalBytes = authorityEvidenceBundleCanonicalBytes.clone();
+ }
+
+ @Override
+ public byte[] requestDigest() {
+ return requestDigest.clone();
+ }
+
+ @Override
+ public byte[] authorityTupleCanonicalBytes() {
+ return authorityTupleCanonicalBytes.clone();
+ }
+
+ @Override
+ public byte[] membershipVersionMapCanonicalBytes() {
+ return membershipVersionMapCanonicalBytes.clone();
+ }
+
+ @Override
+ public byte[] authorityEvidenceBundleCanonicalBytes() {
+ return authorityEvidenceBundleCanonicalBytes.clone();
+ }
+
+ @Override
+ public String toString() {
+ return "AccountResponseEnvelopeCryptography.Binding[redacted]";
+ }
+ }
+
+ /** Defensively copied opaque ciphertext; no response bytes are exposed through diagnostics. */
+ public record EncryptedResponseEnvelope(byte[] bytes) {
+ public EncryptedResponseEnvelope {
+ if (bytes == null) {
+ throw new IllegalArgumentException("Envelope bytes are required");
+ }
+ bytes = bytes.clone();
+ }
+
+ @Override
+ public byte[] bytes() {
+ return bytes.clone();
+ }
+
+ @Override
+ public String toString() {
+ return "EncryptedResponseEnvelope[redacted]";
+ }
+ }
+
+ /** Integrity/format failure; callers must fail closed and must not expose a token. */
+ public static final class IntegrityException extends RuntimeException {
+ private IntegrityException() {
+ super("Account response envelope failed integrity validation");
+ }
+ }
+
+ /** Maps only the immutable owner-recorded response horizon to the canonical terminal outcome. */
+ public static final class ResponseRecoveryExpiredException extends RuntimeException {
+ private ResponseRecoveryExpiredException() {
+ super("Account response recovery horizon has expired");
+ }
+
+ public String errorCode() {
+ return "RESPONSE_RECOVERY_EXPIRED";
+ }
+ }
+
+ /** Retryable provider/runtime failure, without including secret or response material. */
+ public static final class CryptographyUnavailableException extends RuntimeException {
+ private CryptographyUnavailableException() {
+ super("Account response-envelope cryptography is unavailable");
+ }
+
+ public String errorCode() {
+ return "AUTH_UNAVAILABLE";
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java
new file mode 100644
index 0000000000..ffcb7915a5
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyring.java
@@ -0,0 +1,291 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.SeekableByteChannel;
+import java.nio.charset.CharacterCodingException;
+import java.nio.charset.CodingErrorAction;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+
+/**
+ * Loads Account's separate response-envelope encryption ring from its mounted read-only directory.
+ */
+@Component
+public final class AccountResponseEnvelopeKeyring {
+ static final int KEY_BYTES = 32;
+ static final int MAX_MANIFEST_BYTES = 16 * 1024;
+ static final int MAX_RETIRING_KEYS = 8;
+ private static final String MANIFEST_HEADER = "firemud-account-response-envelope-keyring-v1";
+ private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,32}");
+
+ private final String mountPath;
+
+ @Autowired
+ public AccountResponseEnvelopeKeyring(
+ @Value("${firemud.account.response-envelope.keyring-path:}") String mountPath) {
+ this.mountPath = mountPath == null ? "" : mountPath;
+ }
+
+ /** Reloads on every operation so a withdrawn or unreadable mounted key is never cached. */
+ Snapshot readCurrent() {
+ if (mountPath.isBlank()) {
+ throw new KeyUnavailableException();
+ }
+ try {
+ Path configuredRoot = Path.of(mountPath);
+ if (!configuredRoot.isAbsolute()) {
+ throw new KeyUnavailableException();
+ }
+ Path mountRoot = configuredRoot.toRealPath();
+ if (!Files.isDirectory(mountRoot, LinkOption.NOFOLLOW_LINKS)) {
+ throw new KeyUnavailableException();
+ }
+ // Kubernetes projected Secrets use key -> ..data/key and ..data -> .. symlinks.
+ // Resolve that projection, but do not let its target leave this configured trust root.
+ Path projectedKey = mountRoot.resolve("keyring").toRealPath();
+ if (!projectedKey.startsWith(mountRoot)
+ || !Files.isRegularFile(projectedKey, LinkOption.NOFOLLOW_LINKS)) {
+ throw new KeyUnavailableException();
+ }
+ return parse(readBounded(projectedKey));
+ } catch (KeyUnavailableException ex) {
+ throw ex;
+ } catch (Exception ex) {
+ throw new KeyUnavailableException();
+ }
+ }
+
+ private static byte[] readBounded(Path path) throws IOException {
+ ByteArrayOutputStream output = new ByteArrayOutputStream();
+ try (SeekableByteChannel channel =
+ Files.newByteChannel(path, Set.of(StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS))) {
+ ByteBuffer buffer = ByteBuffer.allocate(1024);
+ int total = 0;
+ while (true) {
+ int count = channel.read(buffer);
+ if (count < 0) {
+ break;
+ }
+ if (count == 0) {
+ continue;
+ }
+ total += count;
+ if (total > MAX_MANIFEST_BYTES) {
+ throw new KeyUnavailableException();
+ }
+ buffer.flip();
+ output.write(buffer.array(), buffer.position(), buffer.remaining());
+ buffer.clear();
+ }
+ }
+ return output.toByteArray();
+ }
+
+ private static Snapshot parse(byte[] contents) {
+ if (contents.length == 0 || contents.length > MAX_MANIFEST_BYTES) {
+ throw new KeyUnavailableException();
+ }
+ String text;
+ try {
+ text =
+ StandardCharsets.UTF_8
+ .newDecoder()
+ .onMalformedInput(CodingErrorAction.REPORT)
+ .onUnmappableCharacter(CodingErrorAction.REPORT)
+ .decode(ByteBuffer.wrap(contents))
+ .toString();
+ } catch (CharacterCodingException ex) {
+ throw new KeyUnavailableException();
+ }
+ if (text.indexOf('\r') >= 0 || text.indexOf('\0') >= 0 || text.startsWith("\uFEFF")) {
+ throw new KeyUnavailableException();
+ }
+ for (int index = 0; index < text.length(); index++) {
+ char value = text.charAt(index);
+ if (value > 0x7e || (value < 0x20 && value != '\n')) {
+ throw new KeyUnavailableException();
+ }
+ }
+
+ String normalized = text.endsWith("\n") ? text.substring(0, text.length() - 1) : text;
+ if (normalized.isEmpty() || normalized.endsWith("\n")) {
+ throw new KeyUnavailableException();
+ }
+ String[] lines = normalized.split("\n", -1);
+ if (!MANIFEST_HEADER.equals(lines[0]) || lines.length < 2) {
+ throw new KeyUnavailableException();
+ }
+
+ KeyEntry active = null;
+ Map allKeys = new HashMap<>();
+ Set seenIds = new HashSet<>();
+ int retiringCount = 0;
+ for (int index = 1; index < lines.length; index++) {
+ String line = lines[index];
+ if (line.isEmpty()) {
+ throw new KeyUnavailableException();
+ }
+ String[] fields = line.split(" ", -1);
+ if (fields.length == 3 && "active".equals(fields[0])) {
+ if (active != null) {
+ throw new KeyUnavailableException();
+ }
+ if (index != 1) {
+ throw new KeyUnavailableException();
+ }
+ KeyEntry entry = parseEntry(fields[1], fields[2], null);
+ if (!seenIds.add(entry.keyId())) {
+ throw new KeyUnavailableException();
+ }
+ active = entry;
+ allKeys.put(entry.keyId(), entry);
+ } else if (fields.length == 4 && "retiring".equals(fields[0])) {
+ if (active == null) {
+ throw new KeyUnavailableException();
+ }
+ retiringCount++;
+ if (retiringCount > MAX_RETIRING_KEYS) {
+ throw new KeyUnavailableException();
+ }
+ long decryptUntilMillis;
+ try {
+ if (!fields[2].matches("[1-9][0-9]{0,18}")) {
+ throw new NumberFormatException();
+ }
+ decryptUntilMillis = Long.parseLong(fields[2]);
+ if (decryptUntilMillis <= 0) {
+ throw new NumberFormatException();
+ }
+ } catch (NumberFormatException ex) {
+ throw new KeyUnavailableException();
+ }
+ Instant decryptUntil;
+ try {
+ decryptUntil = Instant.ofEpochMilli(decryptUntilMillis);
+ } catch (RuntimeException ex) {
+ throw new KeyUnavailableException();
+ }
+ KeyEntry entry = parseEntry(fields[1], fields[3], decryptUntil);
+ if (!seenIds.add(entry.keyId())) {
+ throw new KeyUnavailableException();
+ }
+ allKeys.put(entry.keyId(), entry);
+ } else {
+ throw new KeyUnavailableException();
+ }
+ }
+ if (active == null) {
+ throw new KeyUnavailableException();
+ }
+ return new Snapshot(active, allKeys);
+ }
+
+ private static KeyEntry parseEntry(String keyId, String encodedKey, Instant decryptUntil) {
+ if (keyId == null || !KEY_ID.matcher(keyId).matches() || encodedKey == null) {
+ throw new KeyUnavailableException();
+ }
+ byte[] keyMaterial;
+ try {
+ keyMaterial = Base64.getUrlDecoder().decode(encodedKey);
+ } catch (IllegalArgumentException ex) {
+ throw new KeyUnavailableException();
+ }
+ if (keyMaterial.length != KEY_BYTES
+ || !Base64.getUrlEncoder()
+ .withoutPadding()
+ .encodeToString(keyMaterial)
+ .equals(encodedKey)) {
+ java.util.Arrays.fill(keyMaterial, (byte) 0);
+ throw new KeyUnavailableException();
+ }
+ KeyEntry entry = new KeyEntry(keyId, keyMaterial, decryptUntil);
+ java.util.Arrays.fill(keyMaterial, (byte) 0);
+ return entry;
+ }
+
+ static final class Snapshot {
+ private final KeyEntry active;
+ private final Map keys;
+
+ private Snapshot(KeyEntry active, Map keys) {
+ this.active = active;
+ this.keys = Map.copyOf(keys);
+ }
+
+ String activeKeyId() {
+ return active.keyId();
+ }
+
+ KeyEntry activeKey() {
+ return active;
+ }
+
+ KeyEntry decryptionKey(String keyId, Instant now) {
+ KeyEntry key = keys.get(keyId);
+ if (key == null || (key.decryptUntil() != null && !now.isBefore(key.decryptUntil()))) {
+ throw new KeyUnavailableException();
+ }
+ return key;
+ }
+
+ @Override
+ public String toString() {
+ return "AccountResponseEnvelopeKeyring.Snapshot[redacted]";
+ }
+ }
+
+ static final class KeyEntry {
+ private final String keyId;
+ private final byte[] keyMaterial;
+ private final Instant decryptUntil;
+
+ private KeyEntry(String keyId, byte[] keyMaterial, Instant decryptUntil) {
+ this.keyId = keyId;
+ this.keyMaterial = keyMaterial.clone();
+ this.decryptUntil = decryptUntil;
+ }
+
+ String keyId() {
+ return keyId;
+ }
+
+ Instant decryptUntil() {
+ return decryptUntil;
+ }
+
+ javax.crypto.SecretKey secretKey() {
+ return new javax.crypto.spec.SecretKeySpec(keyMaterial.clone(), "AES");
+ }
+
+ @Override
+ public String toString() {
+ return "AccountResponseEnvelopeKeyring.KeyEntry[keyId=" + keyId + ", material=redacted]";
+ }
+ }
+
+ /** Retryable failure for absent, withdrawn, malformed, or unreadable mounted key material. */
+ public static final class KeyUnavailableException extends RuntimeException {
+ private KeyUnavailableException() {
+ super("Account response-envelope encryption keyring is unavailable");
+ }
+
+ public String errorCode() {
+ return "AUTH_UNAVAILABLE";
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java
new file mode 100644
index 0000000000..9cd030f669
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundle.java
@@ -0,0 +1,501 @@
+package net.firedevops.firemud.accountservice.service.session;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.Instant;
+import java.util.Base64;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority;
+import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.Snapshot;
+import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.OwnerLinearization;
+import net.firedevops.firemud.accountservice.service.session.AccountControlUiIssuanceRepository.Stored;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence;
+import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind;
+import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle;
+import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple;
+
+/** Exact ADR 0047 Account authority evidence for the tenantAdmin StartSession branch. */
+public final class AccountStartSessionOperatorAuthorityBundle {
+ public static final String BUNDLE_VERSION = StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION;
+ public static final String HUMAN_EVIDENCE_TYPE =
+ StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE;
+ private static final Pattern DECIMAL = Pattern.compile("[1-9][0-9]{0,18}");
+
+ private final StartSessionAuthorityEvidenceBundle decoded;
+ private final byte[] canonicalBytes;
+ private final Map value;
+
+ private AccountStartSessionOperatorAuthorityBundle(StartSessionAuthorityEvidenceBundle decoded) {
+ this.decoded = Objects.requireNonNull(decoded, "shared authority bundle is required");
+ this.canonicalBytes = decoded.canonicalBytes();
+ this.value = decoded.jsonValue();
+ }
+
+ /**
+ * Builds the one supported human branch from Account's already-current source snapshot and the
+ * control-ui token row proven by {@link AccountControlUiActorService}.
+ */
+ public static AccountStartSessionOperatorAuthorityBundle create(
+ StartSessionPreAuthorizationReservationTuple tuple,
+ Snapshot source,
+ Stored controlUiIssuance,
+ UUID issuanceOperationId,
+ OwnerLinearization linearization,
+ Instant issuedAt,
+ Instant referenceExpiresAt) {
+ Objects.requireNonNull(tuple, "pre-authorization tuple is required");
+ Objects.requireNonNull(source, "current Account source is required");
+ Objects.requireNonNull(controlUiIssuance, "current control-ui issuance is required");
+ Objects.requireNonNull(issuanceOperationId, "issuance operation identity is required");
+ Objects.requireNonNull(linearization, "Account owner linearization is required");
+ requireTimeWindow(issuedAt, referenceExpiresAt);
+
+ if (!tuple.actor().accountId().equals(source.actor())
+ || !tuple.action().scope().tenantId().equals(source.tenant())
+ || !controlUiIssuance.accountId.equals(source.actor())
+ || !controlUiIssuance.tenantId.equals(source.tenant())) {
+ throw denied("Current Account and control-ui source must exactly match the typed actor");
+ }
+
+ Map claims =
+ AccountControlUiIssuanceRepository.object(controlUiIssuance.claims);
+ requireCurrentTenantClaims(tuple, source, controlUiIssuance, claims);
+ SourceEvidence accountSource = uniqueAccountSource(source, source.actor());
+ BundleReference reference =
+ new BundleReference(
+ BUNDLE_VERSION,
+ accountSource.sourceVersion(),
+ Long.toString(linearization.sourceFence()),
+ linearization.transactionId());
+ String sourceEvidenceId =
+ sourceEvidenceId(source.evidence(), accountSource.sourceVersion(), reference);
+
+ Map typedScope =
+ Map.of(
+ "tenantId", tuple.action().scope().tenantId().toString(),
+ "targetNamespace", tuple.action().scope().targetNamespace());
+ Map authorityScope =
+ Map.of(
+ "scope", typedScope,
+ "actionFamily", tuple.actionFamily(),
+ "applicableAccountId", source.actor().toString(),
+ "applicableTenantId", source.tenant().toString());
+ Map projection =
+ Map.of(
+ "sourceType",
+ "ACCOUNT",
+ "sourceEvidenceId",
+ sourceEvidenceId,
+ "sourceEvidenceVersion",
+ accountSource.sourceVersion(),
+ "projectionStatus",
+ "CURRENT",
+ "evaluatedAt",
+ issuedAt.toString(),
+ "expiresAt",
+ referenceExpiresAt.toString());
+ Map operationIdentity =
+ Map.of(
+ "issuanceOperationId", issuanceOperationId.toString(),
+ "controlPlaneRequestId", tuple.controlPlaneRequestId(),
+ "actionFamilyRequestIdentity",
+ Map.of(
+ "requestIdentityKind",
+ "controlPlaneRequestId",
+ "requestId",
+ tuple.controlPlaneRequestId()),
+ "mutationDigest", tuple.mutationDigest());
+ Map humanEvidence = humanTenantEvidence(source, controlUiIssuance.jti, claims);
+
+ Map bundle = new LinkedHashMap<>();
+ bundle.put("bundleVersion", BUNDLE_VERSION);
+ bundle.put("authorityScope", authorityScope);
+ bundle.put("accountProjectionEvidence", projection);
+ bundle.put("issuanceOperationIdentity", operationIdentity);
+ bundle.put("issuanceKind", "human_operator");
+ bundle.put("authorityTuple", source.authorityTuple());
+ bundle.put("membershipVersion", source.membershipVersion());
+ bundle.put("issuanceFence", reference.sourceFence());
+ bundle.put("issuanceEvidence", humanEvidence);
+ byte[] encoded = AccountControlUiAuthority.canonical(bundle);
+ AccountStartSessionOperatorAuthorityBundle result = decode(encoded);
+ result.requireTupleBinding(tuple);
+ result.requireReferenceBinding(reference);
+ result.requireCurrent(source, controlUiIssuance, tuple, reference, issuedAt);
+ return result;
+ }
+
+ /** Strictly decodes one closed canonical authorityEvidenceBundle/v1 value. */
+ public static AccountStartSessionOperatorAuthorityBundle decode(byte[] exactCanonicalBytes) {
+ return new AccountStartSessionOperatorAuthorityBundle(
+ StartSessionAuthorityEvidenceBundle.decode(exactCanonicalBytes));
+ }
+
+ /** Compares every snapshot-bound authority projection and the exact original source reference. */
+ public void requireCurrent(
+ Snapshot currentSource,
+ Stored currentControlUiIssuance,
+ StartSessionPreAuthorizationReservationTuple tuple,
+ BundleReference originalReference,
+ Instant now) {
+ Objects.requireNonNull(currentSource, "current Account source is required");
+ Objects.requireNonNull(currentControlUiIssuance, "current control-ui issuance is required");
+ Objects.requireNonNull(tuple, "pre-authorization tuple is required");
+ Objects.requireNonNull(originalReference, "original Account source reference is required");
+ Objects.requireNonNull(now, "current time is required");
+ decoded.requireTupleBinding(tuple);
+ decoded.requireReferenceBinding(toSharedReference(originalReference));
+ Map projection =
+ object(value.get("accountProjectionEvidence"), "accountProjectionEvidence");
+ if (!now.isBefore(originalReferenceExpiresAt())
+ || !now.isBefore(instant(string(projection.get("expiresAt"), "projection expiry")))) {
+ throw denied("Original Account authority evidence is expired");
+ }
+ if (!tuple.actor().accountId().equals(currentSource.actor())
+ || !tuple.action().scope().tenantId().equals(currentSource.tenant())
+ || !currentControlUiIssuance.accountId.equals(currentSource.actor())
+ || !currentControlUiIssuance.tenantId.equals(currentSource.tenant())) {
+ throw denied("Current Account actor or tenant changed");
+ }
+ Map claims =
+ AccountControlUiIssuanceRepository.object(currentControlUiIssuance.claims);
+ requireCurrentTenantClaims(tuple, currentSource, currentControlUiIssuance, claims);
+ SourceEvidence source = uniqueAccountSource(currentSource, currentSource.actor());
+ if (!source.sourceVersion().equals(projection.get("sourceEvidenceVersion"))
+ || !source.sourceVersion().equals(originalReference.sourceVersion())
+ || !sourceEvidenceId(currentSource.evidence(), source.sourceVersion(), originalReference)
+ .equals(projection.get("sourceEvidenceId"))
+ || !canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple"))
+ || !canonicalEquals(currentSource.membershipVersion(), value.get("membershipVersion"))) {
+ throw denied("Current Account source, generation, or membership changed");
+ }
+ Map expectedEvidence =
+ humanTenantEvidence(currentSource, currentControlUiIssuance.jti, claims);
+ if (!canonicalEquals(expectedEvidence, value.get("issuanceEvidence"))) {
+ throw denied("Current human authority evidence changed");
+ }
+ }
+
+ /** Current-state proof for a same-attempt replay after the exact response envelope horizon. */
+ public void requireCurrentSnapshotForExactReplay(
+ Snapshot currentSource,
+ Stored currentControlUiIssuance,
+ StartSessionPreAuthorizationReservationTuple tuple,
+ BundleReference originalReference) {
+ Objects.requireNonNull(currentSource, "current Account source is required");
+ Objects.requireNonNull(currentControlUiIssuance, "current control-ui issuance is required");
+ Objects.requireNonNull(originalReference, "original Account source reference is required");
+ decoded.requireTupleBinding(tuple);
+ decoded.requireReferenceBinding(toSharedReference(originalReference));
+ if (!tuple.actor().accountId().equals(currentSource.actor())
+ || !tuple.action().scope().tenantId().equals(currentSource.tenant())
+ || !currentControlUiIssuance.accountId.equals(currentSource.actor())
+ || !currentControlUiIssuance.tenantId.equals(currentSource.tenant())) {
+ throw denied("Current Account actor or tenant changed");
+ }
+ Map claims =
+ AccountControlUiIssuanceRepository.object(currentControlUiIssuance.claims);
+ requireCurrentTenantClaims(tuple, currentSource, currentControlUiIssuance, claims);
+ SourceEvidence accountSource = uniqueAccountSource(currentSource, currentSource.actor());
+ Map projection =
+ object(value.get("accountProjectionEvidence"), "accountProjectionEvidence");
+ if (!accountSource.sourceVersion().equals(originalReference.sourceVersion())
+ || !accountSource.sourceVersion().equals(projection.get("sourceEvidenceVersion"))
+ || !sourceEvidenceId(
+ currentSource.evidence(), accountSource.sourceVersion(), originalReference)
+ .equals(projection.get("sourceEvidenceId"))
+ || !canonicalEquals(currentSource.authorityTuple(), value.get("authorityTuple"))
+ || !canonicalEquals(currentSource.membershipVersion(), value.get("membershipVersion"))
+ || !canonicalEquals(
+ humanTenantEvidence(currentSource, currentControlUiIssuance.jti, claims),
+ value.get("issuanceEvidence"))) {
+ throw denied("Current Account source differs from the consumed authorization");
+ }
+ }
+
+ /** Enforces request tuple equality separately from the authority projection. */
+ public void requireTupleBinding(StartSessionPreAuthorizationReservationTuple tuple) {
+ decoded.requireTupleBinding(tuple);
+ }
+
+ public byte[] canonicalBytes() {
+ return canonicalBytes.clone();
+ }
+
+ public BundleReference referenceForSource(Snapshot source, OwnerLinearization linearization) {
+ SourceEvidence accountSource = uniqueAccountSource(source, source.actor());
+ BundleReference reference =
+ new BundleReference(
+ BUNDLE_VERSION,
+ accountSource.sourceVersion(),
+ Long.toString(linearization.sourceFence()),
+ linearization.transactionId());
+ requireReferenceBinding(reference);
+ if (!sourceEvidenceId(source.evidence(), accountSource.sourceVersion(), reference)
+ .equals(sourceEvidenceId())) {
+ throw denied("Account source reference does not identify this captured source");
+ }
+ return reference;
+ }
+
+ public Map authorityTuple() {
+ return decoded.authorityTuple();
+ }
+
+ public Map membershipVersion() {
+ return decoded.membershipVersion();
+ }
+
+ public UUID issuanceOperationId() {
+ return decoded.issuanceOperationId();
+ }
+
+ public String controlPlaneRequestId() {
+ return decoded.controlPlaneRequestId();
+ }
+
+ public String authorizationExpiresAt() {
+ return decoded.authorizationExpiresAt();
+ }
+
+ public String sourceEvidenceId() {
+ return decoded.sourceEvidenceId();
+ }
+
+ public String sourceEvidenceVersion() {
+ return decoded.sourceEvidenceVersion();
+ }
+
+ public UUID controlUiTokenJti() {
+ return decoded.controlUiTokenJti();
+ }
+
+ public Map jsonValue() {
+ return decoded.jsonValue();
+ }
+
+ private Instant originalReferenceExpiresAt() {
+ return decoded.expiresAt();
+ }
+
+ private void requireReferenceBinding(BundleReference reference) {
+ decoded.requireReferenceBinding(toSharedReference(reference));
+ }
+
+ static StartSessionAuthorityEvidenceBundle.BundleReference toSharedReference(
+ BundleReference reference) {
+ Objects.requireNonNull(reference, "original Account source reference is required");
+ return new StartSessionAuthorityEvidenceBundle.BundleReference(
+ reference.bundleVersion(),
+ reference.sourceVersion(),
+ reference.sourceFence(),
+ reference.linearization());
+ }
+
+ static BundleReference fromSharedReference(
+ StartSessionAuthorityEvidenceBundle.BundleReference reference) {
+ Objects.requireNonNull(reference, "original Account source reference is required");
+ return new BundleReference(
+ reference.bundleVersion(),
+ reference.sourceVersion(),
+ reference.sourceFence(),
+ reference.linearization());
+ }
+
+ private static void requireCurrentTenantClaims(
+ StartSessionPreAuthorizationReservationTuple tuple,
+ Snapshot source,
+ Stored stored,
+ Map claims) {
+ if (!tuple.actor().accountId().equals(stored.accountId)
+ || !tuple.actor().accountId().equals(source.actor())
+ || !tuple.action().scope().tenantId().equals(stored.tenantId)
+ || !tuple.action().scope().tenantId().equals(source.tenant())
+ || !stored.jti.toString().equals(claims.get("jti"))
+ || !stored.accountId.toString().equals(claims.get("sub"))
+ || !stored.accountId.toString().equals(claims.get("accountId"))
+ || !"control-ui".equals(claims.get("aud"))
+ || positiveNumber(claims.get("tokenGeneration"), "tokenGeneration") != 1L
+ || claims.containsKey("assurance")
+ || claims.containsKey("globalRoles")
+ || !Map.of(stored.tenantId.toString(), List.of("tenantAdmin"))
+ .equals(claims.get("scopedRoles"))
+ || !canonicalEquals(source.authorityTuple(), claims.get("authorityTuple"))
+ || !canonicalEquals(source.membershipVersion(), claims.get("membershipVersion"))) {
+ throw denied("Current tenantAdmin control-ui evidence is required");
+ }
+ }
+
+ private static Map humanTenantEvidence(
+ Snapshot source, UUID tokenJti, Map claims) {
+ if (claims.containsKey("assurance") || claims.containsKey("globalRoles")) {
+ throw denied("Tenant authority must omit assurance and global-role evidence");
+ }
+ Map tuple = source.authorityTuple();
+ long accountGeneration =
+ positiveNumber(tuple.get("accountAuthorityGeneration"), "accountAuthorityGeneration");
+ Map tenantGenerations =
+ object(tuple.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration");
+ if (!tenantGenerations.keySet().equals(Set.of(source.tenant().toString()))) {
+ throw denied("Exact selected tenant authority generation is required");
+ }
+ long tenantGeneration =
+ positiveNumber(
+ tenantGenerations.get(source.tenant().toString()), "tenantAuthorityGeneration");
+ Map evidence = new LinkedHashMap<>();
+ evidence.put("evidenceType", HUMAN_EVIDENCE_TYPE);
+ evidence.put("actorAccountId", source.actor().toString());
+ evidence.put("controlUiTokenJti", tokenJti.toString());
+ evidence.put("role", "tenantAdmin");
+ evidence.put("accountGeneration", Long.toString(accountGeneration));
+ evidence.put("tenantGeneration", Long.toString(tenantGeneration));
+ return Map.copyOf(evidence);
+ }
+
+ private static String sourceEvidenceId(
+ byte[] sourceEvidence, String sourceVersion, BundleReference reference) {
+ Map value =
+ Map.of(
+ "schema",
+ "account-authority-source-linearization/v1",
+ "sourceType",
+ "ACCOUNT",
+ "sourceEvidenceBytesBase64",
+ Base64.getEncoder().encodeToString(sourceEvidence),
+ "sourceVersion",
+ sourceVersion,
+ "sourceFence",
+ reference.sourceFence(),
+ "transactionId",
+ reference.linearization());
+ try {
+ byte[] digest =
+ MessageDigest.getInstance("SHA-256").digest(AccountControlUiAuthority.canonical(value));
+ return "sha256:" + java.util.HexFormat.of().formatHex(digest);
+ } catch (NoSuchAlgorithmException unavailable) {
+ throw new IllegalStateException("SHA-256 is unavailable", unavailable);
+ }
+ }
+
+ private static SourceEvidence uniqueAccountSource(Snapshot source, UUID actor) {
+ List matches =
+ source.sources().stream()
+ .filter(
+ candidate ->
+ candidate.kind() == SourceKind.ACCOUNT
+ && actor.toString().equals(candidate.scopeId()))
+ .toList();
+ if (matches.size() != 1) {
+ throw denied("One exact Account source version for the human actor is required");
+ }
+ return matches.getFirst();
+ }
+
+ private static void requireTimeWindow(Instant issuedAt, Instant expiresAt) {
+ Objects.requireNonNull(issuedAt, "issue time is required");
+ Objects.requireNonNull(expiresAt, "reference expiry is required");
+ if (!issuedAt.isAfter(Instant.EPOCH)
+ || !expiresAt.isAfter(issuedAt)
+ || issuedAt.getNano() % 1_000_000 != 0
+ || expiresAt.getNano() % 1_000_000 != 0) {
+ throw denied("Operator evidence timestamps must be positive exact milliseconds");
+ }
+ }
+
+ private static Instant instant(String value) {
+ try {
+ Instant parsed = Instant.parse(value);
+ if (!parsed.toString().equals(value)) {
+ throw denied("Timestamp is not canonical UTC text");
+ }
+ return parsed;
+ } catch (RuntimeException malformed) {
+ throw denied("Timestamp is malformed");
+ }
+ }
+
+ private static boolean canonicalEquals(Object first, Object second) {
+ if (first == null || second == null) return false;
+ return MessageDigest.isEqual(
+ AccountControlUiAuthority.canonical(first), AccountControlUiAuthority.canonical(second));
+ }
+
+ @SuppressWarnings("unchecked")
+ private static Map object(Object value, String field) {
+ if (!(value instanceof Map, ?> map)
+ || map.keySet().stream().anyMatch(key -> !(key instanceof String))) {
+ throw denied(field + " must be an object");
+ }
+ return (Map) map;
+ }
+
+ private static void requireFields(Map value, Set