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 e79b1b2fdc..a9121de2ea 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -350,6 +350,12 @@ This preparation is owned by AA-1.3 in [Capability Status](#capability-status), The added `AccountDraftSourceCompositionService`, `AccountControlUiAuthority`, and `AccountControlUiSigningSpec` remain unregistered and transaction-bound source preparation. They do not issue a JWT, authorize receiver execution, or establish runtime currentness/readiness. +### Account retained-login and signer storage proof receiving + +The receiving #3047 batch preserves current production and migration owners and restores useful proof from its retained source into four existing PostgreSQL suites. It covers exact revocation retry and immutable retained evidence, admission blocked behind revocation on independent database connections, full Account/source/outbox immutability, independent malformed signer enrollment and promotion writes, retained generation/observation/result refusal, generation-result lock retention and rollback after protected trust moves. The readiness producer case uses the complete V2 inventory: eight probes and twelve Pod receipts, competing one-shot claims, committed ISSUED readback before delivery, verified receipt readback before a controlled callback failure, sanitized errors and wiped transient bytes, operation-wide ABORTED/CLEANED retention, and refusal of redelivery, resurrection or reclaim. + +R1378's initial native four-suite run passes 34 of 35 PostgreSQL cases; its aggregate remains failed because the new readiness case expected the producer's inner delivery exception rather than the mounted signer's deliberately sanitized outer exception. After correcting only that expectation and adding an explicit final verified-readback marker, the exact case passes with zero failures, errors or skips; affected enabled integration Checkstyle/SpotBugs, full Java formatting and documentation checks pass. Together these results qualify all 35 selected cases at their stated iterations, rather than claiming a fresh successful aggregate. The current stronger signer, V2 inventory and per-Pod receipt assertions remain intact. These are manually composed storage fixtures with controlled trust and transport collaborators, not live Kubernetes enrollment, real PKI/custody, protected Redis provisioning, default runtime registration, public admission or activation. The original retained source remains preserved; its obsolete schema names and held configuration paths are not restored. + ### Account–Game Session JWT readiness receiver source preparation The existing Account-owned signer/readiness preparation now has a matching unregistered Account-to-Game Session receiver source boundary. The source adds a manual, unregistered, read-only Account readiness-owner RPC adapter; Game Session rereads that exact owner evidence before and after local JWT verification, binds the observation to its protected local identity and JWKS source, and uses the existing workload mTLS identity and method guard. The receiver remains non-authorizing: it creates no authentication context, admission, application operation, or protected effect. These sources implement only the receiver seam described by accepted [ADR 0014](../../architecture/decisions/adr-0014-phased-jwt-signing-key-rotation-and-readiness.md) and [ADR 0038](../../architecture/decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md); they do not implement the pending ADR 0185 CSR enrollment, approval, issuer, or rotation proposal. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java index ae33bacbc9..838d6654c2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java @@ -4,6 +4,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; @@ -341,6 +343,35 @@ void freshAccountGenericSecurityEventsRemainNonCurrentWithExactSourceEvidence() assertThat(rolledBackEvent).isEmpty(); Account lifecycleUpdate = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); lifecycleUpdate.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); + var accountBeforeLifecycleRejection = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT *, xmin::TEXT AS row_version FROM accounts WHERE account_uuid = ?", + account.getAccountUuid()), + "expected Account before lifecycle rejection") + .intoMap(); + var generationsBeforeLifecycleRejection = + dsl.fetch( + "SELECT *, xmin::TEXT AS row_version FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + account.getAccountUuid()) + .intoMaps(); + var fencesBeforeLifecycleRejection = + dsl.fetch( + "SELECT *, xmin::TEXT AS row_version FROM account_authority_issuance_fences WHERE account_uuid = ?", + account.getAccountUuid()) + .intoMaps(); + var sourceRowsBeforeLifecycleRejection = + dsl.fetch( + "SELECT *, xmin::TEXT AS row_version FROM account_authority_source_records WHERE account_uuid = ?", + account.getAccountUuid()) + .intoMaps(); + var outboxRowsBeforeLifecycleRejection = + dsl.fetch( + "SELECT *, xmin::TEXT AS row_version FROM account_authority_outbox_events WHERE outbox_stream_key = ? " + + "ORDER BY outbox_sequence", + accountStream) + .intoMaps(); assertThatThrownBy( () -> transaction.executeWithoutResult(status -> accounts.save(lifecycleUpdate))) .isInstanceOf(IllegalStateException.class) @@ -359,6 +390,44 @@ void freshAccountGenericSecurityEventsRemainNonCurrentWithExactSourceEvidence() .isEqualTo(account.getPasswordHash()); assertThat(lifecycleUpdate.getLifecycleState()) .isEqualTo(AccountLifecycleState.SECURITY_LOCKED); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT *, xmin::TEXT AS row_version FROM accounts WHERE account_uuid = ?", + account.getAccountUuid()), + "expected Account after lifecycle rejection") + .intoMap()) + .usingRecursiveComparison() + .isEqualTo(accountBeforeLifecycleRejection); + assertThat( + dsl.fetch( + "SELECT *, xmin::TEXT AS row_version FROM account_authority_generations " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + account.getAccountUuid()) + .intoMaps()) + .usingRecursiveComparison() + .isEqualTo(generationsBeforeLifecycleRejection); + assertThat( + dsl.fetch( + "SELECT *, xmin::TEXT AS row_version FROM account_authority_issuance_fences WHERE account_uuid = ?", + account.getAccountUuid()) + .intoMaps()) + .usingRecursiveComparison() + .isEqualTo(fencesBeforeLifecycleRejection); + assertThat( + dsl.fetch( + "SELECT *, xmin::TEXT AS row_version FROM account_authority_source_records WHERE account_uuid = ?", + account.getAccountUuid()) + .intoMaps()) + .usingRecursiveComparison() + .isEqualTo(sourceRowsBeforeLifecycleRejection); + assertOutboxRowsEqual( + outboxRowsBeforeLifecycleRejection, + dsl.fetch( + "SELECT *, xmin::TEXT AS row_version FROM account_authority_outbox_events WHERE outbox_stream_key = ? " + + "ORDER BY outbox_sequence", + accountStream) + .intoMaps()); assertThat(afterLifecycleUpdate.generation()).isEqualTo(3L); assertThat(afterLifecycleUpdate.sourceVersion()).isEqualTo(3L); assertThat(afterLifecycleUpdate.issuanceFence().value()).isEqualTo(3L); @@ -882,6 +951,26 @@ private static void await(CountDownLatch latch, String failureMessage) { } } + private static void assertOutboxRowsEqual( + List> expected, List> actual) { + assertThat(actual).hasSize(expected.size()); + for (int index = 0; index < expected.size(); index++) { + Map expectedRow = expected.get(index); + Map actualRow = actual.get(index); + assertThat(actualRow.keySet()).isEqualTo(expectedRow.keySet()); + for (Map.Entry entry : expectedRow.entrySet()) { + String field = entry.getKey(); + Object expectedValue = entry.getValue(); + Object actualValue = actualRow.get(field); + if ("payload".equals(field)) { + assertThat((byte[]) actualValue).containsExactly((byte[]) expectedValue); + } else { + assertThat(actualValue).isEqualTo(expectedValue); + } + } + } + } + private static void awaitLockWait(DSLContext dsl, Integer waitingPid, Integer... blockerPids) throws InterruptedException { if (blockerPids.length == 0) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index 9704b5349a..dfd312e520 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -78,6 +78,7 @@ import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.CallerIdentity; import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation; import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayTokenIdentityFenceRepository.TokenRevokedException; import net.firedevops.firemud.accountservice.repository.AccountRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository; import net.firedevops.firemud.accountservice.repository.AccountSecurityStateOperationRepository.Capture; @@ -951,6 +952,196 @@ void realCommittedIssuanceEstablishesExactSqlFenceAndIndependentRetryReadback() .isEqualTo(1L); } + @Test + void durableExactRevocationIntentDeniesAdmissionAndCommitRecoveryWithoutRecreation() + throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.NONE, false); + assertThat(harness.service().commitPendingCandidate(harness.pending().requestId()).outcome()) + .isEqualTo(AccountGameplayDelegationIssuanceCommitService.Outcome.COMMITTED); + TokenIdentity identity = tokenFenceIdentity(harness); + AccountGameplayTokenIdentityFenceRepository fences = + new AccountGameplayTokenIdentityFenceRepository(harness.dsl()); + UUID requestId = UUID.randomUUID(); + String digest = + AccountGameplayTokenIdentityFenceRepository.revocationDigest(identity, requestId); + + var pending = + inTransaction( + harness.context(), () -> fences.beginRevocationIntent(identity, requestId, digest)); + assertThat(pending.state()).isEqualTo(State.PENDING); + assertThat(pending.tokenIdentityFence()).isEqualTo(2L); + assertThat( + inTransaction( + harness.context(), () -> fences.beginRevocationIntent(identity, requestId, digest))) + .isEqualTo(pending); + Record pendingFence = + Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_token_identity_fences WHERE operation_id = ?", + identity.operationId()), + "pending token identity fence must be retained"); + Map pendingFenceImage = pendingFence.intoMap(); + + assertThatThrownBy( + () -> inTransaction(harness.context(), () -> fences.requireActiveForUpdate(identity))) + .isInstanceOf(TokenRevokedException.class); + assertThatThrownBy(() -> harness.issuance().readCommittedProof(identity.issuanceRequestId())) + .isInstanceOf(TokenRevokedException.class); + assertThatThrownBy(() -> harness.service().commitPendingCandidate(identity.issuanceRequestId())) + .isInstanceOf( + AccountGameplayDelegationIssuanceCommitService.IssuanceCommitUnavailableException.class) + .hasNoCause(); + + UUID conflictingRequest = UUID.randomUUID(); + assertThatThrownBy( + () -> + inTransaction( + harness.context(), + () -> + fences.beginRevocationIntent( + identity, + conflictingRequest, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, conflictingRequest)))) + .isInstanceOf( + AccountGameplayTokenIdentityFenceRepository.RevocationConflictException.class); + assertThatThrownBy( + () -> + inTransaction( + harness.context(), + () -> + harness + .dsl() + .execute( + "UPDATE account_gameplay_token_identity_fences SET state = 'ACTIVE', " + + "token_identity_fence = 1, revocation_request_id = NULL, " + + "revocation_digest = NULL WHERE operation_id = ?", + identity.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + harness.context(), + () -> + harness + .dsl() + .execute( + "DELETE FROM account_gameplay_token_identity_fences " + + "WHERE operation_id = ?", + identity.operationId()))) + .isInstanceOf(DataAccessException.class); + + assertThat( + Objects.requireNonNull( + harness + .dsl() + .fetchOne( + "SELECT * FROM account_gameplay_token_identity_fences " + + "WHERE operation_id = ?", + identity.operationId()), + "the exact pending token identity fence must not be deleted or recreated") + .intoMap()) + .isEqualTo(pendingFenceImage); + assertThat( + inTransaction( + harness.context(), () -> fences.beginRevocationIntent(identity, requestId, digest))) + .isEqualTo(pending); + } + + @Test + void racingAdmissionWaitsForAccountRevocationTransactionThenObservesPendingFence() + throws Exception { + CommitHarness harness = newCommitHarness(CommitHook.NONE, false); + harness.service().commitPendingCandidate(harness.pending().requestId()); + TokenIdentity identity = tokenFenceIdentity(harness); + AccountGameplayTokenIdentityFenceRepository fences = + new AccountGameplayTokenIdentityFenceRepository(harness.dsl()); + CountDownLatch pendingWritten = new CountDownLatch(1); + CountDownLatch releaseRevocation = new CountDownLatch(1); + CountDownLatch readerPidCaptured = new CountDownLatch(1); + AtomicInteger revocationPid = new AtomicInteger(); + AtomicInteger readerPid = new AtomicInteger(); + var executor = Executors.newFixedThreadPool(2); + try { + var revocation = + executor.submit( + () -> + inTransaction( + harness.context(), + () -> { + revocationPid.set( + Objects.requireNonNull( + harness.dsl().fetchOne("SELECT pg_backend_pid()"), + "revocation transaction must have a PostgreSQL backend") + .get(0, Integer.class)); + UUID requestId = UUID.randomUUID(); + var pending = + fences.beginRevocationIntent( + identity, + requestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, requestId)); + pendingWritten.countDown(); + try { + if (!releaseRevocation.await(30, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "Timed out waiting to release Account revocation transaction"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted waiting to release Account revocation transaction", + interrupted); + } + return pending; + })); + assertThat(pendingWritten.await(10, TimeUnit.SECONDS)).isTrue(); + + var admission = + executor.submit( + () -> + inTransaction( + harness.context(), + () -> { + readerPid.set( + Objects.requireNonNull( + harness.dsl().fetchOne("SELECT pg_backend_pid()"), + "admission transaction must have a PostgreSQL backend") + .get(0, Integer.class)); + readerPidCaptured.countDown(); + return fences.requireActiveForUpdate(identity); + })); + assertThat(readerPidCaptured.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(revocationPid.get()).isPositive(); + assertThat(readerPid.get()).isPositive().isNotEqualTo(revocationPid.get()); + assertThat( + waitUntilBlockedBy( + harness.dsl(), + readerPid.get(), + revocationPid.get(), + TimeUnit.SECONDS.toNanos(10))) + .as("admission must block on the Account row held by the uncommitted revocation") + .isTrue(); + assertThat(admission.isDone()).isFalse(); + assertThat(revocation.isDone()).isFalse(); + + releaseRevocation.countDown(); + assertThat(revocation.get(10, TimeUnit.SECONDS).state()).isEqualTo(State.PENDING); + assertThatThrownBy(() -> admission.get(10, TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(TokenRevokedException.class); + } finally { + releaseRevocation.countDown(); + executor.shutdown(); + if (!executor.awaitTermination(15, TimeUnit.SECONDS)) { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + } + @Test void concurrentDifferentAccountIssuerSnapshotsAndPendingIssuanceShareGlobalRows() throws Exception { @@ -2330,6 +2521,27 @@ private static void awaitLatch(CountDownLatch latch, String description) { } } + private static boolean waitUntilBlockedBy( + DSLContext dsl, int waitingPid, int blockingPid, long timeoutNanos) + throws InterruptedException { + long deadline = System.nanoTime() + timeoutNanos; + while (System.nanoTime() < deadline) { + Boolean blocked = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity " + + "WHERE pid = ? AND wait_event_type = 'Lock' " + + "AND ? = ANY(pg_blocking_pids(pid)))", + waitingPid, + blockingPid), + "PostgreSQL lock-wait readback must return a row") + .get(0, Boolean.class); + if (Boolean.TRUE.equals(blocked)) return true; + Thread.sleep(10L); + } + return false; + } + private record TestContext( TransactionTemplate transaction, PlatformTransactionManager manager, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java index cab856a65e..8badd2eaf2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java @@ -2,7 +2,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; - +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.Grpc; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.security.KeyPairGenerator; @@ -12,10 +22,17 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; +import javax.net.ssl.SSLSession; +import net.firedevops.firemud.account.v1.RecordGenerationResultRequest; +import net.firedevops.firemud.account.v1.RecordGenerationResultResponse; +import net.firedevops.firemud.accountservice.config.AccountJwtSignerMaterializerTrustBinding; +import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.Binding; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.CustodyMode; @@ -23,6 +40,8 @@ import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationRequest; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.GenerationResult; import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository.TrustFence; +import net.firedevops.firemud.accountservice.security.AccountJwtSignerMaterializerTlsInterceptor; +import net.firedevops.firemud.accountservice.service.impl.AccountJwtSignerMaterializationService; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; @@ -390,6 +409,489 @@ void parentV98UpgradePreservesRetainedAccountWithoutInventingSignerEnrollment() assertThat(inTransaction(context, () -> desired.readEnrollmentState(BINDING))).isEmpty(); } + @Test + void independentSqlEnrollmentInsertsRejectPartialAndMalformedProtectedIdentity() { + TestContext context = newTestContext(null); + AccountJwtSignerDesiredStateRepository desired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + String validRow = + context + .transaction() + .execute( + status -> { + desired.initialize(BINDING, enrollmentIdentity()); + String row = signerRow(context, "account_jwt_signer_desired_states"); + status.setRollbackOnly(); + return row; + }); + assertThat(validRow).isNotNull(); + for (String field : + List.of( + "enrollment_cluster_incarnation_uid", + "enrollment_namespace_uid", + "enrollment_materializer_binding_digest", + "enrollment_materializer_config_revision", + "enrollment_api_binding_digest", + "enrollment_api_config_revision", + "enrollment_public_config_map_uid", + "enrollment_public_config_map_resource_version", + "enrollment_public_config_map_snapshot_digest")) { + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + insertSignerRow( + context, + "account_jwt_signer_desired_states", + validRow, + "jsonb_build_object(?, NULL)", + field))) + .as("independent partial enrollment INSERT: %s", field) + .isInstanceOf(DataAccessException.class) + .satisfies(failure -> assertThat(signerSqlState(failure)).isEqualTo("23514")); + assertThat(count(context, "account_jwt_signer_desired_states")).isZero(); + } + for (String field : + List.of( + "enrollment_materializer_binding_digest", + "enrollment_api_binding_digest", + "enrollment_public_config_map_snapshot_digest")) { + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + insertSignerRow( + context, + "account_jwt_signer_desired_states", + validRow, + "jsonb_build_object(?, ?)", + field, + "not-a-sha256"))) + .as("independent malformed enrollment INSERT: %s", field) + .isInstanceOf(DataAccessException.class) + .satisfies(failure -> assertThat(signerSqlState(failure)).isEqualTo("23514")); + assertThat(count(context, "account_jwt_signer_desired_states")).isZero(); + } + inTransaction(context, () -> desired.initialize(BINDING, enrollmentIdentity())); + assertThat(count(context, "account_jwt_signer_desired_states")).isEqualTo(1L); + } + + @Test + void rawResourceVersionWritesAndImmutableGenerationEvidenceMutationsAreRefused() + throws Exception { + TestContext context = newTestContext(null); + AccountJwtSignerDesiredStateRepository desired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + inTransaction(context, () -> desired.initialize(BINDING, enrollmentIdentity())); + GenerationRequest request = + inTransaction(context, () -> desired.ensureCurrentGenerationRequest(BINDING, trust())); + String observationRow = + context + .transaction() + .execute( + status -> { + desired.recordSecretObservation( + BINDING, + trust(), + request.operationId(), + request.operationDigest(), + SECRET_UID, + "12"); + String row = signerRow(context, "account_jwt_signer_secret_observations"); + status.setRollbackOnly(); + return row; + }); + assertThat(observationRow).isNotNull(); + for (String invalid : List.of("", "r\n", "r\u0001", "r".repeat(257))) { + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + insertSignerRow( + context, + "account_jwt_signer_secret_observations", + observationRow, + "jsonb_build_object('observed_resource_version', ?)", + invalid))) + .isInstanceOf(DataAccessException.class) + .satisfies( + failure -> + assertThat(signerSqlState(failure)) + .isEqualTo(invalid.length() > 256 ? "22001" : "23514")); + assertThat(count(context, "account_jwt_signer_secret_observations")).isZero(); + } + GenerationRequest observed = + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + trust(), + request.operationId(), + request.operationDigest(), + SECRET_UID, + "12")); + PublicJwk key = publicJwk(request.targetKid()); + String resultRow = + context + .transaction() + .execute( + status -> { + desired.recordGenerationResult( + BINDING, + trust(), + request.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + key.json()); + String row = signerRow(context, "account_jwt_signer_generation_results"); + status.setRollbackOnly(); + return row; + }); + assertThat(resultRow).isNotNull(); + for (String field : List.of("expected_prior_resource_version", "observed_resource_version")) { + for (String invalid : List.of("", "r\n", "r\u0001", "r".repeat(257))) { + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + insertSignerRow( + context, + "account_jwt_signer_generation_results", + resultRow, + "jsonb_build_object(?, ?)", + field, + invalid))) + .as("raw result resource version: %s", field) + .isInstanceOf(DataAccessException.class) + .satisfies( + failure -> + assertThat(signerSqlState(failure)) + .isEqualTo(invalid.length() > 256 ? "22001" : "23514")); + assertThat(count(context, "account_jwt_signer_generation_results")).isZero(); + } + } + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + trust(), + request.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + key.json())); + Map mutations = + Map.of( + "account_jwt_signer_generation_operations", "target_kid = 'changed'", + "account_jwt_signer_secret_observations", "trust_config_revision = 'changed'", + "account_jwt_signer_generation_results", + "public_key_fingerprint = '" + "0".repeat(64) + "'"); + Map retained = new LinkedHashMap<>(); + mutations.keySet().forEach(table -> retained.put(table, signerRow(context, table))); + for (var mutation : mutations.entrySet()) { + for (String sql : + List.of( + "UPDATE " + mutation.getKey() + " SET " + mutation.getValue(), + "DELETE FROM " + mutation.getKey(), + "TRUNCATE TABLE " + mutation.getKey(), + "TRUNCATE TABLE " + mutation.getKey() + " CASCADE")) { + assertThatThrownBy(() -> inTransaction(context, () -> context.dsl().execute(sql))) + .as("immutable signer evidence: %s", sql) + .isInstanceOf(DataAccessException.class) + .satisfies(failure -> assertThat(signerSqlState(failure)).isIn("23514", "0A000")); + retained.forEach((table, row) -> assertThat(signerRow(context, table)).isEqualTo(row)); + } + } + } + + @Test + void rawGenerationResultTriggerRetainsOwnerLocksUntilTransactionCompletion() throws Exception { + TestContext context = newTestContext(null); + AccountJwtSignerDesiredStateRepository desired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + inTransaction(context, () -> desired.initialize(BINDING, enrollmentIdentity())); + GenerationRequest request = + inTransaction(context, () -> desired.ensureCurrentGenerationRequest(BINDING, trust())); + GenerationRequest observed = + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + trust(), + request.operationId(), + request.operationDigest(), + SECRET_UID, + "12")); + PublicJwk key = publicJwk(request.targetKid()); + String resultRow = + context + .transaction() + .execute( + status -> { + desired.recordGenerationResult( + BINDING, + trust(), + request.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + key.json()); + String row = signerRow(context, "account_jwt_signer_generation_results"); + status.setRollbackOnly(); + return row; + }); + assertThat(resultRow).isNotNull(); + // Raw INSERT takes no repository locks: these locks must come from the result trigger. + inTransaction( + context, + () -> { + insertSignerRow( + context, "account_jwt_signer_generation_results", resultRow, "'{}'::jsonb"); + for (String table : + List.of( + "account_jwt_signer_desired_states", + "account_jwt_signer_generation_operations", + "account_jwt_signer_secret_observations")) { + assertThatThrownBy( + () -> { + try (var connection = context.dataSource().getConnection()) { + DSL.using(connection, SQLDialect.POSTGRES) + .fetch("SELECT * FROM " + table + " FOR UPDATE NOWAIT"); + } + }) + .as("result trigger retains %s on an independent physical connection", table) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("could not obtain lock"); + } + return null; + }); + try (var connection = context.dataSource().getConnection()) { + assertThat( + DSL.using(connection, SQLDialect.POSTGRES) + .fetch("SELECT * FROM account_jwt_signer_desired_states FOR UPDATE NOWAIT")) + .hasSize(1); + } + assertThat(count(context, "account_jwt_signer_generation_results")).isEqualTo(1L); + } + + @Test + void protectedTrustMovementBeforeCommitRollsBackActualGenerationResult() throws Exception { + TestContext context = newTestContext(null); + AccountJwtSignerDesiredStateRepository desired = + new AccountJwtSignerDesiredStateRepository(context.dsl()); + byte[] peerSpki = "controlled-materializer-peer".getBytes(StandardCharsets.US_ASCII); + String peerUri = "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer"; + String pin = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(peerSpki)); + String digest = + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + TRUST_REVISION, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + peerUri, + List.of(pin)); + var initial = + new AccountJwtSignerMaterializerTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + peerUri, + List.of(pin), + TRUST_REVISION, + digest); + var changed = + new AccountJwtSignerMaterializerTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + peerUri, + List.of(pin), + "trust-r2", + AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( + "trust-r2", + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + peerUri, + List.of(pin))); + TrustFence initialTrust = new TrustFence(CLUSTER_UID, NAMESPACE_UID, digest, TRUST_REVISION); + inTransaction( + context, + () -> + desired.initialize( + BINDING, + new EnrollmentIdentity( + CLUSTER_UID, + NAMESPACE_UID, + digest, + TRUST_REVISION, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "12", + INITIAL_CONFIG_MAP_SNAPSHOT_DIGEST))); + GenerationRequest request = + inTransaction(context, () -> desired.ensureCurrentGenerationRequest(BINDING, initialTrust)); + GenerationRequest observed = + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + initialTrust, + request.operationId(), + request.operationDigest(), + SECRET_UID, + "12")); + String retainedState = signerRow(context, "account_jwt_signer_desired_states"); + var provider = mock(AccountJwtSignerMaterializerTrustBinding.class); + when(provider.current()) + .thenReturn(Optional.of(initial), Optional.of(initial)) + .thenAnswer( + invocation -> { + assertThat(count(context, "account_jwt_signer_generation_results")) + .as("the real INSERT is visible inside the transaction before trust moves") + .isEqualTo(1L); + return Optional.of(changed); + }); + var service = + new AccountJwtSignerMaterializationService( + desired, + new AccountJwtReadinessProbeRepository( + context.dsl(), + desired, + new AccountJwtJwksPublicationRepository(context.dsl(), desired)), + provider, + new DataSourceTransactionManager(context.dataSource())); + PublicJwk key = publicJwk(request.targetKid()); + var rpcRequest = + RecordGenerationResultRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(request.operationId().toString()) + .setGenerationRequestDigest(observed.generationRequestDigest()) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion("12") + .setObservedResourceVersion("13") + .setPublicJwkJson(key.json()) + .build(); + boolean[] delivered = {false}; + boolean[] completed = {false}; + Status.Code[] error = {null}; + StreamObserver response = + new StreamObserver<>() { + @Override + public void onNext(RecordGenerationResultResponse value) { + delivered[0] = true; + } + + @Override + public void onError(Throwable failure) { + error[0] = Status.fromThrowable(failure).getCode(); + } + + @Override + public void onCompleted() { + completed[0] = true; + } + }; + @SuppressWarnings("unchecked") + ServerCall call = mock(ServerCall.class); + SSLSession session = mock(SSLSession.class); + var certificate = mock(java.security.cert.X509Certificate.class); + var publicKey = mock(java.security.PublicKey.class); + when(publicKey.getEncoded()).thenReturn(peerSpki); + when(certificate.getPublicKey()).thenReturn(publicKey); + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, peerUri))); + when(session.getPeerCertificates()) + .thenReturn(new java.security.cert.Certificate[] {certificate}); + when(call.getAttributes()) + .thenReturn(Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, session).build()); + new AccountJwtSignerMaterializerTlsInterceptor(provider) + .interceptCall( + call, + new Metadata(), + (intercepted, headers) -> { + service.recordGenerationResult(rpcRequest, response); + return new ServerCall.Listener<>() {}; + }); + assertThat(error[0]).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(delivered[0]).isFalse(); + assertThat(completed[0]).isFalse(); + verify(provider, times(3)).current(); + assertThat(count(context, "account_jwt_signer_generation_results")).isZero(); + assertThat(count(context, "account_jwt_signer_secret_observations")).isEqualTo(1L); + assertThat(signerRow(context, "account_jwt_signer_desired_states")).isEqualTo(retainedState); + // The same exact receipt can still be recorded after the rolled-back attempt. + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + initialTrust, + request.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + key.json())); + assertThat(count(context, "account_jwt_signer_generation_results")).isEqualTo(1L); + } + + private static String signerRow(TestContext context, String table) { + return java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull( + context + .dsl() + .fetchOne("SELECT to_jsonb(retained)::text FROM " + table + " AS retained")) + .get(0, String.class)); + } + + private static String signerSqlState(Throwable failure) { + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current instanceof java.sql.SQLException sqlFailure) { + return sqlFailure.getSQLState(); + } + } + return null; + } + + private static int insertSignerRow( + TestContext context, String table, String row, String patchSql, Object... patchValues) { + Object[] bindings = new Object[patchValues.length + 1]; + bindings[0] = row; + System.arraycopy(patchValues, 0, bindings, 1, patchValues.length); + return context + .dsl() + .execute( + "INSERT INTO " + + table + + " SELECT * FROM jsonb_populate_record(NULL::" + + table + + ", ?::jsonb || " + + patchSql + + ")", + bindings); + } + private TestContext newTestContext(String targetVersion) { String schema = SCHEMA_PREFIX + "_" + UUID.randomUUID().toString().replace("-", ""); schemas.add(schema); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java index 3c17f45f4b..2b24d9de14 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java @@ -15,6 +15,7 @@ import java.security.KeyPairGenerator; import java.security.MessageDigest; import java.security.interfaces.RSAPublicKey; +import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.util.Base64; @@ -26,12 +27,18 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding; import net.firedevops.firemud.accountservice.config.AccountJwtReadinessTrustBinding.PeerIdentity; import net.firedevops.firemud.accountservice.config.AccountJwtValidatorInventoryBinding.ProfileExpectation; import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository; +import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.DeliveryClaim; import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ExpectedPod; import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeEntry; import net.firedevops.firemud.accountservice.repository.AccountJwtReadinessProbeRepository.ProbeState; @@ -61,6 +68,7 @@ import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; @@ -1077,6 +1085,7 @@ void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart( .isEqualTo(proof.readinessEvidenceDigest()); byte[] exactPreimage = proof.readinessEvidencePreimage(); + assertIndependentPartialPromotionInsertsRejected(context, owner, proof, exactPreimage); assertThatThrownBy( () -> insertDirectPromotion(context, owner, proof, "0".repeat(64), exactPreimage)) .satisfies( @@ -1367,6 +1376,368 @@ context, owner, proof, sha256(changedPreimage), changedPreimage)) "account_jwt_readiness_delivery_claims")); } + @Test + void producerFailureRetainsCompleteV2AbortedEvidenceWithoutRedeliveryOrReclaim() + throws Exception { + TestContext context = newTestContext(null); + OwnerState owner = createOwnerState(context); + ObservationContext observationContext = + inTransaction( + context, + () -> owner.readiness().readCurrentInventoryObservationContext(BINDING, owner.trust())); + long now = databaseNow(context); + Instant plannedAt = + Instant.ofEpochSecond( + now + - AccountJwtReadinessProbeRepository.MAX_VALIDATOR_CACHE_AGE_SECONDS + - AccountJwtReadinessProbeRepository.PROBE_LIFETIME_SECONDS + + BULK_READINESS_PLAN_HEADROOM_SECONDS); + InventorySnapshot planningInventory = completeInventorySnapshot(plannedAt, observationContext); + ReadinessProbePlan plan = + inTransaction( + context, + () -> + owner + .readiness() + .planCurrent(BINDING, owner.trust(), plannedAt, planningInventory)); + assertThat(plan.planVersion()).isEqualTo(2); + assertThat(plan.validatorInventoryComplete()).isTrue(); + assertThat(plan.entries()).hasSize(8); + assertThat(count(context, "account_jwt_readiness_validator_pods")).isEqualTo(12L); + InventorySnapshot refreshedInventory = + completeInventorySnapshot(Instant.ofEpochSecond(now), observationContext); + assertThat(refreshedInventory.digest()).isEqualTo(planningInventory.digest()); + + Path privateMount = Files.createDirectory(tempDirectory.resolve("failure-private-mount")); + Path publicMount = Files.createDirectory(tempDirectory.resolve("failure-public-mount")); + Files.writeString( + privateMount.resolve("pending.key"), + privateBundleJson(owner.request(), owner.result(), owner.keyPair())); + Files.writeString(publicMount.resolve("jwks.json"), owner.desiredJwks()); + var early = + new AccountJwtReadinessProbeService( + owner.readiness(), + context.transaction(), + Clock.fixed( + Instant.ofEpochSecond(plan.notBeforeEpochSecond() - 1), java.time.ZoneOffset.UTC), + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json")); + assertThatThrownBy( + () -> early.issueCurrentPlan(BINDING, owner.trust(), plan.operationId(), null, null)) + .isInstanceOf(AccountJwtReadinessProbeRepository.CacheAgeNotElapsedException.class); + var future = + new AccountJwtReadinessProbeService( + owner.readiness(), + context.transaction(), + Clock.fixed( + Instant.ofEpochSecond(plan.expiresAtEpochSecond()), java.time.ZoneOffset.UTC), + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json")); + assertThat(databaseClockNow(context)).isLessThan(plan.expiresAtEpochSecond()); + assertThatThrownBy( + () -> future.issueCurrentPlan(BINDING, owner.trust(), plan.operationId(), null, null)) + .isInstanceOf(DataAccessException.class); + assertThat( + inTransaction( + context, + () -> + owner.readiness().readCurrentPlan(BINDING, owner.trust(), plan.operationId()))) + .isEqualTo(plan); + assertThat(plan.entries()) + .allSatisfy( + entry -> { + assertThat(entry.state()).isEqualTo(ProbeState.PLANNED); + assertThat(entry.signingAttemptedAtEpochSecond()).isEmpty(); + assertThat(entry.compactTokenSha256()).isEmpty(); + }); + assertThat(count(context, "account_jwt_readiness_delivery_claims")).isZero(); + + var harnessBinding = deliveryHarnessBinding(plan.expiresAtEpochSecond() + 600); + PeerIdentity peer = new PeerIdentity(harnessBinding.expectedPeerUri(), "f".repeat(64)); + DeliveryClaim claim = + raceForSingleV2DeliveryClaim(context, owner, plan, harnessBinding, peer, now); + assertThat(count(context, "account_jwt_readiness_delivery_claims")).isEqualTo(1L); + var producer = + new AccountJwtReadinessProbeService( + owner.readiness(), + context.transaction(), + Clock.fixed(Instant.ofEpochSecond(now), java.time.ZoneOffset.UTC), + privateMount, + Path.of("pending.key"), + publicMount, + Path.of("jwks.json")); + Map transientBytes = new LinkedHashMap<>(); + Map verifiedBeforeFailure = new LinkedHashMap<>(); + int[] deliveries = {0}; + long[] podReceipts = {0}; + boolean[] verifiedInterruptionReached = {false}; + AccountJwtReadinessProbeService.OwnerInternalProbeDelivery delivery = + (metadata, compactJwt) -> { + deliveries[0]++; + assertThat(transientBytes.put(metadata.jti(), compactJwt)).isNull(); + assertThat(compactJwt).isNotEmpty(); + assertThat(sha256(compactJwt)).isEqualTo(metadata.compactTokenSha256()); + // A newly constructed reader sees committed ISSUED evidence before this callback. + var restarted = + new AccountJwtReadinessProbeRepository( + context.dsl(), owner.desired(), owner.publication(), owner.inventory()); + ProbeEntry issued = + inTransaction( + context, + () -> restarted.readCurrentPlan(BINDING, owner.trust(), plan.operationId())) + .entries() + .stream() + .filter(entry -> entry.jti().equals(metadata.jti())) + .findFirst() + .orElseThrow(); + assertThat(issued.state()).isEqualTo(ProbeState.ISSUED); + assertThat(issued.entryVersion()).isEqualTo(metadata.entryVersion()); + assertThat(issued.compactTokenSha256()).contains(metadata.compactTokenSha256()); + List pods = + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentExpectedPods( + BINDING, owner.trust(), issued, refreshedInventory)); + ProbeEntry observed = issued; + for (ExpectedPod pod : pods) { + ProbeEntry current = observed; + AuthenticatedAcceptance acceptance = testAcceptance(current, pod, databaseNow(context)); + observed = + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + current, + pod, + acceptance, + refreshedInventory)); + podReceipts[0]++; + } + assertThat(observed.state()).isEqualTo(ProbeState.VERIFIED); + assertThat(observed.verificationReceipt()).isPresent(); + assertThat(observed.verificationReceipt().orElseThrow().receiptVersion()).isEqualTo(2); + assertThat(observed.verificationReceipt().orElseThrow().podReceiptCount()) + .isEqualTo(pods.size()); + verifiedBeforeFailure.put(metadata.jti(), observed); + if (deliveries[0] == plan.entries().size()) { + ReadinessProbePlan verifiedReadback = + inTransaction( + context, + () -> restarted.readCurrentPlan(BINDING, owner.trust(), plan.operationId())); + assertThat(verifiedReadback.entries()) + .hasSize(8) + .allSatisfy( + entry -> { + assertThat(entry.state()).isEqualTo(ProbeState.VERIFIED); + assertThat(entry).isEqualTo(verifiedBeforeFailure.get(entry.jti())); + }); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(12L); + verifiedInterruptionReached[0] = true; + throw new IllegalStateException( + "controlled interruption after verified observation: " + + new String(compactJwt, StandardCharsets.US_ASCII)); + } + }; + assertThatThrownBy( + () -> + producer.issueCurrentPlan( + BINDING, owner.trust(), plan.operationId(), claim, delivery)) + .satisfies( + failure -> + assertThat(verifiedInterruptionReached[0]) + .as( + "the controlled interruption follows durable verification of all eight probes") + .isTrue()) + // The mounted signer sanitizes callback RuntimeExceptions, including the producer's + // delivery-quarantine exception, rather than exposing callback details or credentials. + .isInstanceOf(AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class) + .hasMessage("Mounted signer correspondence is unavailable or invalid") + .hasNoCause() + .satisfies(failure -> assertThat(failure.getSuppressed()).isEmpty()); + assertThat(deliveries[0]).isEqualTo(8); + assertThat(podReceipts[0]).isEqualTo(12L); + assertThat(transientBytes.values()) + .allSatisfy(bytes -> assertThat(bytes).containsOnly((byte) 0)); + ReadinessProbePlan cleanedPlan = + inTransaction( + context, + () -> owner.readiness().readCurrentPlan(BINDING, owner.trust(), plan.operationId())); + List cleaned = cleanedPlan.entries(); + assertThat(cleaned) + .hasSize(8) + .allSatisfy( + entry -> { + ProbeEntry verified = + java.util.Objects.requireNonNull( + verifiedBeforeFailure.get(entry.jti()), + "Every cleaned entry must retain its independently observed V2 receipt"); + assertThat(entry.state()).isEqualTo(ProbeState.CLEANED); + assertThat(entry.terminalOutcome()).contains("ABORTED"); + assertThat(entry.compactTokenSha256()).isEqualTo(verified.compactTokenSha256()); + assertThat(entry.signingAttemptedAtEpochSecond()) + .isEqualTo(verified.signingAttemptedAtEpochSecond()); + assertThat(entry.verificationReceipt()).isEqualTo(verified.verificationReceipt()); + }); + assertThat( + producer.issueCurrentPlan(BINDING, owner.trust(), plan.operationId(), claim, delivery)) + .isEqualTo(cleaned); + assertThat(deliveries[0]).isEqualTo(8); + assertThat(producer.abortCurrentPlan(BINDING, owner.trust(), plan.operationId())).isEmpty(); + assertThat( + inTransaction( + context, + () -> + owner.readiness().readCurrentPlan(BINDING, owner.trust(), plan.operationId()))) + .isEqualTo(cleanedPlan); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_readiness_probe_entries SET state = 'VERIFIED', " + + "entry_version = entry_version + 1 WHERE rotation_operation_id = ?", + plan.operationId()))) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .claimSingleDelivery( + BINDING, + owner.trust(), + cleanedPlan, + harnessBinding, + peer, + Instant.ofEpochSecond(now)))) + .isInstanceOf(AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException.class); + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + owner + .readiness() + .claimSingleDelivery( + BINDING, + owner.trust(), + plan, + harnessBinding, + peer, + Instant.ofEpochSecond(now)))) + .isInstanceOf(AccountJwtReadinessProbeRepository.StaleOperationException.class); + assertThat( + inTransaction( + context, + () -> + owner.readiness().readCurrentPlan(BINDING, owner.trust(), plan.operationId()))) + .isEqualTo(cleanedPlan); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(1L); + assertThat(count(context, "account_jwt_readiness_probe_entries")).isEqualTo(8L); + assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(12L); + assertThat(count(context, "account_jwt_readiness_delivery_claims")).isEqualTo(1L); + } + + private static AccountJwtReadinessTrustBinding.Binding deliveryHarnessBinding(long validUntil) { + String uri = "spiffe://firemud/ns/" + BINDING.namespace() + "/sa/account-jwt-readiness-harness"; + List pins = List.of("f".repeat(64)); + String instanceId = "account-harness-failure-test"; + String revision = "readiness-r1"; + String digest = + AccountJwtReadinessTrustBinding.computeBindingDigest( + revision, + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + uri, + pins, + instanceId, + validUntil); + return new AccountJwtReadinessTrustBinding.Binding( + BINDING.environmentId(), + BINDING.clusterId(), + BINDING.namespace(), + CLUSTER_UID, + NAMESPACE_UID, + uri, + pins, + revision, + "account-service", + instanceId, + validUntil, + digest); + } + + private static DeliveryClaim raceForSingleV2DeliveryClaim( + TestContext context, + OwnerState owner, + ReadinessProbePlan plan, + AccountJwtReadinessTrustBinding.Binding harnessBinding, + PeerIdentity peer, + long now) + throws Exception { + var contenders = Executors.newFixedThreadPool(2); + CyclicBarrier start = new CyclicBarrier(2); + try { + java.util.concurrent.Callable attempt = + () -> { + start.await(30, TimeUnit.SECONDS); + return inTransaction( + context, + () -> + owner + .readiness() + .claimSingleDelivery( + BINDING, + owner.trust(), + plan, + harnessBinding, + peer, + Instant.ofEpochSecond(now))); + }; + List> attempts = + List.of(contenders.submit(attempt), contenders.submit(attempt)); + DeliveryClaim winner = null; + int refused = 0; + for (Future result : attempts) { + try { + DeliveryClaim claim = result.get(30, TimeUnit.SECONDS); + assertThat(winner).isNull(); + winner = claim; + } catch (ExecutionException failure) { + assertThat(failure.getCause()) + .isInstanceOf( + AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException.class); + refused++; + } + } + assertThat(winner).isNotNull(); + assertThat(refused).isEqualTo(1); + return java.util.Objects.requireNonNull(winner); + } finally { + contenders.shutdownNow(); + assertThat(contenders.awaitTermination(30, TimeUnit.SECONDS)).isTrue(); + } + } + private static long completeRemainingProbes( TestContext context, OwnerState owner, @@ -1462,6 +1833,94 @@ private static long completeRemainingProbes( return expectedPodReceiptCount; } + private static void assertIndependentPartialPromotionInsertsRejected( + TestContext context, + OwnerState owner, + AccountJwtReadinessProbeRepository.ReadinessPromotionProof proof, + byte[] exactPreimage) { + // Derive the template from the current complete V2 inventory and all twelve Pod receipts, + // not from the donor's obsolete partial-inventory promotion fixture. + String validRow = + context + .transaction() + .execute( + status -> { + insertDirectPromotionInCurrentTransaction( + context, + owner, + proof, + UUID.randomUUID(), + proof.readinessEvidenceDigest(), + exactPreimage); + String row = + java.util.Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT to_jsonb(promotion)::text FROM account_jwt_signer_promotion_operations AS promotion")) + .get(0, String.class); + assertThat(count(context, "account_jwt_signer_promotion_operations")) + .isEqualTo(1L); + status.setRollbackOnly(); + return row; + }); + assertThat(validRow).isNotNull(); + for (String field : + List.of( + "materializer_trust_binding_digest", + "api_config_revision", + "expected_public_config_map_uid")) { + for (boolean explicitNull : new boolean[] {false, true}) { + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_promotion_operations SELECT * FROM " + + "jsonb_populate_record(NULL::account_jwt_signer_promotion_operations, " + + (explicitNull + ? "?::jsonb || jsonb_build_object(?, NULL)" + : "?::jsonb - ?::text") + + ")", + validRow, + field))) + .as("independent promotion INSERT with %s %s", explicitNull ? "null" : "missing", field) + .isInstanceOf(DataAccessException.class) + .satisfies(failure -> assertThat(postgresSqlState(failure)).isEqualTo("23514")); + assertThat(count(context, "account_jwt_signer_promotion_operations")).isZero(); + } + } + for (String field : + List.of( + "materializer_trust_binding_digest", + "api_binding_digest", + "expected_private_secret_resource_version", + "expected_public_jwks_resource_version")) { + String invalid = field.endsWith("resource_version") ? "r\n" : "not-a-sha256"; + assertThatThrownBy( + () -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_promotion_operations SELECT * FROM " + + "jsonb_populate_record(NULL::account_jwt_signer_promotion_operations, " + + "?::jsonb || jsonb_build_object(?, ?))", + validRow, + field, + invalid))) + .as("independent malformed promotion INSERT: %s", field) + .isInstanceOf(DataAccessException.class) + .satisfies(failure -> assertThat(postgresSqlState(failure)).isEqualTo("23514")); + assertThat(count(context, "account_jwt_signer_promotion_operations")).isZero(); + } + } + private static void insertDirectPromotion( TestContext context, OwnerState owner,