From 9dfeef50a129f1b75bc0cad1199ed4d4d9612870 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 17:54:47 +1300 Subject: [PATCH 01/10] Prepare exact Logging authorization receiving and durable handoff --- ...dmin-as-external-operator-write-ingress.md | 2 + .../logging-admin-service/api-contracts.md | 4 +- ...ame-authoring-publishing-and-activation.md | 2 + .../logging-admin-service/build.gradle.kts | 1 + .../client/GameSessionClient.java | 11 + ...artSessionOperatorAuthorizationClient.java | 40 +- ...ionOperatorAuthorizationConfiguration.java | 5 +- .../StartSessionAuthorizationCoordinator.java | 654 ++++++++++- .../client/GameSessionClientTest.java | 49 +- ...onOperatorAuthorizationClientMtlsTest.java | 1034 +++++++++++++++++ ...essionOperatorAuthorizationClientTest.java | 74 +- ...rtSessionAuthorizationCoordinatorTest.java | 604 ++++++++-- 12 files changed, 2310 insertions(+), 170 deletions(-) create mode 100644 services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 2acaf0ac1e..48e32aef72 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -8,6 +8,8 @@ Accepted This ADR is partially implemented. Logging & Admin has current operator-facing read, investigation, admission-pointer read/audit, and prepared-upgrade proof-read surfaces, but no forwarded owner mutation family is currently supported as an executable external route until its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus owner-side redemption exist. The service-local `/moderation/actions` and `ApplyModerationAction` paths are present legacy transport stubs that now hard fail closed after their narrow tenant/admin checks: HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They have no external Gateway route, persist no separate fixed-category audit evidence, and perform no owner-side enforcement. The target Logging & Admin-owned moderation policy-input/audit path remains gated pending Account authorization-reference issuance plus Logging & Admin receiving-service validation/redemption; it does not require domain-owner redemption. The live `EvaluateModerationPolicy` read remains available only to its internal enforcement owners. Versioned policy propagation and owner enforcement remain target-state work. +The provisional original StartSession receiving candidate retains Account-returned tuple bytes through Logging completion, independent exact authorization readback and the one-time owner-pending handoff. Missing or substituted evidence and ambiguous transport or durable transitions fail closed; the coordinator and clients reject ambient SQL transactions or synchronization. The disabled-by-default composition, passive production reservation owner and absence of a routable StartSession ingress remain in force. The isolated candidate passes the complete local Logging check: 272 unit cases and 25 PostgreSQL/service integration cases, with zero failures, errors or skips. Eight unit-task cases use actual loopback mTLS against an explicitly synthetic Account handler; coordinator transition/readback cases use controlled owner doubles. These qualify their exercised receiving, transport and storage boundaries only. The intended receiving parent after the reconstructed Entity PRESEEDED boundary has not yet been materialized, so qualification on that parent remains pending. This source preparation supplies no genuine producer, activation or operational-region proof. + ## Decision Record - Decision date: 2026-07-19 diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 39101efd31..0e48888d45 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -12,6 +12,8 @@ Implementation status: the claim-evidence receiver and Account read client exist When enabled, the Spring composition requires the configured canonical workload namespace and readable file-backed client mTLS inputs, initializes the typed Account client through the managed bean lifecycle, and connects it to the existing durable reservation service. The configuration supplies no reservation or authority source and exposes no external route. Its context test uses a controlled channel factory and test-only placeholder TLS files; it does not prove physical mTLS, production service startup, remote Account availability, or execution through Game Session launch selection and World activation. The target authorization and owner-forwarding rules remain owned by [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) and [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md). +Before completing an original StartSession reservation, Logging & Admin compares the complete Account-returned tuple with its exact reserved operation and validated response, persists those unchanged Account bytes, and independently reads back the same durable authorization before advancing the one-time owner handoff. Exact retries may observe secret-free durable state but never return another transient reference or dispatch again. Ambiguous Account calls, local completion, readback, or owner-pending transitions remain pending with no automatic replacement issuance or rearming. ISSUE, RECOVER, and owner forwarding require no ambient SQL transaction or synchronization. The [Account authorization-reference contract](../account-service/api-contracts.md#operator-authorization-references) owns original tuple and capture-reference binding; this local receiving boundary does not activate operator ingress or replace Account current-authority and expiry decisions. + ## Account Audit Ingress and Receipt The canonical Account-to-Logging & Admin audit ingress is the existing `logging_admin.v1.LoggingAdminService/CreateLogEvent` RPC, converged in place rather than duplicated as a parallel ingress. It is a non-destructive internal service RPC, not an operator/admin mutation. Account is the producer and source authority for account state; Logging & Admin owns the receiver-side audit envelope, durable receipt/readback, deduplication, and audit projection. The audit ingress follows only shared envelope fundamentals (stable identity, event type/schema, producer occurrence time, and at-least-once/idempotent delivery) from [Session Behavior](../../system-architecture-session-behavior.md); it does **not** inherit that document's membership-specific field set or `eventDigest` grammar. Internal workload identity and method authorization follow [Authentication](../../system-architecture-authentication.md) and [gRPC](../../system-architecture-grpc.md#tls-requirements). @@ -113,8 +115,6 @@ The implementation gap is fail-closed: the HTTP controller and Gateway route are The source-level `StartSessionAuthorizationCoordinator` now offers separate `issueHumanAndDispatch` and `recoverAndDispatch` methods that compose its existing authorization/recovery flow with `GameSessionClient`. They call the owner once only when that invocation wins the durable `OWNER_EXECUTION_PENDING` transition; exact/in-progress and recovery-unavailable results do not dispatch, and ambiguous owner outcomes propagate without automatic retry or rearming. The existing `issueHuman` and `recover` methods remain prepare-only. The typed `GameSessionClient` call sends the transient post-authorization tuple/reference and validates Game Session's secret-free durable attempt/progress echo; it requires readable file-backed workload mTLS and pins both request and response to the exact same-namespace Game Session SPIFFE URI derived from the tuple. Ping and stop keep their existing client behavior. These methods are not wired to a routable Logging & Admin StartSession ingress. Mocked tests do not establish physical mTLS, production ingress, prepared launch selection, or instance activation. -The Account client accepts the new StartSession response only after comparing its complete returned owner tuple with the exact reservation and response evidence. The coordinator retains and hands off the Account-returned tuple bytes through the existing completion/recovery path, under [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md). Missing or substituted owner evidence fails closed before durable completion or owner dispatch; this does not activate a routable ingress. - **Target ADR 0047/0048 owner-forwarding path:** [ADR 0047](../../decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md) owns the Logging & Admin ingress and Account-reference issuance boundary; [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) owns the phase-qualified execution, redemption, and reconciliation contract. Supported executable operator mutations use Account's canonical [`IssueHumanOperatorAuthorizationReference`](../account-service/api-contracts.md#operator-authorization-references) issuance RPC after Logging & Admin authenticates the current `control-ui` actor and records durable intent. Logging & Admin forwards the opaque bounded reference and unchanged request/generation binding; the authoritative receiving owner recomputes the canonical digest and is the only service that calls Account's `RedeemOperatorAuthorization` RPC. Unattended automation uses Account's `IssueAutomationOperatorAuthorizationReference` with `exact_mtls_workload_plus_versioned_automation_policy`, bound to the exact Logging and Admin workload mTLS identity and current `automation_policy_id`/`automation_policy_version`; the currently supported automation branch is tenant-scoped only and carries the exact target `tenant_generation` through issuance, forwarding, redemption, and owner commit. It carries no human identity, end-user token, or `privileged_control` authority. For each owner contract, predicate evidence comes exclusively from Account's redemption response; any copy forwarded by Logging & Admin is unchanged audit/context evidence, not authority. The local `/moderation/actions` policy-input/audit mutation is a separate receiving-service path: after its gate exists, Logging & Admin redeems its one Account reference exactly once for local persistence and never forwards or reuses that reference. Any future moderation owner-enforcement command uses a separately issued command-bound reference redeemed exactly once by the receiving owner. The moderation route is currently gated/unavailable; it hard fails closed without dispatch or persistence and performs no target fixed-category policy/audit persistence or forwarding. `EvaluateModerationPolicy` is a live read and carries no mutation authorization reference. For non-moderation action families, the request identity is the exact `controlPlaneRequestId` plus digest pair. Moderation and appeal transports instead use dedicated `policyIntentRequestId`, `ownerEnforcementRequestId`, and stable appeal-submission request identities end-to-end; `controlPlaneRequestId` remains a separate correlation-only field and must not carry, replace, alias, or serve as any of those mutation identities. The dedicated identities are never shared or reused. Logging & Admin never becomes a second authorization authority. Current feature-flag and tick forwarding paths, plus internal admission control-plane implementations, are not evidence that this ADR 0048 target contract is complete. For every forwarded owner mutation, excluding the separate local `/moderation/actions` policy-input/audit path, the authoritative owner calls Account's `RedeemOperatorAuthorization` with the separately issued opaque reference and its independently derived request binding. Authorization predicates and generation authority come exclusively from that Account response. Any predicate, generation, checkpoint, or assurance copies forwarded by Logging & Admin are unchanged audit/context evidence only; the owner must not authorize or mutate from those copies, and they are excluded from the canonical `mutationDigest/v1`, which covers the normalized action request rather than ingress assertions. The local moderation route is gated/unavailable; it hard fails closed without dispatch or persistence and does not persist target fixed-category policy/audit evidence, redeem, forward, or enforce. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 2be505dccf..1bcf4bcdea 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,6 +6,8 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +A provisional Logging authorization receiving candidate is prepared on published parent #3125 at `1b89f28e82ecdae237a9cb71d9324cb5e3437103`. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The complete local Logging check passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. The intended receiving parent after the reconstructed Entity PRESEEDED boundary is unavailable; this candidate is neither published nor qualified on that parent. Account V164 receiving repair remains a separate source-carrier checkpoint. All genuine handoffs and broader Unit 1B remain held. + At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved. This tracker consolidates Game Design authoring, settings, publication, release admission, and activation by capability. The live implementation is strongest in control-plane publication, release attestation, launch preflight, and the first typed World authoring handoff; broader creator/editor UX and downstream ownership synchronization remain incomplete. diff --git a/services/logging-admin-service/build.gradle.kts b/services/logging-admin-service/build.gradle.kts index c3da9c94a7..39b564782a 100644 --- a/services/logging-admin-service/build.gradle.kts +++ b/services/logging-admin-service/build.gradle.kts @@ -13,6 +13,7 @@ firemudJooq { } dependencies { + testImplementation(testFixtures(project(":common-platform-core"))) testImplementation(libs.grpc.inprocess) testImplementation(libs.grpc.netty.shaded) testImplementation(testFixtures(project(":logging-admin-service"))) diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java index bfbbd87dd8..1c9e8c30eb 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionClient.java @@ -29,6 +29,7 @@ import net.firedevops.firemud.gamesession.v1.StopSessionResponse; import net.firedevops.firemud.loggingadmin.operator.StartSessionAuthorizationCoordinator.TransientOwnerExecutionHandoff; import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** gRPC client for communicating with the Game Session Service. */ @Component @@ -91,12 +92,14 @@ public StopSessionResponse stopSession(long sessionId) { */ public StartSessionOwnerHandoffResult authorizeStartSession( TransientOwnerExecutionHandoff handoff) { + requireNoAmbientSqlOrSynchronization(); Objects.requireNonNull(handoff, "durable Logging owner handoff is required"); StartSessionPostAuthorizationExecutionTuple tuple = handoff.postAuthorizationTuple(); String reference = handoff.accountResponse().operatorAuthorizationReference(); byte[] tupleBytes = tuple.canonicalBytes(); if (tupleBytes.length == 0 || tupleBytes.length > StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + || reference == null || !OPAQUE_OPERATOR_REFERENCE.matcher(reference).matches() || !tuple .authenticatedWorkloadIdentity() @@ -138,6 +141,14 @@ public StartSessionOwnerHandoffResult authorizeStartSession( return validateOwnerHandoffResponse(tuple, response); } + private static void requireNoAmbientSqlOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Game Session owner handoff requires no ambient SQL or synchronization"); + } + } + private void requireFileBackedMtls() { FileBackedGrpcMtlsPolicy.require( transportTlsProperties, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java index 22eca3e89a..66aa5e8e7a 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java @@ -6,6 +6,7 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Clock; +import java.time.Duration; import java.time.Instant; import java.util.Objects; import java.util.UUID; @@ -31,6 +32,7 @@ import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Explicitly initialized, typed Logging & Admin client for Account's StartSession issue/recover @@ -42,6 +44,12 @@ public class StartSessionOperatorAuthorizationClient StartSessionOperatorAuthorizationServiceGrpc .StartSessionOperatorAuthorizationServiceBlockingStub> { private static final int MAX_TUPLE_BYTES = 8 * 1_024; + private static final int MAX_REQUEST_BYTES = MAX_TUPLE_BYTES + 16 * 1_024 + 1_024; + private static final int MAX_RESPONSE_BYTES = + StartSessionAuthorityEvidenceBundle.MAX_BUNDLE_BYTES + + StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + + 2_048; + private static final Duration MAX_REFERENCE_LIFETIME = Duration.ofMinutes(5); private static final int MAX_CONTROL_UI_TOKEN_BYTES = 16 * 1_024; private static final int MAX_REFERENCE_BYTES = 128; private static final long RPC_DEADLINE_SECONDS = 5L; @@ -109,6 +117,8 @@ protected String defaultTarget() { buildStub(io.grpc.ManagedChannel channel) { return applyStubCustomizer( StartSessionOperatorAuthorizationServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize(MAX_RESPONSE_BYTES) + .withMaxOutboundMessageSize(MAX_REQUEST_BYTES) .withCompression("gzip")); } @@ -120,6 +130,7 @@ public AuthorizationReference issueHuman( long reservationClaimFence, UUID currentClaimOwnerId, long currentClaimFence) { + requireNoAmbientSqlOrSynchronization(); byte[] tupleBytes = canonicalTupleBytes(tuple); requireVisibleAsciiToken(controlUiJwt); requireOwnerFence(reservationOwnerId, reservationClaimFence, "reservation owner"); @@ -133,10 +144,17 @@ public AuthorizationReference issueHuman( .setCurrentClaimOwnerId(currentClaimOwnerId.toString()) .setCurrentClaimFence(currentClaimFence) .build(); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException( + "Account authorization request exceeds its supported bound"); + } IssueHumanOperatorAuthorizationReferenceResponse response = requirePinnedAccountStub(tuple.action().scope().targetNamespace()) .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) .issueHumanOperatorAuthorizationReference(request); + if (response == null || response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw malformedResponse(); + } return validateResponse( response.getOperatorAuthorizationReference(), response.getAuthorizationReferenceFingerprint(), @@ -160,6 +178,7 @@ public AuthorizationReference recover( long reservationClaimFence, UUID currentClaimOwnerId, long currentClaimFence) { + requireNoAmbientSqlOrSynchronization(); byte[] tupleBytes = canonicalTupleBytes(tuple); requireOwnerFence(reservationOwnerId, reservationClaimFence, "reservation owner"); requireOwnerFence(currentClaimOwnerId, currentClaimFence, "current claim owner"); @@ -171,10 +190,17 @@ public AuthorizationReference recover( .setCurrentClaimOwnerId(currentClaimOwnerId.toString()) .setCurrentClaimFence(currentClaimFence) .build(); + if (request.getSerializedSize() > MAX_REQUEST_BYTES) { + throw new IllegalArgumentException( + "Account authorization request exceeds its supported bound"); + } RecoverOperatorAuthorizationReferenceResponse response = requirePinnedAccountStub(tuple.action().scope().targetNamespace()) .withDeadlineAfter(RPC_DEADLINE_SECONDS, TimeUnit.SECONDS) .recoverOperatorAuthorizationReference(request); + if (response == null || response.getSerializedSize() > MAX_RESPONSE_BYTES) { + throw malformedResponse(); + } return validateResponse( response.getOperatorAuthorizationReference(), response.getAuthorizationReferenceFingerprint(), @@ -255,9 +281,13 @@ private AuthorizationReference validateResponse( throw malformedResponse(); } Instant expiresAt = exactExpiry(expiryTimestamp); - if (!expiresAt.isAfter(clock.instant())) { + Instant now = clock.instant(); + if (!expiresAt.isAfter(now)) { throw new IllegalStateException("Account authorization response is expired"); } + if (expiresAt.isAfter(now.plus(MAX_REFERENCE_LIFETIME))) { + throw malformedResponse(); + } StartSessionAuthorityEvidenceBundle bundle = StartSessionAuthorityEvidenceBundle.decode(authorityEvidenceBundle); bundle.requireTupleBinding(tuple); @@ -348,6 +378,14 @@ private static void requireVisibleAsciiToken(String token) { } } + private static void requireNoAmbientSqlOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account authorization requires no ambient SQL or synchronization"); + } + } + private static void requireOwnerFence(UUID owner, long fence, String field) { if (owner == null || owner.equals(new UUID(0L, 0L)) || fence <= 0L) { throw new IllegalArgumentException(field + " and positive fence are required"); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java index 53bcb79115..22ad374853 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfiguration.java @@ -58,7 +58,8 @@ public StartSessionOperatorAuthorizationClient startSessionOperatorAuthorization @Bean public StartSessionAuthorizationCoordinator startSessionAuthorizationCoordinator( StartSessionPreAuthorizationReservationService reservations, - StartSessionOperatorAuthorizationClient accountClient) { - return new StartSessionAuthorizationCoordinator(reservations, accountClient); + StartSessionOperatorAuthorizationClient accountClient, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new StartSessionAuthorizationCoordinator(workloadNamespace, reservations, accountClient); } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java index 51a4282ad7..6b243be3df 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java @@ -1,21 +1,43 @@ package net.firedevops.firemud.loggingadmin.operator; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Base64; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.loggingadmin.client.GameSessionClient; import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient; import net.firedevops.firemud.loggingadmin.client.StartSessionOperatorAuthorizationClient.AuthorizationReference; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Acquisition; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizationCompletion; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.AuthorizedSnapshot; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimEvidence; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimHandle; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimPurpose; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.ClaimState; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionHandoff; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.OwnerExecutionTransition; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.PendingTransition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Phase; import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.RecoveryAcquisition; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.Snapshot; +import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; +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; /** * Coordinates Account authorization and durably records the owner handoff without activating an @@ -28,41 +50,118 @@ * logged here. */ public final class StartSessionAuthorizationCoordinator { + private static final int MAX_CONTROL_UI_JWT_BYTES = 16 * 1024; + private static final Pattern OPAQUE_REFERENCE = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final JsonMapper JWT_JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + private static final TypeReference> JSON_OBJECT = new TypeReference<>() {}; + + private final String configuredNamespace; private final StartSessionPreAuthorizationReservationService reservations; private final StartSessionOperatorAuthorizationClient accountClient; public StartSessionAuthorizationCoordinator( + String configuredNamespace, StartSessionPreAuthorizationReservationService reservations, StartSessionOperatorAuthorizationClient accountClient) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("A valid configured workload namespace is required"); + } + this.configuredNamespace = configuredNamespace; this.reservations = Objects.requireNonNull(reservations, "reservation service is required"); this.accountClient = Objects.requireNonNull(accountClient, "Account client is required"); } + /** Derives the original actor from the current authenticated tenant-admin request context. */ + public Result begin( + String controlPlaneRequestId, + StartSessionOperatorAction action, + String originalControlUiJwt) { + requireNoAmbientSqlOrSynchronization(); + Objects.requireNonNull(action, "typed StartSession action is required"); + String stableRequestId = + StartSessionPreAuthorizationReservationTuple.requireCanonicalControlPlaneRequestId( + controlPlaneRequestId); + requireConfiguredNamespace(action); + requireCompactJwtEnvelope(originalControlUiJwt); + // The verified Logging context binds the claimed original actor, but Account alone validates + // the forwarded ControlUI token's current authorization and signature. + StartSessionPreAuthorizationReservationTuple tuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + stableRequestId, action); + return issueHuman(tuple, originalControlUiJwt); + } + /** Begins human issuance only for the first reservation owner that wins AUTHORIZATION_PENDING. */ public Result issueHuman( StartSessionPreAuthorizationReservationTuple tuple, String controlUiJwt) { + requireNoAmbientSqlOrSynchronization(); Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + requireConfiguredNamespace(tuple.action()); + requireCompactJwtEnvelope(controlUiJwt); + StartSessionPreAuthorizationReservationTuple currentTuple = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + tuple.controlPlaneRequestId(), tuple.action()); + if (!currentTuple.canonicalJson().equals(tuple.canonicalJson())) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + return issueHumanFromCurrentContext(currentTuple, controlUiJwt); + } + + private Result issueHumanFromCurrentContext( + StartSessionPreAuthorizationReservationTuple tuple, String controlUiJwt) { Acquisition acquisition = reservations.acquire(tuple); + Snapshot acquiredSnapshot = acquisition.snapshot(); + requireSnapshotTuple(acquiredSnapshot, tuple); if (!acquisition.newlyAcquired()) { - return Result.alreadyInProgress(); + return observeExisting(tuple, acquiredSnapshot); } ClaimHandle claim = acquisition.claim(); - PendingTransition pending = reservations.markAuthorizationPending(claim); + if (claim == null || !claimMatchesOriginalReservation(claim, tuple)) { + return Result.outcomeUnknown(acquiredSnapshot, PendingReason.RESERVATION_CLAIM_MISMATCH); + } + + PendingTransition pending; + try { + pending = reservations.markAuthorizationPending(claim); + } catch (RuntimeException transitionFailure) { + return Result.outcomeUnknown( + acquiredSnapshot, PendingReason.PENDING_TRANSITION_OUTCOME_UNKNOWN); + } + if (pending == null || pending.snapshot() == null) { + return Result.outcomeUnknown( + acquiredSnapshot, PendingReason.PENDING_TRANSITION_OUTCOME_UNKNOWN); + } + Snapshot pendingSnapshot = pending.snapshot(); + requireSnapshotTuple(pendingSnapshot, tuple); if (!pending.mayDispatchAccountAuthorization()) { - return Result.alreadyInProgress(); + return observeExisting(tuple, pendingSnapshot); + } + if (!isExactPendingSnapshot(pendingSnapshot, tuple, claim)) { + return Result.outcomeUnknown( + pendingSnapshot, PendingReason.PENDING_TRANSITION_OUTCOME_UNKNOWN); } ClaimEvidence claimEvidence = claim.claimEvidence(); - AuthorizationReference accountResponse = - accountClient.issueHuman( - sharedTuple(tuple), - controlUiJwt, - claimEvidence.reservationOwnerId(), - claimEvidence.reservationClaimFence(), - claimEvidence.currentClaimOwnerId(), - claimEvidence.currentClaimFence()); - return persistExactAccountResponse(tuple, claim, accountResponse); + AuthorizationReference accountResponse; + try { + accountResponse = + accountClient.issueHuman( + sharedTuple(tuple), + controlUiJwt, + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence()); + } catch (RuntimeException ambiguousOrFailedCall) { + return Result.outcomeUnknown(pendingSnapshot, PendingReason.ACCOUNT_ISSUANCE_OUTCOME_UNKNOWN); + } + return persistExactAccountResponse(tuple, claim, accountResponse, pendingSnapshot); } /** Issues the human reference and forwards only this invocation's durable owner-pending win. */ @@ -76,22 +175,45 @@ public OwnerDispatchResult issueHumanAndDispatch( /** Recovers only the original issuance response under a fresh read-only recovery claim. */ public Result recover(StartSessionPreAuthorizationReservationTuple tuple) { + requireNoAmbientSqlOrSynchronization(); Objects.requireNonNull(tuple, "pre-authorization tuple is required"); + requireConfiguredNamespace(tuple.action()); Optional acquired = reservations.acquireAuthorizationRecoveryClaim(tuple); if (acquired.isEmpty()) { return Result.recoveryUnavailable(); } - ClaimHandle claim = acquired.orElseThrow().claim(); + RecoveryAcquisition recovery = acquired.orElseThrow(); + requireSnapshotTuple(recovery.snapshot(), tuple); + ClaimHandle claim = recovery.claim(); ClaimEvidence claimEvidence = claim.claimEvidence(); - AuthorizationReference accountResponse = - accountClient.recover( - sharedTuple(tuple), - claimEvidence.reservationOwnerId(), - claimEvidence.reservationClaimFence(), - claimEvidence.currentClaimOwnerId(), - claimEvidence.currentClaimFence()); - return persistExactAccountResponse(tuple, claim, accountResponse); + if (!claim.isRecoveryLookupOnly() + || !tuple.canonicalJson().equals(claim.tuple().canonicalJson()) + || !tuple.mutationDigest().equals(claim.mutationDigest()) + || recovery.snapshot().claimPurpose() != claim.purpose() + || recovery.snapshot().claimState() != ClaimState.ACTIVE + || recovery.snapshot().phase() != Phase.ACCOUNT_AUTHORIZATION + || recovery.snapshot().claimFence() != claimEvidence.currentClaimFence() + || recovery.snapshot().reservationClaimFence() != claimEvidence.reservationClaimFence() + || claimEvidence.reservationOwnerId().equals(claimEvidence.currentClaimOwnerId()) + || claimEvidence.currentClaimFence() <= claimEvidence.reservationClaimFence()) { + return Result.outcomeUnknown(recovery.snapshot(), PendingReason.RESERVATION_CLAIM_MISMATCH); + } + AuthorizationReference accountResponse; + try { + accountResponse = + accountClient.recover( + sharedTuple(tuple), + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + claimEvidence.currentClaimOwnerId(), + claimEvidence.currentClaimFence()); + } catch (RuntimeException ambiguousOrFailedCall) { + return Result.outcomeUnknown( + acquired.orElseThrow().snapshot(), PendingReason.ACCOUNT_RECOVERY_OUTCOME_UNKNOWN); + } + return persistExactAccountResponse( + tuple, claim, accountResponse, acquired.orElseThrow().snapshot()); } /** Recovers the original reference and forwards only a newly persisted owner-pending handoff. */ @@ -118,39 +240,372 @@ private static OwnerDispatchResult dispatchOwnerPending( private Result persistExactAccountResponse( StartSessionPreAuthorizationReservationTuple tuple, ClaimHandle claim, - AuthorizationReference accountResponse) { - Objects.requireNonNull(accountResponse, "validated Account response is required"); - StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple = - accountResponse.postAuthorizationTuple(); - ClaimEvidence claimEvidence = claim.claimEvidence(); - StartSessionPostAuthorizationExecutionTuple expectedTuple = - StartSessionPostAuthorizationExecutionTuple.createHuman( - sharedTuple(tuple), - accountResponse.authenticatedLoggingWorkloadIdentity(), - accountResponse.authorizationReferenceFingerprint(), - claimEvidence.reservationOwnerId(), - claimEvidence.reservationClaimFence(), - accountResponse.authorityEvidenceBundle(), - accountResponse.bundleReference()); - if (!MessageDigest.isEqual( - expectedTuple.canonicalBytes(), postAuthorizationTuple.canonicalBytes())) { - throw new IllegalArgumentException( - "Account post-authorization tuple differs from its authorization response"); + AuthorizationReference accountResponse, + Snapshot lastKnownSnapshot) { + StartSessionPostAuthorizationExecutionTuple postAuthorizationTuple; + String transientReference; + try { + if (accountResponse == null) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + transientReference = accountResponse.operatorAuthorizationReference(); + ClaimEvidence claimEvidence = claim.claimEvidence(); + if (transientReference == null || !OPAQUE_REFERENCE.matcher(transientReference).matches()) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + String expectedWorkloadIdentity = + "spiffe://firemud/ns/" + configuredNamespace + "/sa/logging-admin-service"; + if (!expectedWorkloadIdentity.equals( + accountResponse.authenticatedLoggingWorkloadIdentity())) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + StartSessionPostAuthorizationExecutionTuple expectedTuple = + StartSessionPostAuthorizationExecutionTuple.createHuman( + sharedTuple(tuple), + accountResponse.authenticatedLoggingWorkloadIdentity(), + accountResponse.authorizationReferenceFingerprint(), + claimEvidence.reservationOwnerId(), + claimEvidence.reservationClaimFence(), + accountResponse.authorityEvidenceBundle(), + accountResponse.bundleReference()); + postAuthorizationTuple = accountResponse.postAuthorizationTuple(); + if (postAuthorizationTuple == null + || !MessageDigest.isEqual( + expectedTuple.canonicalBytes(), postAuthorizationTuple.canonicalBytes()) + || !isExactAccountResult(tuple, claimEvidence, accountResponse, postAuthorizationTuple)) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + } catch (RuntimeException invalidResponse) { + return Result.outcomeUnknown(lastKnownSnapshot, PendingReason.ACCOUNT_RESPONSE_INVALID); + } + + AuthorizationCompletion completion; + try { + completion = reservations.completeAuthorization(claim, postAuthorizationTuple); + } catch (RuntimeException localCompletionFailure) { + return Result.outcomeUnknown( + lastKnownSnapshot, PendingReason.LOCAL_COMPLETION_OUTCOME_UNKNOWN); + } + if (completion == null || completion.snapshot() == null) { + return Result.outcomeUnknown( + lastKnownSnapshot, PendingReason.LOCAL_COMPLETION_OUTCOME_UNKNOWN); } - AuthorizationCompletion completion = - reservations.completeAuthorization(claim, postAuthorizationTuple); if (!completion.transitioned()) { - return Result.alreadyInProgress(); + return observeExisting(tuple, completion.snapshot().reservationSnapshot()); + } + ClaimEvidence claimEvidence = claim.claimEvidence(); + AuthorizedSnapshot completedSnapshot = completion.snapshot(); + if (!isExactAuthorizedSnapshot( + completedSnapshot, tuple, claim, claimEvidence, postAuthorizationTuple)) { + return Result.outcomeUnknown( + completedSnapshot.reservationSnapshot(), PendingReason.LOCAL_COMPLETION_RESULT_MISMATCH); } + + Optional readback; + try { + readback = reservations.findAuthorizedExact(tuple); + } catch (RuntimeException readbackFailure) { + return Result.outcomeUnknown( + completedSnapshot.reservationSnapshot(), PendingReason.AUTHORIZATION_READBACK_UNKNOWN); + } + if (readback == null + || readback.isEmpty() + || !sameAuthorizedSnapshot(completedSnapshot, readback.orElseThrow()) + || !isExactAuthorizedSnapshot( + readback.orElseThrow(), tuple, claim, claimEvidence, postAuthorizationTuple)) { + return Result.outcomeUnknown( + completedSnapshot.reservationSnapshot(), PendingReason.AUTHORIZATION_READBACK_MISMATCH); + } + OwnerExecutionHandoff handoff = new OwnerExecutionHandoff(UUID.randomUUID()); - OwnerExecutionTransition ownerTransition = - reservations.beginOwnerExecution(claim, postAuthorizationTuple, handoff); + OwnerExecutionTransition ownerTransition; + try { + ownerTransition = reservations.beginOwnerExecution(claim, postAuthorizationTuple, handoff); + } catch (RuntimeException ownerTransitionFailure) { + return Result.outcomeUnknown( + readback.orElseThrow().reservationSnapshot(), + PendingReason.OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN, + readback); + } + if (ownerTransition == null || ownerTransition.snapshot() == null) { + return Result.outcomeUnknown( + readback.orElseThrow().reservationSnapshot(), + PendingReason.OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN, + readback); + } if (!ownerTransition.mayDispatch()) { - return Result.alreadyInProgress(); + return Result.alreadyInProgress(ownerTransition.snapshot().reservationSnapshot(), readback); + } + if (!isExactOwnerPendingSnapshot( + ownerTransition.snapshot(), tuple, claim, claimEvidence, postAuthorizationTuple, handoff)) { + return Result.outcomeUnknown( + ownerTransition.snapshot().reservationSnapshot(), + PendingReason.OWNER_PENDING_TRANSITION_RESULT_MISMATCH, + readback); } return Result.ownerExecutionPending( new TransientOwnerExecutionHandoff( - ownerTransition.snapshot().handoff(), accountResponse, postAuthorizationTuple)); + ownerTransition.snapshot().handoff(), accountResponse, postAuthorizationTuple), + ownerTransition.snapshot().reservationSnapshot(), + readback); + } + + private Result observeExisting( + StartSessionPreAuthorizationReservationTuple tuple, Snapshot acquisitionSnapshot) { + Optional readback; + try { + readback = reservations.findAuthorizedExact(tuple); + } catch (RuntimeException unavailable) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_UNKNOWN); + } + if (readback == null) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_UNKNOWN); + } + if (readback.isPresent()) { + AuthorizedSnapshot existing = readback.orElseThrow(); + if (!isBoundAuthorizedSnapshot(existing, tuple)) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_MISMATCH); + } + return Result.alreadyInProgress(existing.reservationSnapshot(), readback); + } + if (acquisitionSnapshot.state() == State.AUTHORIZED + || acquisitionSnapshot.state() == State.OWNER_EXECUTION_PENDING) { + return Result.outcomeUnknown( + acquisitionSnapshot, PendingReason.EXISTING_AUTHORIZATION_READBACK_MISMATCH); + } + return Result.alreadyInProgress(acquisitionSnapshot, Optional.empty()); + } + + private boolean isExactAccountResult( + StartSessionPreAuthorizationReservationTuple tuple, + ClaimEvidence claimEvidence, + AuthorizationReference response, + StartSessionPostAuthorizationExecutionTuple postTuple) { + try { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode(postTuple.authorityEvidenceBundleBytes()); + if (!response.expiresAt().equals(bundle.expiresAt()) + || !tuple.canonicalJson().equals(postTuple.preAuthorizationTuple().canonicalJson()) + || !tuple.controlPlaneRequestId().equals(postTuple.controlPlaneRequestId()) + || !tuple.mutationDigest().equals(postTuple.mutationDigest()) + || !"human_operator".equals(postTuple.issuanceKind()) + || !claimEvidence.reservationOwnerId().equals(postTuple.reservationOwnerId()) + || claimEvidence.reservationClaimFence() != postTuple.reservationClaimFence()) { + return false; + } + bundle.requireTupleBinding(postTuple.preAuthorizationTuple()); + bundle.requireReferenceBinding(postTuple.bundleReference()); + return true; + } catch (RuntimeException malformedEvidence) { + return false; + } + } + + private static boolean claimMatchesOriginalReservation( + ClaimHandle claim, StartSessionPreAuthorizationReservationTuple tuple) { + ClaimEvidence evidence = claim.claimEvidence(); + return tuple.canonicalJson().equals(claim.tuple().canonicalJson()) + && tuple.mutationDigest().equals(claim.mutationDigest()) + && claim.purpose() == ClaimPurpose.ORIGINAL + && evidence.reservationOwnerId().equals(evidence.currentClaimOwnerId()) + && evidence.reservationClaimFence() == evidence.currentClaimFence() + && evidence.reservationClaimFence() > 0L; + } + + private static boolean isExactPendingSnapshot( + Snapshot snapshot, StartSessionPreAuthorizationReservationTuple tuple, ClaimHandle claim) { + ClaimEvidence evidence = claim.claimEvidence(); + return snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING + && snapshot.claimState() == ClaimState.ACTIVE + && snapshot.claimPurpose() == claim.purpose() + && snapshot.reservationClaimFence() == evidence.reservationClaimFence() + && snapshot.claimFence() == evidence.currentClaimFence() + && tuple.canonicalJson().equals(snapshot.tuple().canonicalJson()) + && tuple.mutationDigest().equals(snapshot.mutationDigest()); + } + + private static boolean isExactAuthorizedSnapshot( + AuthorizedSnapshot snapshot, + StartSessionPreAuthorizationReservationTuple tuple, + ClaimHandle claim, + ClaimEvidence evidence, + StartSessionPostAuthorizationExecutionTuple postTuple) { + return isBoundAuthorizedSnapshot(snapshot, tuple) + && snapshot.reservationSnapshot().phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.reservationSnapshot().state() == State.AUTHORIZED + && snapshot.reservationSnapshot().claimState() == ClaimState.ACTIVE + && snapshot.reservationSnapshot().claimPurpose() == claim.purpose() + && snapshot.reservationSnapshot().claimFence() == evidence.currentClaimFence() + && snapshot.reservationSnapshot().reservationClaimFence() + == evidence.reservationClaimFence() + && snapshot.reservationOwnerId().equals(evidence.reservationOwnerId()) + && snapshot.currentClaimOwnerId().equals(evidence.currentClaimOwnerId()) + && snapshot.handoff() == null + && Arrays.equals( + snapshot.postAuthorizationTuple().canonicalBytes(), postTuple.canonicalBytes()); + } + + private static boolean isExactOwnerPendingSnapshot( + AuthorizedSnapshot snapshot, + StartSessionPreAuthorizationReservationTuple tuple, + ClaimHandle claim, + ClaimEvidence evidence, + StartSessionPostAuthorizationExecutionTuple postTuple, + OwnerExecutionHandoff expectedHandoff) { + return isBoundAuthorizedSnapshot(snapshot, tuple) + && snapshot.reservationSnapshot().phase() == Phase.OWNER_EXECUTION + && snapshot.reservationSnapshot().state() == State.OWNER_EXECUTION_PENDING + && snapshot.reservationSnapshot().claimState() == ClaimState.ACTIVE + && snapshot.reservationSnapshot().claimPurpose() == claim.purpose() + && snapshot.reservationSnapshot().claimFence() == evidence.currentClaimFence() + && snapshot.reservationSnapshot().reservationClaimFence() + == evidence.reservationClaimFence() + && snapshot.reservationOwnerId().equals(evidence.reservationOwnerId()) + && snapshot.currentClaimOwnerId().equals(evidence.currentClaimOwnerId()) + && Arrays.equals( + snapshot.postAuthorizationTuple().canonicalBytes(), postTuple.canonicalBytes()) + && expectedHandoff.equals(snapshot.handoff()); + } + + private static boolean isBoundAuthorizedSnapshot( + AuthorizedSnapshot snapshot, StartSessionPreAuthorizationReservationTuple tuple) { + if (snapshot == null + || !tuple.canonicalJson().equals(snapshot.reservationSnapshot().tuple().canonicalJson()) + || !tuple.mutationDigest().equals(snapshot.reservationSnapshot().mutationDigest()) + || !tuple + .canonicalJson() + .equals(snapshot.postAuthorizationTuple().preAuthorizationTuple().canonicalJson()) + || !tuple + .controlPlaneRequestId() + .equals(snapshot.postAuthorizationTuple().controlPlaneRequestId()) + || !tuple.mutationDigest().equals(snapshot.postAuthorizationTuple().mutationDigest()) + || !"human_operator".equals(snapshot.postAuthorizationTuple().issuanceKind()) + || snapshot.reservationSnapshot().reservationClaimFence() + != snapshot.postAuthorizationTuple().reservationClaimFence() + || !snapshot + .reservationOwnerId() + .equals(snapshot.postAuthorizationTuple().reservationOwnerId()) + || snapshot.reservationSnapshot().state() != State.AUTHORIZED + && snapshot.reservationSnapshot().state() != State.OWNER_EXECUTION_PENDING + || snapshot.reservationSnapshot().phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.reservationSnapshot().state() != State.AUTHORIZED + || snapshot.reservationSnapshot().phase() == Phase.OWNER_EXECUTION + && snapshot.reservationSnapshot().state() != State.OWNER_EXECUTION_PENDING) { + return false; + } + try { + StartSessionAuthorityEvidenceBundle bundle = + StartSessionAuthorityEvidenceBundle.decode( + snapshot.postAuthorizationTuple().authorityEvidenceBundleBytes()); + bundle.requireTupleBinding(snapshot.postAuthorizationTuple().preAuthorizationTuple()); + bundle.requireReferenceBinding(snapshot.postAuthorizationTuple().bundleReference()); + return true; + } catch (RuntimeException malformedEvidence) { + return false; + } + } + + private static boolean sameAuthorizedSnapshot( + AuthorizedSnapshot expected, AuthorizedSnapshot actual) { + return expected.reservationSnapshot().equals(actual.reservationSnapshot()) + && Arrays.equals( + expected.postAuthorizationTuple().canonicalBytes(), + actual.postAuthorizationTuple().canonicalBytes()) + && expected.reservationOwnerId().equals(actual.reservationOwnerId()) + && Objects.equals(expected.currentClaimOwnerId(), actual.currentClaimOwnerId()) + && Objects.equals(expected.handoff(), actual.handoff()); + } + + private static void requireNoAmbientSqlOrSynchronization() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "StartSession authorization requires no ambient SQL or synchronization"); + } + } + + private void requireConfiguredNamespace(StartSessionOperatorAction action) { + if (!configuredNamespace.equals(action.scope().targetNamespace())) { + throw new IllegalArgumentException( + "StartSession target namespace does not match the configured workload namespace"); + } + } + + private static void requireSnapshotTuple( + Snapshot snapshot, StartSessionPreAuthorizationReservationTuple tuple) { + if (snapshot == null + || !tuple.canonicalJson().equals(snapshot.tuple().canonicalJson()) + || !tuple.mutationDigest().equals(snapshot.mutationDigest())) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + } + + /** Local envelope validation is not signature validation or current Account authorization. */ + private static void requireCompactJwtEnvelope(String token) { + if (token == null || token.isEmpty() || token.length() > MAX_CONTROL_UI_JWT_BYTES) { + throw malformedJwtEnvelope(); + } + for (int index = 0; index < token.length(); index++) { + if (token.charAt(index) > 0x7f) { + throw malformedJwtEnvelope(); + } + } + String[] segments = token.split("\\.", -1); + if (segments.length != 3 + || segments[0].isEmpty() + || segments[1].isEmpty() + || segments[2].isEmpty()) { + throw malformedJwtEnvelope(); + } + byte[] header = decodeJwtSegment(segments[0]); + byte[] claims = decodeJwtSegment(segments[1]); + byte[] signature = decodeJwtSegment(segments[2]); + if (header == null || claims == null || signature == null || signature.length == 0) { + throw malformedJwtEnvelope(); + } + requireJsonObject(header); + requireJsonObject(claims); + } + + private static byte[] decodeJwtSegment(String segment) { + if (!segment.matches("[A-Za-z0-9_-]+")) { + return null; + } + try { + byte[] decoded = Base64.getUrlDecoder().decode(segment); + return Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(segment) + ? decoded + : null; + } catch (IllegalArgumentException malformed) { + return null; + } + } + + private static void requireJsonObject(byte[] bytes) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + Map object = JWT_JSON.readValue(json, JSON_OBJECT); + if (object == null) { + throw malformedJwtEnvelope(); + } + } catch (IOException | RuntimeException malformed) { + throw malformedJwtEnvelope(); + } + } + + private static IllegalArgumentException malformedJwtEnvelope() { + return new IllegalArgumentException("control-ui JWT envelope is malformed"); } private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple @@ -162,29 +617,92 @@ private Result persistExactAccountResponse( public enum Progress { OWNER_EXECUTION_PENDING, ALREADY_IN_PROGRESS, - RECOVERY_UNAVAILABLE + RECOVERY_UNAVAILABLE, + AUTHORIZATION_OUTCOME_UNKNOWN } /** Contains no response material unless this call won the durable owner-pending transition. */ - public record Result(Progress progress, TransientOwnerExecutionHandoff handoff) { - public Result { - Objects.requireNonNull(progress, "progress is required"); - if ((progress == Progress.OWNER_EXECUTION_PENDING) != (handoff != null)) { + public static final class Result { + private final Progress progress; + private final TransientOwnerExecutionHandoff handoff; + private final Snapshot snapshot; + private final Optional authorizedReadback; + private final PendingReason pendingReason; + + private Result( + Progress progress, + TransientOwnerExecutionHandoff handoff, + Snapshot snapshot, + Optional authorizedReadback, + PendingReason pendingReason) { + this.progress = Objects.requireNonNull(progress, "progress is required"); + this.handoff = handoff; + this.snapshot = snapshot; + this.authorizedReadback = + Objects.requireNonNull(authorizedReadback, "authorized readback is required"); + this.pendingReason = pendingReason; + if ((progress == Progress.OWNER_EXECUTION_PENDING) != (handoff != null) + || (progress == Progress.RECOVERY_UNAVAILABLE) != (snapshot == null) + || (progress == Progress.AUTHORIZATION_OUTCOME_UNKNOWN) != (pendingReason != null)) { throw new IllegalArgumentException( - "only newly persisted owner-pending state has a handoff"); + "authorization result progress and transient material are inconsistent"); } } - private static Result ownerExecutionPending(TransientOwnerExecutionHandoff handoff) { - return new Result(Progress.OWNER_EXECUTION_PENDING, handoff); + private static Result ownerExecutionPending( + TransientOwnerExecutionHandoff handoff, + Snapshot snapshot, + Optional authorizedReadback) { + return new Result( + Progress.OWNER_EXECUTION_PENDING, handoff, snapshot, authorizedReadback, null); } - private static Result alreadyInProgress() { - return new Result(Progress.ALREADY_IN_PROGRESS, null); + private static Result alreadyInProgress( + Snapshot snapshot, Optional authorizedReadback) { + return new Result( + Progress.ALREADY_IN_PROGRESS, + null, + Objects.requireNonNull(snapshot, "observed snapshot is required"), + authorizedReadback, + null); + } + + private static Result outcomeUnknown(Snapshot snapshot, PendingReason reason) { + return outcomeUnknown(snapshot, reason, Optional.empty()); + } + + private static Result outcomeUnknown( + Snapshot snapshot, PendingReason reason, Optional authorizedReadback) { + return new Result( + Progress.AUTHORIZATION_OUTCOME_UNKNOWN, + null, + Objects.requireNonNull(snapshot, "last known snapshot is required"), + authorizedReadback, + Objects.requireNonNull(reason, "pending reason is required")); } private static Result recoveryUnavailable() { - return new Result(Progress.RECOVERY_UNAVAILABLE, null); + return new Result(Progress.RECOVERY_UNAVAILABLE, null, null, Optional.empty(), null); + } + + public Progress progress() { + return progress; + } + + public TransientOwnerExecutionHandoff handoff() { + return handoff; + } + + public Snapshot snapshot() { + return snapshot; + } + + public Optional authorizedReadback() { + return authorizedReadback; + } + + public Optional pendingReason() { + return Optional.ofNullable(pendingReason); } @Override @@ -193,10 +711,32 @@ public String toString() { + progress + ", handoff=" + (handoff == null ? "null" : "") + + ", snapshot=" + + (snapshot == null ? "null" : "") + + ", authorizedReadbackPresent=" + + authorizedReadback.isPresent() + + ", pendingReason=" + + pendingReason + "]"; } } + public enum PendingReason { + RESERVATION_CLAIM_MISMATCH, + PENDING_TRANSITION_OUTCOME_UNKNOWN, + ACCOUNT_ISSUANCE_OUTCOME_UNKNOWN, + ACCOUNT_RECOVERY_OUTCOME_UNKNOWN, + ACCOUNT_RESPONSE_INVALID, + LOCAL_COMPLETION_OUTCOME_UNKNOWN, + LOCAL_COMPLETION_RESULT_MISMATCH, + AUTHORIZATION_READBACK_UNKNOWN, + AUTHORIZATION_READBACK_MISMATCH, + EXISTING_AUTHORIZATION_READBACK_UNKNOWN, + EXISTING_AUTHORIZATION_READBACK_MISMATCH, + OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN, + OWNER_PENDING_TRANSITION_RESULT_MISMATCH + } + /** * Safe composition result: original progress and, only after dispatch, a secret-free owner echo. */ diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java index a6c8b8266f..5cc5c154d0 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionClientTest.java @@ -17,6 +17,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.UUID; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; @@ -38,6 +39,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; class GameSessionClientTest { @TempDir private Path tlsDirectory; @@ -84,7 +86,7 @@ public > T customize(T candidate) { @Test void sendsOneExactTypedHandoffAndValidatesSecretFreeOwnerEcho() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); - var handoff = handoff(); + TransientOwnerExecutionHandoff handoff = handoff(); StartSessionPostAuthorizationExecutionTuple tuple = handoff.postAuthorizationTuple(); AuthorizeStartSessionResponse response = ownerResponse( @@ -100,8 +102,7 @@ void sendsOneExactTypedHandoffAndValidatesSecretFreeOwnerEcho() throws Exception GameSessionClient.StartSessionOwnerHandoffResult result = client.authorizeStartSession(handoff); - verify(stub, times(1)) - .withDeadlineAfter(DEADLINE_SECONDS, java.util.concurrent.TimeUnit.SECONDS); + verify(stub, times(1)).withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS); verify(stub, times(1)).authorizeStartSession(requestCaptor.capture()); verify(stub, never()).stopSession(any()); assertThat( @@ -132,7 +133,7 @@ void sendsOneExactTypedHandoffAndValidatesSecretFreeOwnerEcho() throws Exception @Test void refusesOwnerResponseThatDoesNotEchoTheOriginalTuple() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); - var handoff = handoff(); + TransientOwnerExecutionHandoff handoff = handoff(); AuthorizeStartSessionResponse substitutedResponse = ownerResponse( handoff.postAuthorizationTuple(), @@ -190,6 +191,43 @@ void rejectsSubstitutedAccountReferenceBeforeCallingGameSession() throws Excepti verify(stub, never()).authorizeStartSession(any()); } + @Test + void refusesNullOpaqueReferenceBeforeOwnerRpc() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + TransientOwnerExecutionHandoff handoff = handoff(); + when(handoff.accountResponse().operatorAuthorizationReference()).thenReturn(null); + assertThatThrownBy(() -> client(stub).authorizeStartSession(handoff)) + .isInstanceOf(IllegalArgumentException.class); + verify(stub, never()).authorizeStartSession(any()); + } + + @Test + void refusesOwnerHandoffInsideAmbientSqlOrSynchronizationBeforeRpc() throws Exception { + GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); + GameSessionClient client = client(stub); + TransientOwnerExecutionHandoff handoff = handoff(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> client.authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.authorizeStartSession(handoff)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + + verify(stub, never()).authorizeStartSession(any()); + } + @Test void surfacesTransportAmbiguityWithoutAutomaticRetryOrReferenceDisclosure() throws Exception { GameSessionServiceGrpc.GameSessionServiceBlockingStub stub = mockStub(); @@ -252,8 +290,7 @@ private static GameSessionServiceGrpc.GameSessionServiceBlockingStub mockStub() var stub = mock(GameSessionServiceGrpc.GameSessionServiceBlockingStub.class); when(stub.withCallCredentials(any(CallCredentials.class))).thenReturn(stub); when(stub.withInterceptors(any(ClientInterceptor[].class))).thenReturn(stub); - when(stub.withDeadlineAfter(DEADLINE_SECONDS, java.util.concurrent.TimeUnit.SECONDS)) - .thenReturn(stub); + when(stub.withDeadlineAfter(DEADLINE_SECONDS, TimeUnit.SECONDS)).thenReturn(stub); return stub; } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java new file mode 100644 index 0000000000..3b699a6ed4 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java @@ -0,0 +1,1034 @@ +package net.firedevops.firemud.loggingadmin.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslProvider; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.SecureRandom; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Clock; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.UnaryOperator; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManagerFactory; +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.RecoverOperatorAuthorizationReferenceRequest; +import net.firedevops.firemud.account.v1.RecoverOperatorAuthorizationReferenceResponse; +import net.firedevops.firemud.account.v1.StartSessionOperatorAuthorizationServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionOperatorAction; +import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; +import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Socket-mTLS proof against a synthetic Account handler, not Account issuance or Logging claim + * proof. + */ +class StartSessionOperatorAuthorizationClientMtlsTest { + private static final String NAMESPACE = "logging-test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/logging-test/sa/account-service"; + private static final String LOGGING_URI = + "spiffe://firemud/ns/logging-test/sa/logging-admin-service"; + private static final String STORE_PASSWORD = "synthetic-start-session-authorization-test"; + private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); + private static final UUID ACTOR_ID = UUID.fromString("a4f5f4eb-8243-4d42-903a-33495456a622"); + private static final UUID OWNER_ACCOUNT_ID = + UUID.fromString("36aa9ce5-0ebc-4c14-9f6b-d160edc6059a"); + private static final UUID RESERVATION_OWNER_ID = + UUID.fromString("ef5b97ec-3cbe-43dc-a85f-f119060386ab"); + private static final UUID CLAIM_OWNER_ID = + UUID.fromString("9bb650bd-38c2-4dc1-8132-1af107358e60"); + private static final String CONTROL_UI_JWT = "synthetic-original-control-ui-jwt-body-only"; + private static final String OPERATOR_REFERENCE = "a".repeat(43); + private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); + private static final Instant NOW = Instant.parse("2026-10-11T12:00:00Z"); + private static final Instant EXPIRY = NOW.plusSeconds(240); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @TempDir static Path temporaryDirectory; + private static TestPki pki; + private Server server; + private StartSessionOperatorAuthorizationClient client; + private AtomicInteger rpcCalls; + private IssueHumanOperatorAuthorizationReferenceRequest receivedIssue; + private RecoverOperatorAuthorizationReferenceRequest receivedRecovery; + + @BeforeAll + static void createSyntheticWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @BeforeEach + void clearAmbientThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @AfterEach + void stopTransportAndClearThreadState() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @ParameterizedTest + @ValueSource(longs = {9_007_199_254_740_993L, Long.MAX_VALUE}) + void issueAndRecoverPreserveTheExactOriginalResponseAndCompleteEvidence(long reservationFence) + throws Exception { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + var tuple = tuple("synthetic-issue-recover-01"); + + var issued = + client.issueHuman( + tuple, CONTROL_UI_JWT, RESERVATION_OWNER_ID, reservationFence, CLAIM_OWNER_ID, 71L); + var recovered = + client.recover(tuple, RESERVATION_OWNER_ID, reservationFence, CLAIM_OWNER_ID, 71L); + + assertThat(issued.operatorAuthorizationReference()).isEqualTo(OPERATOR_REFERENCE); + assertThat(recovered.operatorAuthorizationReference()).isEqualTo(OPERATOR_REFERENCE); + assertThat(recovered.authorizationReferenceFingerprint()) + .isEqualTo(issued.authorizationReferenceFingerprint()); + assertThat(issued.expiresAt()).isEqualTo(EXPIRY); + assertThat(recovered.expiresAt()).isEqualTo(issued.expiresAt()); + assertThat(recovered.authorityEvidenceBundle()) + .containsExactly(issued.authorityEvidenceBundle()); + assertThat(recovered.bundleReference()).isEqualTo(issued.bundleReference()); + assertThat(issued.postAuthorizationTuple().canonicalBytes()) + .containsExactly(originalTupleBytes(tuple, RESERVATION_OWNER_ID, reservationFence)); + assertThat(recovered.postAuthorizationTuple().canonicalBytes()) + .containsExactly(issued.postAuthorizationTuple().canonicalBytes()); + assertThat(issued.postAuthorizationTuple().reservationOwnerId()) + .isEqualTo(RESERVATION_OWNER_ID); + assertThat(issued.postAuthorizationTuple().reservationClaimFence()).isEqualTo(reservationFence); + assertThat(recovered.postAuthorizationTuple().reservationClaimFence()) + .isEqualTo(reservationFence); + Map encodedTuple = + JSON.readValue(issued.postAuthorizationTuple().canonicalBytes(), Map.class); + assertThat(encodedTuple.get("reservationClaimFence")) + .isEqualTo(Long.toString(reservationFence)); + assertThat(issued.bundleReference().sourceFence()) + .isNotEqualTo(issued.postAuthorizationTuple().issuanceFence()); + assertThat(issued.authenticatedLoggingWorkloadIdentity()).isEqualTo(LOGGING_URI); + assertThat(recovered.authenticatedLoggingWorkloadIdentity()).isEqualTo(LOGGING_URI); + assertThat(issued.decodedBundle().controlPlaneRequestId()) + .isEqualTo(tuple.controlPlaneRequestId()); + assertThat(issued.toString()).doesNotContain(OPERATOR_REFERENCE, CONTROL_UI_JWT); + assertThat(receivedIssue.getControlUiJwt()).isEqualTo(CONTROL_UI_JWT); + assertThat(receivedIssue.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(receivedIssue.getReservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(receivedIssue.getReservationClaimFence()).isEqualTo(reservationFence); + assertThat(receivedIssue.getCurrentClaimOwnerId()).isEqualTo(CLAIM_OWNER_ID.toString()); + assertThat(receivedIssue.getCurrentClaimFence()).isEqualTo(71L); + assertThat(receivedRecovery.getCanonicalPreAuthorizationTupleBytes().toByteArray()) + .containsExactly(receivedIssue.getCanonicalPreAuthorizationTupleBytes().toByteArray()); + assertThat(receivedRecovery.getReservationOwnerId()) + .isEqualTo(receivedIssue.getReservationOwnerId()); + assertThat(receivedRecovery.getReservationClaimFence()) + .isEqualTo(receivedIssue.getReservationClaimFence()); + assertThat(receivedRecovery.getCurrentClaimOwnerId()) + .isEqualTo(receivedIssue.getCurrentClaimOwnerId()); + assertThat(receivedRecovery.getCurrentClaimFence()) + .isEqualTo(receivedIssue.getCurrentClaimFence()); + assertThat(rpcCalls).hasValue(2); + } + + @Test + void rejectsWrongAccountServerServiceAndNamespaceBeforeSendingRequest() throws Exception { + assertWrongServerIdentity( + pki.identity( + "wrong-service-server", "spiffe://firemud/ns/logging-test/sa/account-other", true)); + assertWrongServerIdentity( + pki.identity( + "wrong-namespace-server", "spiffe://firemud/ns/other-test/sa/account-service", true)); + } + + @Test + void rejectsWrongLoggingCallerServiceAndNamespaceAtSyntheticAccountBoundary() throws Exception { + for (TestIdentity caller : + List.of( + pki.identity( + "wrong-service-client", + "spiffe://firemud/ns/logging-test/sa/game-session-service", + false), + pki.identity( + "wrong-namespace-client", + "spiffe://firemud/ns/other-test/sa/logging-admin-service", + false))) { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(caller); + client.initialize(); + + assertThatThrownBy( + () -> + client.issueHuman( + tuple("wrong-caller-" + caller.alias()), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 8L, + CLAIM_OWNER_ID, + 9L)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("PERMISSION_DENIED"); + assertThat(rpcCalls).hasValue(1); + stopServer(); + client.close(); + client = null; + } + } + + @Test + void rejectsUnknownFieldsChangedTupleBindingAndExpirySubstitution() throws Exception { + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build(); + startServer( + pki.accountServer(), + response -> response.toBuilder().setUnknownFields(unknown).build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setAuthorityEvidenceBundle( + ByteString.copyFrom(bundleFor(tuple("different-original-request")))) + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + + for (UnaryOperator substitute : + List.>of( + response -> response.toBuilder().clearOriginalAccountPostAuthorizationTuple().build(), + response -> + response.toBuilder() + .setBundleReference( + response.getBundleReference().toBuilder().setSourceFence("25")) + .build(), + response -> + response.toBuilder() + .setBundleReference( + response.getBundleReference().toBuilder() + .setLinearization("18446744073709551614")) + .build())) { + startServer(pki.accountServer(), substitute, UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + } + + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setExpiresAt( + Timestamp.newBuilder().setSeconds(EXPIRY.plusSeconds(1).getEpochSecond())) + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + } + + @Test + void rejectsAuthenticatedLoggingIdentityMismatchAndExpiredEvidence() throws Exception { + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setAuthenticatedLoggingWorkloadIdentity( + "spiffe://firemud/ns/other-test/sa/logging-admin-service") + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + stopTransportOnly(); + + startServer( + pki.accountServer(), + response -> + response.toBuilder() + .setExpiresAt( + Timestamp.newBuilder().setSeconds(NOW.minusSeconds(1).getEpochSecond())) + .setAuthorityEvidenceBundle( + ByteString.copyFrom(bundleFor(tuple("expired-original-request")))) + .build(), + UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertInvalidResponse(); + } + + @Test + void deniesIssueAndRecoveryBeforeNetworkUnderSqlOrSynchronization() throws Exception { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + var tuple = tuple("pre-network-denial-01"); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_JWT, RESERVATION_OWNER_ID, 1L, CLAIM_OWNER_ID, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + TransactionSynchronizationManager.clear(); + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER_ID, 1L, CLAIM_OWNER_ID, 2L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.clear(); + } + assertThat(rpcCalls).hasValue(0); + } + + @Test + void syntheticMutualTlsRejectsMissingClientCertificateWithSharedTlsAssertion() throws Exception { + startServer(pki.accountServer(), UnaryOperator.identity(), UnaryOperator.identity()); + SSLContext trustOnlyContext = SSLContext.getInstance("TLS"); + var trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); + trustStore.load(null, null); + trustStore.setCertificateEntry("trusted-test-ca", pki.caCertificate()); + var trustManagers = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagers.init(trustStore); + trustOnlyContext.init(null, trustManagers.getTrustManagers(), new SecureRandom()); + + Throwable failure = + catchThrowable( + () -> { + try (SSLSocket socket = + (SSLSocket) + trustOnlyContext + .getSocketFactory() + .createSocket("127.0.0.1", server.getPort())) { + socket.setSoTimeout(2_000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + parameters.setProtocols(new String[] {"TLSv1.3"}); + parameters.setApplicationProtocols(new String[] {"h2"}); + socket.setSSLParameters(parameters); + socket.startHandshake(); + socket.getInputStream().read(); + } + }); + + assertThat(failure).isInstanceOf(SSLHandshakeException.class); + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue(); + assertThat(rpcCalls).hasValue(0); + } + + private void assertWrongServerIdentity(TestIdentity serverIdentity) throws Exception { + startServer(serverIdentity, UnaryOperator.identity(), UnaryOperator.identity()); + client = newClient(pki.loggingClient()); + client.initialize(); + assertThatThrownBy( + () -> + client.issueHuman( + tuple("wrong-server-" + serverIdentity.alias()), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 10L, + CLAIM_OWNER_ID, + 11L)) + .isInstanceOf(StatusRuntimeException.class) + .hasMessageContaining("UNAUTHENTICATED"); + assertThat(rpcCalls).hasValue(0); + stopTransportOnly(); + } + + private void assertInvalidResponse() { + assertThatThrownBy( + () -> + client.issueHuman( + tuple("invalid-account-result-01"), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 12L, + CLAIM_OWNER_ID, + 13L)) + .isInstanceOf(IllegalStateException.class); + assertThat(rpcCalls).hasValue(1); + } + + private void startServer( + TestIdentity serverIdentity, + UnaryOperator issueMutation, + UnaryOperator recoverMutation) + throws Exception { + rpcCalls = new AtomicInteger(); + receivedIssue = null; + receivedRecovery = null; + var service = + new StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceImplBase() { + @Override + public void issueHumanOperatorAuthorizationReference( + IssueHumanOperatorAuthorizationReferenceRequest request, + StreamObserver observer) { + rpcCalls.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !LOGGING_URI.equals(peer.uri()) + || !NAMESPACE.equals(peer.namespace()) + || SessionContext.hasAuthenticatedCallerContext()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + receivedIssue = request.toBuilder().build(); + try { + observer.onNext(issueMutation.apply(issueResponse(request))); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + + @Override + public void recoverOperatorAuthorizationReference( + RecoverOperatorAuthorizationReferenceRequest request, + StreamObserver observer) { + rpcCalls.incrementAndGet(); + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null + || !LOGGING_URI.equals(peer.uri()) + || !NAMESPACE.equals(peer.namespace()) + || SessionContext.hasAuthenticatedCallerContext()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + receivedRecovery = request.toBuilder().build(); + try { + observer.onNext(recoverMutation.apply(recoveryResponse(request))); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + }; + ServerInterceptor requestMetadataGuard = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + if (headers.get(Metadata.Key.of("authorization", Metadata.ASCII_STRING_MARSHALLER)) + != null) { + call.close(Status.PERMISSION_DENIED, new Metadata()); + return new ServerCall.Listener<>() {}; + } + return next.startCall(call, headers); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate()), + SslProvider.JDK) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .protocols("TLSv1.3") + .build()) + .addService( + ServerInterceptors.intercept( + service, requestMetadataGuard, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private void stopTransportOnly() throws Exception { + if (client != null) { + client.close(); + client = null; + } + stopServer(); + } + + private void stopServer() throws Exception { + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } + + private StartSessionOperatorAuthorizationClient newClient(TestIdentity clientIdentity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + server.getPort()); + return new StartSessionOperatorAuthorizationClient( + endpoints, + pki.clientProperties(clientIdentity), + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + Clock.fixed(NOW, java.time.ZoneOffset.UTC)); + } + + private static IssueHumanOperatorAuthorizationReferenceResponse issueResponse( + IssueHumanOperatorAuthorizationReferenceRequest request) { + return IssueHumanOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setExpiresAt(timestamp(EXPIRY)) + .setAuthorityEvidenceBundle(ByteString.copyFrom(bundleFor(tupleFrom(request)))) + .setBundleReference(bundleReference()) + .setAuthenticatedLoggingWorkloadIdentity(LOGGING_URI) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + originalTupleBytes( + tupleFrom(request), + UUID.fromString(request.getReservationOwnerId()), + request.getReservationClaimFence()))) + .build(); + } + + private static RecoverOperatorAuthorizationReferenceResponse recoveryResponse( + RecoverOperatorAuthorizationReferenceRequest request) { + return RecoverOperatorAuthorizationReferenceResponse.newBuilder() + .setOperatorAuthorizationReference(OPERATOR_REFERENCE) + .setAuthorizationReferenceFingerprint(FINGERPRINT) + .setExpiresAt(timestamp(EXPIRY)) + .setAuthorityEvidenceBundle(ByteString.copyFrom(bundleFor(tupleFrom(request)))) + .setBundleReference(bundleReference()) + .setAuthenticatedLoggingWorkloadIdentity(LOGGING_URI) + .setOriginalAccountPostAuthorizationTuple( + ByteString.copyFrom( + originalTupleBytes( + tupleFrom(request), + UUID.fromString(request.getReservationOwnerId()), + request.getReservationClaimFence()))) + .build(); + } + + private static byte[] originalTupleBytes( + StartSessionPreAuthorizationReservationTuple tuple, UUID reservationOwner, long fence) { + var reference = bundleReference(); + return StartSessionPostAuthorizationExecutionTuple.createHuman( + tuple, + LOGGING_URI, + FINGERPRINT, + reservationOwner, + fence, + bundleFor(tuple), + new StartSessionAuthorityEvidenceBundle.BundleReference( + reference.getBundleVersion(), + reference.getSourceVersion(), + reference.getSourceFence(), + reference.getLinearization())) + .canonicalBytes(); + } + + private static byte[] bundleFor( + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple tuple) { + String tenantId = tuple.action().scope().tenantId().toString(); + Map root = + new LinkedHashMap<>( + Map.of( + "bundleVersion", StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "authorityScope", + Map.of( + "scope", + Map.of( + "tenantId", + tenantId, + "targetNamespace", + tuple.action().scope().targetNamespace()), + "actionFamily", tuple.actionFamily(), + "applicableAccountId", tuple.actor().accountId().toString(), + "applicableTenantId", tenantId), + "accountProjectionEvidence", + Map.of( + "sourceType", + "ACCOUNT", + "sourceEvidenceId", + "sha256:" + "c".repeat(64), + "sourceEvidenceVersion", + "17", + "projectionStatus", + "CURRENT", + "evaluatedAt", + NOW.toString(), + "expiresAt", + EXPIRY.toString()), + "issuanceOperationIdentity", + Map.of( + "issuanceOperationId", "f5d044bd-7e5f-4e2d-9859-9025cbdcc60f", + "controlPlaneRequestId", tuple.controlPlaneRequestId(), + "actionFamilyRequestIdentity", + Map.of( + "requestIdentityKind", + "controlPlaneRequestId", + "requestId", + tuple.controlPlaneRequestId()), + "mutationDigest", tuple.mutationDigest()), + "issuanceKind", "human_operator", + "authorityTuple", + Map.of( + "issuerAuthGeneration", 1L, + "accountAuthorityGeneration", 2L, + "tenantAuthorityGeneration", Map.of(tenantId, 3L), + "membershipAuthorityGeneration", Map.of(tenantId, 4L), + "privateRealmGrantVersions", List.of()), + "membershipVersion", Map.of(tenantId, 5L), + "issuanceFence", "23", + "issuanceEvidence", + Map.of( + "evidenceType", StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, + "actorAccountId", tuple.actor().accountId().toString(), + "controlUiTokenJti", "a681bba7-c215-4cf1-a35b-14348912cbdc", + "role", "tenantAdmin", + "accountGeneration", "2", + "tenantGeneration", "3"))); + try { + return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + } catch (IOException fixtureFailure) { + throw new IllegalStateException( + "Synthetic Account authority bundle fixture could not be encoded", fixtureFailure); + } + } + + private static AuthorityEvidenceBundleReference bundleReference() { + return AuthorityEvidenceBundleReference.newBuilder() + .setBundleVersion(StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION) + .setSourceVersion("17") + .setSourceFence("24") + .setLinearization("18446744073709551615") + .build(); + } + + private static Timestamp timestamp(Instant value) { + return Timestamp.newBuilder() + .setSeconds(value.getEpochSecond()) + .setNanos(value.getNano()) + .build(); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String requestId) { + var action = + new StartSessionOperatorAction( + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, + StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, + new StartSessionOperatorAction.Scope(TENANT_ID, NAMESPACE), + new StartSessionOperatorAction.Target(91L, OWNER_ACCOUNT_ID), + StartSessionOperatorAction.ExpectedVersion.ABSENT, + new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), + "synthetic Account authorization client transport proof"); + var shared = + net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .createHuman(requestId, ACTOR_ID, action); + return StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(shared.canonicalJson()); + } + + private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + tupleFrom(IssueHumanOperatorAuthorizationReferenceRequest request) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(request.getCanonicalPreAuthorizationTupleBytes().toStringUtf8()); + } + + private static net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + tupleFrom(RecoverOperatorAuthorizationReferenceRequest request) { + return net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple + .fromCanonicalJson(request.getCanonicalPreAuthorizationTupleBytes().toStringUtf8()); + } + + private record TestIdentity( + String alias, + String workloadUri, + boolean server, + Path store, + Path certificatePem, + Path privateKeyPem, + PrivateKey privateKey, + X509Certificate certificate) {} + + private static final class TestPki { + private final Path directory; + private final Path caStore; + private final Path caCertificatePem; + private final X509Certificate caCertificate; + private final Map identities; + + private TestPki( + Path directory, + Path caStore, + Path caCertificatePem, + X509Certificate caCertificate, + Map identities) { + this.directory = directory; + this.caStore = caStore; + this.caCertificatePem = caCertificatePem; + this.caCertificate = caCertificate; + this.identities = identities; + } + + private static TestPki create(Path directory) throws Exception { + Files.createDirectories(directory); + Path caStore = directory.resolve("start-session-authorization-test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD StartSession authorization synthetic test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caCertificate = directory.resolve("start-session-authorization-test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caCertificate.toString(), + "-rfc"); + var identities = new LinkedHashMap(); + addIdentity( + identities, + issueIdentity(directory, caStore, caCertificate, "account-server", ACCOUNT_URI, true)); + addIdentity( + identities, + issueIdentity(directory, caStore, caCertificate, "logging-client", LOGGING_URI, false)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-service-server", + "spiffe://firemud/ns/logging-test/sa/account-other", + true)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-namespace-server", + "spiffe://firemud/ns/other-test/sa/account-service", + true)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-service-client", + "spiffe://firemud/ns/logging-test/sa/game-session-service", + false)); + addIdentity( + identities, + issueIdentity( + directory, + caStore, + caCertificate, + "wrong-namespace-client", + "spiffe://firemud/ns/other-test/sa/logging-admin-service", + false)); + return new TestPki( + directory, caStore, caCertificate, readCertificate(caCertificate), identities); + } + + private static void addIdentity(Map identities, TestIdentity identity) { + identities.put(identity.alias(), identity); + } + + private TestIdentity accountServer() { + return identities.get("account-server"); + } + + private TestIdentity loggingClient() { + return identities.get("logging-client"); + } + + private TestIdentity identity(String alias, String workloadUri, boolean server) { + TestIdentity identity = identities.get(alias); + if (identity == null + || !identity.workloadUri().equals(workloadUri) + || identity.server() != server) { + throw new IllegalArgumentException("Unexpected synthetic mTLS identity fixture"); + } + return identity; + } + + private X509Certificate caCertificate() { + return caCertificate; + } + + private CommonGrpcClientProperties clientProperties(TestIdentity identity) { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(identity.certificatePem().toString()); + properties.setPrivateKey(identity.privateKeyPem().toString()); + properties.setCaCert(caCertificatePem.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, + Path caStore, + Path caCertificate, + String alias, + String workloadUri, + boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + workloadUri + ",DNS:localhost,IP:127.0.0.1"; + String extendedKeyUsage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + extendedKeyUsage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caCertificate.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()); + X509Certificate leaf = (X509Certificate) keyStore.getCertificate(alias); + Path certificatePem = + writePem(directory.resolve(alias + "-leaf.pem"), "CERTIFICATE", leaf.getEncoded()); + Path privateKeyPem = + writePem( + directory.resolve(alias + "-private.pem"), "PRIVATE KEY", privateKey.getEncoded()); + return new TestIdentity( + alias, workloadUri, server, store, certificatePem, privateKeyPem, privateKey, leaf); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Path outputFile = Files.createTempFile("firemud-start-session-auth-keytool-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(outputFile.toFile()) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + throw new IllegalStateException("synthetic workload keytool fixture timed out"); + } + String output = Files.readString(outputFile, StandardCharsets.UTF_8); + if (process.exitValue() != 0) { + throw new IllegalStateException("synthetic workload keytool fixture failed: " + output); + } + } finally { + Files.deleteIfExists(outputFile); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java index d84515884e..b552f2f8f1 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java @@ -50,6 +50,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; import tools.jackson.databind.json.JsonMapper; class StartSessionOperatorAuthorizationClientTest { @@ -435,6 +436,71 @@ void unavailableAccountResponseRemainsUnavailableWithoutCreatingFallback() throw } } + @Test + void deniesIssueAndRecoverBeforeAccountUnderSqlOrSynchronization() throws Exception { + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-no-ambient-transaction"); + + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + client.issueHuman( + tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clear(); + } + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.clear(); + } + + verify(stub, never()).issueHumanOperatorAuthorizationReference(any()); + verify(stub, never()).recoverOperatorAuthorizationReference(any()); + } + } + + @Test + void rejectsExpiredRecoveryWithoutReplacementIssuance() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-expired-recovery"); + var stub = + mock( + StartSessionOperatorAuthorizationServiceGrpc + .StartSessionOperatorAuthorizationServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + Instant expired = NOW.minusSeconds(1); + RecoverOperatorAuthorizationReferenceResponse response = + recoverResponse(tuple, expired, bundleBytes(tuple, NOW.minusSeconds(2), expired)); + when(stub.recoverOperatorAuthorizationReference(any())).thenReturn(response); + try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { + assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("expired"); + verify(stub, never()).issueHumanOperatorAuthorizationReference(any()); + } + } + + @Test + void rejectsAccountReferenceLifetimeAboveItsConfiguredMaximum() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("client-overlong-reference"); + assertRejected( + tuple, + issueResponse(tuple, NOW.plusSeconds(301), bundleBytes(tuple, NOW.plusSeconds(301)))); + } + private void assertRejected( StartSessionPreAuthorizationReservationTuple tuple, IssueHumanOperatorAuthorizationReferenceResponse response) @@ -557,6 +623,12 @@ private static AuthorityEvidenceBundleReference reference() { private static byte[] bundleBytes( StartSessionPreAuthorizationReservationTuple tuple, Instant expiry) throws Exception { + return bundleBytes(tuple, NOW, expiry); + } + + private static byte[] bundleBytes( + StartSessionPreAuthorizationReservationTuple tuple, Instant evaluatedAt, Instant expiry) + throws Exception { String tenantId = TENANT_ID.toString(); Map projection = Map.of( @@ -569,7 +641,7 @@ private static byte[] bundleBytes( "projectionStatus", "CURRENT", "evaluatedAt", - NOW.toString(), + evaluatedAt.toString(), "expiresAt", expiry.toString()); Map authority = diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java index 6409516c44..fe9a6f0b38 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java @@ -14,7 +14,6 @@ import static org.mockito.Mockito.when; import io.grpc.Status; -import java.io.IOException; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; @@ -22,8 +21,10 @@ import java.util.Map; import java.util.Optional; import java.util.UUID; -import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundle; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture; +import net.firedevops.firemud.common.operator.StartSessionAuthorityEvidenceBundleFixture.Values; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple; import net.firedevops.firemud.common.security.SessionContext; @@ -45,10 +46,11 @@ import net.firedevops.firemud.loggingadmin.operator.StartSessionPreAuthorizationReservationService.State; import net.firedevops.firemud.loggingadmin.repository.StartSessionPreAuthorizationReservationRepository; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; -import tools.jackson.databind.json.JsonMapper; +import org.springframework.transaction.support.TransactionSynchronizationManager; class StartSessionAuthorizationCoordinatorTest { private static final UUID TENANT_ID = UUID.fromString("9f8f06b4-36e5-4d11-9c2a-5adfd7f41531"); @@ -65,12 +67,11 @@ class StartSessionAuthorizationCoordinatorTest { UUID.fromString("89da7d84-12f5-4cf8-b69b-30ba8eb115a4"); private static final Instant NOW = Instant.parse("2026-10-09T00:00:00Z"); private static final long NOW_MILLIS = NOW.toEpochMilli(); - private static final String CONTROL_UI_TOKEN = "operator-control-ui-secret"; + private static final String CONTROL_UI_TOKEN = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0In0.c2ln"; private static final String OPAQUE_REFERENCE = "r".repeat(43); private static final String FINGERPRINT = "arfp/v1/test-key/" + "b".repeat(64); private static final String LOGGING_IDENTITY = "spiffe://firemud/ns/world-runtime/sa/logging-admin-service"; - private static final JsonMapper JSON = JsonMapper.builder().build(); private final StartSessionPreAuthorizationReservationRepository repository = mock(StartSessionPreAuthorizationReservationRepository.class); @@ -79,12 +80,25 @@ class StartSessionAuthorizationCoordinatorTest { repository, Clock.fixed(NOW, ZoneOffset.UTC)); private final StartSessionOperatorAuthorizationClient accountClient = mock(StartSessionOperatorAuthorizationClient.class); + private final AtomicReference exactReadback = new AtomicReference<>(); private final StartSessionAuthorizationCoordinator coordinator = - new StartSessionAuthorizationCoordinator(reservations, accountClient); + new StartSessionAuthorizationCoordinator("world-runtime", reservations, accountClient); + + @BeforeEach + void setAuthenticatedTenantAdminContext() { + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("tenantAdmin")), + false, + null, + null); + } @AfterEach void clearAuthenticatedContext() { SessionContext.clear(); + TransactionSynchronizationManager.clear(); } @Test @@ -134,10 +148,15 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere .isEqualTo(LOGGING_IDENTITY); assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); assertThat(duplicate.handoff()).isNull(); + assertThat(duplicate.authorizedReadback()).isPresent(); assertThat(first.toString()) .doesNotContain(CONTROL_UI_TOKEN) .doesNotContain(OPAQUE_REFERENCE) .doesNotContain(FINGERPRINT); + assertThat(duplicate.toString()) + .doesNotContain(CONTROL_UI_TOKEN) + .doesNotContain(OPAQUE_REFERENCE) + .doesNotContain(FINGERPRINT); assertThat(first.handoff().toString()) .doesNotContain(CONTROL_UI_TOKEN) .doesNotContain(OPAQUE_REFERENCE) @@ -148,6 +167,19 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere ArgumentCaptor persistedTuple = ArgumentCaptor.forClass(String.class); ArgumentCaptor handoffId = ArgumentCaptor.forClass(UUID.class); InOrder persistenceOrder = inOrder(accountClient, repository); + persistenceOrder + .verify(repository) + .acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L)); + persistenceOrder + .verify(repository) + .markAuthorizationPending( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + eq(NOW_MILLIS)); persistenceOrder .verify(accountClient) .issueHuman( @@ -158,6 +190,14 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere currentOwner.capture(), eq(1L)); assertThat(originalOwner.getValue()).isEqualTo(currentOwner.getValue()); + verify(accountClient, org.mockito.Mockito.times(1)) + .issueHuman( + eq(shared(tuple)), + eq(CONTROL_UI_TOKEN), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L)); verify(accountClient, never()).recover(any(), any(), anyLong(), any(), anyLong()); persistenceOrder .verify(repository) @@ -176,6 +216,12 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere .doesNotContain(CONTROL_UI_TOKEN); assertThat(persistedTuple.getValue()) .isEqualTo(first.handoff().postAuthorizationTuple().canonicalJson()); + assertThat( + StartSessionPostAuthorizationExecutionTuple.decode( + persistedTuple.getValue().getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .canonicalBytes()) + .containsExactly(first.handoff().postAuthorizationTuple().canonicalBytes()); + persistenceOrder.verify(repository).findAuthorizedExact(eq(tuple)); persistenceOrder .verify(repository) .beginOwnerExecution( @@ -191,6 +237,299 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere assertThat(handoffId.getValue()).isEqualTo(first.handoff().ownerExecutionHandoff().handoffId()); } + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeReservationWork() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-ambient-sql"); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> + coordinator.begin( + tuple.controlPlaneRequestId(), tuple.action(), CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL or synchronization"); + } finally { + TransactionSynchronizationManager.clear(); + } + TransactionSynchronizationManager.initSynchronization(); + try { + assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> coordinator.recover(tuple)) + .isInstanceOf(IllegalStateException.class); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + TransactionSynchronizationManager.clear(); + } + verifyNoInteractions(repository, accountClient); + } + + @Test + void nullReferenceAndWrongWorkloadCannotCompleteOrHandoff() throws Exception { + for (String caseName : List.of("null-reference", "wrong-workload")) { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-" + caseName); + stubInitialReservation(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), + anyString(), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong())) + .thenAnswer( + invocation -> { + AuthorizationReference response = + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue()); + if (caseName.equals("null-reference")) { + when(response.operatorAuthorizationReference()).thenReturn(null); + } else { + when(response.authenticatedLoggingWorkloadIdentity()) + .thenReturn("spiffe://firemud/ns/other/sa/logging-admin-service"); + } + return response; + }); + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains(StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_RESPONSE_INVALID); + assertThat(result.handoff()).isNull(); + verify(repository, never()) + .completeAuthorization( + eq(tuple), anyString(), any(), anyLong(), any(), anyLong(), anyString(), anyLong()); + verify(repository, never()) + .beginOwnerExecution( + eq(tuple), + anyString(), + any(), + anyLong(), + any(), + anyLong(), + anyString(), + any(), + anyLong()); + } + } + + @Test + void recoveryFailureKeepsOriginalPendingClaimAndDoesNotIssueReplacement() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-recovery-unavailable"); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 3L); + when(repository.acquireRecoveryClaim( + eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + Optional.of( + new StartSessionPreAuthorizationReservationRepository.RecoveryClaimResult( + pending, ORIGINAL_OWNER))); + when(accountClient.recover( + eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + Result result = coordinator.recover(tuple); + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_RECOVERY_OUTCOME_UNKNOWN); + assertThat(result.snapshot()).isEqualTo(pending); + assertThat(result.handoff()).isNull(); + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + verify(repository, never()) + .completeAuthorization( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), anyLong()); + } + + @Test + void namespaceJwtAndHumanTenantAdminGuardsRunBeforeStorage() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-input-guards"); + StartSessionOperatorAction action = tuple.action(); + StartSessionOperatorAction wrongNamespaceAction = + new StartSessionOperatorAction( + action.actionFamilySchemaId(), + action.actionFamilySchemaVersion(), + new StartSessionOperatorAction.Scope(TENANT_ID, "other-runtime"), + action.target(), + action.expectedVersion(), + action.mutation(), + action.auditReason()); + + assertThatThrownBy( + () -> + coordinator.begin( + tuple.controlPlaneRequestId(), wrongNamespaceAction, CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + assertThatThrownBy(() -> coordinator.begin(tuple.controlPlaneRequestId(), action, "not-a-jwt")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("JWT envelope is malformed"); + assertThatThrownBy( + () -> + coordinator.begin( + tuple.controlPlaneRequestId(), action, CONTROL_UI_TOKEN + ".extra")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("JWT envelope is malformed"); + + SessionContext.setContext( + ACTOR_ID.toString(), + List.of(), + Map.of(TENANT_ID.toString(), List.of("moderator")), + false, + null, + null); + assertThatThrownBy( + () -> coordinator.begin(tuple.controlPlaneRequestId(), action, CONTROL_UI_TOKEN)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("tenantAdmin authority"); + + verifyNoInteractions(repository, accountClient); + } + + @Test + void beginAcceptsCanonicalCompactThreeSegmentJwtEnvelope() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-valid-jwt-envelope"); + Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); + when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); + + Result result = + coordinator.begin(tuple.controlPlaneRequestId(), tuple.action(), CONTROL_UI_TOKEN); + + assertThat(CONTROL_UI_TOKEN.split("\\.", -1)).hasSize(3); + assertThat(result.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); + verify(repository) + .acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L)); + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + } + + @Test + void changedTupleForExistingRequestConflictsWithoutAccountCall() { + StartSessionPreAuthorizationReservationTuple requested = tuple("coordinator-tuple-conflict"); + StartSessionOperatorAction action = requested.action(); + StartSessionOperatorAction changedAction = + new StartSessionOperatorAction( + action.actionFamilySchemaId(), + action.actionFamilySchemaVersion(), + action.scope(), + new StartSessionOperatorAction.Target(92L, action.target().ownerAccountId()), + action.expectedVersion(), + action.mutation(), + action.auditReason()); + StartSessionPreAuthorizationReservationTuple conflicting = + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + requested.controlPlaneRequestId(), changedAction); + Snapshot existing = snapshot(conflicting, State.AUTHORIZATION_PENDING, 1L, 1L); + when(repository.acquire( + eq(requested), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) + .thenReturn( + new StartSessionPreAuthorizationReservationRepository.AcquireResult(existing, false)); + + assertThatThrownBy(() -> coordinator.issueHuman(requested, CONTROL_UI_TOKEN)) + .isInstanceOf( + StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); + + verify(accountClient, never()) + .issueHuman(any(), anyString(), any(), anyLong(), any(), anyLong()); + verify(repository, never()) + .markAuthorizationPending( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyLong()); + } + + @Test + void productionReservationMutationRemainsDeniedByDefault() { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-default-denial"); + StartSessionPreAuthorizationReservationService productionDefault = + new StartSessionPreAuthorizationReservationService(repository); + + assertThatThrownBy(() -> productionDefault.acquire(tuple)) + .isInstanceOf(UnsupportedOperationException.class) + .hasMessageContaining("disabled for production construction"); + + verifyNoInteractions(repository); + } + + @Test + void missingIndependentAuthorizedReadbackLeavesAuthorizationUnknownAndDoesNotHandoff() + throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-readback-missing"); + stubInitialReservation(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); + stubAuthorizationEnrichment(tuple, true, true); + when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.AUTHORIZATION_READBACK_MISMATCH); + assertThat(result.snapshot().state()).isEqualTo(State.AUTHORIZED); + assertThat(result.handoff()).isNull(); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + } + + @Test + void conflictingIndependentAuthorizedReadbackCannotAdvanceOwnerPending() throws Exception { + StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-readback-conflict"); + stubInitialReservation(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); + stubAuthorizationEnrichment(tuple, true, true); + when(repository.findAuthorizedExact(eq(tuple))) + .thenAnswer( + invocation -> { + AuthorizedSnapshot exact = exactReadback.get(); + Snapshot snapshot = exact.reservationSnapshot(); + Snapshot substituted = + new Snapshot( + snapshot.tuple(), + snapshot.mutationDigest(), + snapshot.phase(), + snapshot.state(), + snapshot.reservationClaimFence(), + snapshot.claimFence(), + snapshot.claimExpiresAtEpochMillis() + 1L, + snapshot.claimState(), + snapshot.claimPurpose()); + return Optional.of( + new AuthorizedSnapshot( + substituted, + exact.postAuthorizationTuple(), + exact.reservationOwnerId(), + exact.currentClaimOwnerId(), + exact.handoff())); + }); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.AUTHORIZATION_READBACK_MISMATCH); + assertThat(result.handoff()).isNull(); + verify(repository, never()) + .beginOwnerExecution( + any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); + } + @Test void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-recovery"); @@ -203,7 +542,12 @@ void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception pending, ORIGINAL_OWNER))); when(accountClient.recover( eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) - .thenAnswer(invocation -> authorizationReference(tuple, ORIGINAL_OWNER, 1L)); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(1), + ((Number) invocation.getArgument(2)).longValue())); stubAuthorizationEnrichment(tuple, true, true); Result result = coordinator.recover(tuple); @@ -341,7 +685,12 @@ void recoverAndDispatchForwardsTheOriginalRecoveredOperationOnce() throws Except pending, ORIGINAL_OWNER))); when(accountClient.recover( eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) - .thenAnswer(invocation -> authorizationReference(tuple, ORIGINAL_OWNER, 1L)); + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(1), + ((Number) invocation.getArgument(2)).longValue())); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); @@ -391,6 +740,7 @@ void nonWinningAndUnavailableAuthorizationPathsNeverDispatchOwner() { eq(duplicateTuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) .thenReturn( new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); + when(repository.findAuthorizedExact(eq(duplicateTuple))).thenReturn(Optional.empty()); StartSessionPreAuthorizationReservationTuple unavailableTuple = tuple("coordinator-dispatch-unavailable"); when(repository.acquireRecoveryClaim( @@ -504,7 +854,9 @@ void ownerPendingTransitionFailureNeverReturnsTransientPayload() throws Exceptio .thenAnswer( invocation -> authorizationReference( - tuple, invocation.getArgument(2), invocation.getArgument(3))); + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); when(repository.beginOwnerExecution( eq(tuple), @@ -520,9 +872,14 @@ void ownerPendingTransitionFailureNeverReturnsTransientPayload() throws Exceptio new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( tuple.controlPlaneRequestId())); - assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) - .isInstanceOf( - StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason + .OWNER_PENDING_TRANSITION_OUTCOME_UNKNOWN); + assertThat(result.handoff()).isNull(); verify(repository) .completeAuthorization( eq(tuple), @@ -553,7 +910,8 @@ void uncertainAccountCallLeavesPendingAndIsNotRetried() { Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); when(repository.acquire(eq(tuple), any(UUID.class), eq(NOW_MILLIS), eq(NOW_MILLIS + 30_000L))) .thenReturn( - new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true)); + new StartSessionPreAuthorizationReservationRepository.AcquireResult(reserved, true), + new StartSessionPreAuthorizationReservationRepository.AcquireResult(pending, false)); when(repository.markAuthorizationPending( eq(tuple), eq(tuple.mutationDigest()), @@ -567,9 +925,17 @@ void uncertainAccountCallLeavesPendingAndIsNotRetried() { when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) .thenThrow(Status.UNAVAILABLE.asRuntimeException()); + when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); + + Result first = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + Result duplicate = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); - assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) - .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThat(first.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(first.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_ISSUANCE_OUTCOME_UNKNOWN); + assertThat(first.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); + assertThat(duplicate.progress()).isEqualTo(Progress.ALREADY_IN_PROGRESS); verify(repository, never()) .completeAuthorization( @@ -578,6 +944,9 @@ void uncertainAccountCallLeavesPendingAndIsNotRetried() { .beginOwnerExecution( any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); verify(accountClient, never()).recover(any(), any(), anyLong(), any(), anyLong()); + verify(accountClient, org.mockito.Mockito.times(1)) + .issueHuman( + eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong()); } @Test @@ -594,8 +963,11 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr (UUID) invocation.getArgument(2), ((Number) invocation.getArgument(3)).longValue())); - assertThatThrownBy(() -> coordinator.issueHuman(tuple, CONTROL_UI_TOKEN)) - .isInstanceOf(IllegalArgumentException.class); + Result invalidAccountResult = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(invalidAccountResult.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(invalidAccountResult.pendingReason()) + .contains(StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_RESPONSE_INVALID); verify(repository, never()) .completeAuthorization( any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), anyLong()); @@ -631,14 +1003,79 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( staleTuple.controlPlaneRequestId())); - assertThatThrownBy(() -> coordinator.issueHuman(staleTuple, CONTROL_UI_TOKEN)) - .isInstanceOf( - StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); + Result staleCompletion = coordinator.issueHuman(staleTuple, CONTROL_UI_TOKEN); + assertThat(staleCompletion.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(staleCompletion.pendingReason()) + .contains( + StartSessionAuthorizationCoordinator.PendingReason.LOCAL_COMPLETION_OUTCOME_UNKNOWN); verify(repository, never()) .beginOwnerExecution( any(), anyString(), any(), anyLong(), any(), anyLong(), anyString(), any(), anyLong()); } + @Test + void sourceFenceAndLinearizationMismatchesNeverReachLoggingCompletion() throws Exception { + List alteredTupleReferences = + List.of( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "25", + "18446744073709551615"), + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "24", + "18446744073709551614")); + int caseNumber = 0; + for (var alteredReference : alteredTupleReferences) { + StartSessionPreAuthorizationReservationTuple tuple = + tuple("coordinator-capture-reference-mismatch-" + caseNumber++); + stubInitialReservation(tuple); + when(accountClient.issueHuman( + eq(shared(tuple)), + anyString(), + any(UUID.class), + anyLong(), + any(UUID.class), + anyLong())) + .thenAnswer( + invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue(), + alteredReference)); + + Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); + + assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); + assertThat(result.pendingReason()) + .contains(StartSessionAuthorizationCoordinator.PendingReason.ACCOUNT_RESPONSE_INVALID); + verify(repository, never()) + .completeAuthorization( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + eq(NOW_MILLIS)); + verify(repository, never()) + .beginOwnerExecution( + eq(tuple), + eq(tuple.mutationDigest()), + any(UUID.class), + eq(1L), + any(UUID.class), + eq(1L), + anyString(), + any(UUID.class), + eq(NOW_MILLIS)); + } + } + private void stubInitialReservation(StartSessionPreAuthorizationReservationTuple tuple) { Snapshot reserved = snapshot(tuple, State.RESERVED, 1L, 1L); Snapshot pending = snapshot(tuple, State.AUTHORIZATION_PENDING, 1L, 1L); @@ -661,6 +1098,7 @@ private void stubAuthorizationEnrichment( StartSessionPreAuthorizationReservationTuple tuple, boolean transitioned, boolean mayDispatch) { + exactReadback.set(null); when(repository.completeAuthorization( eq(tuple), eq(tuple.mutationDigest()), @@ -693,12 +1131,15 @@ private void stubAuthorizationEnrichment( currentOwner.equals(reservationOwner) && currentFence == reservationFence ? ClaimPurpose.ORIGINAL : ClaimPurpose.AUTHORIZATION_RECOVERY); - return new StartSessionPreAuthorizationReservationRepository - .AuthorizationTransitionResult( + AuthorizedSnapshot authorizedSnapshot = new AuthorizedSnapshot( - authorized, postTuple, reservationOwner, currentOwner, null), - transitioned); + authorized, postTuple, reservationOwner, currentOwner, null); + exactReadback.set(authorizedSnapshot); + return new StartSessionPreAuthorizationReservationRepository + .AuthorizationTransitionResult(authorizedSnapshot, transitioned); }); + when(repository.findAuthorizedExact(eq(tuple))) + .thenAnswer(invocation -> Optional.ofNullable(exactReadback.get())); when(repository.beginOwnerExecution( eq(tuple), eq(tuple.mutationDigest()), @@ -733,26 +1174,39 @@ private void stubAuthorizationEnrichment( currentOwner.equals(reservationOwner) && currentFence == reservationFence ? ClaimPurpose.ORIGINAL : ClaimPurpose.AUTHORIZATION_RECOVERY); - return new StartSessionPreAuthorizationReservationRepository - .OwnerExecutionTransitionResult( + AuthorizedSnapshot ownerPendingSnapshot = new AuthorizedSnapshot( ownerPending, postTuple, reservationOwner, currentOwner, - new OwnerExecutionHandoff(handoffId)), - mayDispatch); + new OwnerExecutionHandoff(handoffId)); + exactReadback.set(ownerPendingSnapshot); + return new StartSessionPreAuthorizationReservationRepository + .OwnerExecutionTransitionResult(ownerPendingSnapshot, mayDispatch); }); } private static AuthorizationReference authorizationReference( - StartSessionPreAuthorizationReservationTuple tuple, UUID reservationOwner, long claimFence) + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwner, + long reservationFence) + throws Exception { + return authorizationReference(tuple, reservationOwner, reservationFence, bundleReference()); + } + + private static AuthorizationReference authorizationReference( + StartSessionPreAuthorizationReservationTuple tuple, + UUID reservationOwner, + long reservationFence, + StartSessionAuthorityEvidenceBundle.BundleReference tupleReference) throws Exception { AuthorizationReference response = mock(AuthorizationReference.class); when(response.operatorAuthorizationReference()).thenReturn(OPAQUE_REFERENCE); when(response.authorizationReferenceFingerprint()).thenReturn(FINGERPRINT); when(response.expiresAt()).thenReturn(NOW.plusSeconds(300)); - when(response.authorityEvidenceBundle()).thenReturn(bundleBytes(tuple, NOW.plusSeconds(300))); + byte[] bundle = bundleBytes(tuple, NOW.plusSeconds(300)); + when(response.authorityEvidenceBundle()).thenReturn(bundle); when(response.bundleReference()).thenReturn(bundleReference()); when(response.authenticatedLoggingWorkloadIdentity()).thenReturn(LOGGING_IDENTITY); when(response.postAuthorizationTuple()) @@ -762,9 +1216,9 @@ private static AuthorizationReference authorizationReference( LOGGING_IDENTITY, FINGERPRINT, reservationOwner, - claimFence, - bundleBytes(tuple, NOW.plusSeconds(300)), - bundleReference())); + reservationFence, + bundle, + tupleReference)); return response; } @@ -783,82 +1237,30 @@ private static StartSessionOwnerHandoffResult ownerEcho( } private static byte[] bundleBytes( - StartSessionPreAuthorizationReservationTuple tuple, Instant expiresAt) throws IOException { - String tenantId = TENANT_ID.toString(); - Map projection = - Map.of( - "sourceType", - "ACCOUNT", - "sourceEvidenceId", + StartSessionPreAuthorizationReservationTuple tuple, Instant expiresAt) { + return StartSessionAuthorityEvidenceBundleFixture.canonicalBytes( + shared(tuple), + new Values( + ISSUANCE_ID, "sha256:" + "a".repeat(64), - "sourceEvidenceVersion", "17", - "projectionStatus", "CURRENT", - "evaluatedAt", - NOW.toString(), - "expiresAt", - expiresAt.toString()); - Map authority = - Map.of( - "issuerAuthGeneration", 1L, - "accountAuthorityGeneration", 2L, - "tenantAuthorityGeneration", Map.of(tenantId, 3L), - "membershipAuthorityGeneration", Map.of(tenantId, 4L), - "privateRealmGrantVersions", List.of()); - Map evidence = - Map.of( - "evidenceType", - StartSessionAuthorityEvidenceBundle.HUMAN_EVIDENCE_TYPE, - "actorAccountId", - ACTOR_ID.toString(), - "controlUiTokenJti", - TOKEN_JTI.toString(), - "role", - "tenantAdmin", - "accountGeneration", + NOW, + expiresAt, + 1L, + 2L, + 3L, + 4L, + 5L, + 23L, + TOKEN_JTI, "2", - "tenantGeneration", - "3"); - Map bundle = - Map.of( - "bundleVersion", - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "authorityScope", - Map.of( - "scope", Map.of("tenantId", tenantId, "targetNamespace", "world-runtime"), - "actionFamily", tuple.actionFamily(), - "applicableAccountId", ACTOR_ID.toString(), - "applicableTenantId", tenantId), - "accountProjectionEvidence", - projection, - "issuanceOperationIdentity", - Map.of( - "issuanceOperationId", ISSUANCE_ID.toString(), - "controlPlaneRequestId", tuple.controlPlaneRequestId(), - "actionFamilyRequestIdentity", - Map.of( - "requestIdentityKind", - "controlPlaneRequestId", - "requestId", - tuple.controlPlaneRequestId()), - "mutationDigest", tuple.mutationDigest()), - "issuanceKind", - "human_operator", - "authorityTuple", - authority, - "membershipVersion", - Map.of(tenantId, 5L), - "issuanceFence", - "23", - "issuanceEvidence", - evidence); - return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(bundle)); + "3")); } private static StartSessionAuthorityEvidenceBundle.BundleReference bundleReference() { return new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "23", "18446744073709551615"); + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "18446744073709551615"); } private static Snapshot snapshot( From 6d98f3bd7e15255a246650ff575143f04b1e7add Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:01:56 +1300 Subject: [PATCH 02/10] Record fresh Logging qualification on the published Entity parent --- ...adr-0047-logging-admin-as-external-operator-write-ingress.md | 2 +- .../game-authoring-publishing-and-activation.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 48e32aef72..9d6d2cefdf 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -8,7 +8,7 @@ Accepted This ADR is partially implemented. Logging & Admin has current operator-facing read, investigation, admission-pointer read/audit, and prepared-upgrade proof-read surfaces, but no forwarded owner mutation family is currently supported as an executable external route until its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus owner-side redemption exist. The service-local `/moderation/actions` and `ApplyModerationAction` paths are present legacy transport stubs that now hard fail closed after their narrow tenant/admin checks: HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They have no external Gateway route, persist no separate fixed-category audit evidence, and perform no owner-side enforcement. The target Logging & Admin-owned moderation policy-input/audit path remains gated pending Account authorization-reference issuance plus Logging & Admin receiving-service validation/redemption; it does not require domain-owner redemption. The live `EvaluateModerationPolicy` read remains available only to its internal enforcement owners. Versioned policy propagation and owner enforcement remain target-state work. -The provisional original StartSession receiving candidate retains Account-returned tuple bytes through Logging completion, independent exact authorization readback and the one-time owner-pending handoff. Missing or substituted evidence and ambiguous transport or durable transitions fail closed; the coordinator and clients reject ambient SQL transactions or synchronization. The disabled-by-default composition, passive production reservation owner and absence of a routable StartSession ingress remain in force. The isolated candidate passes the complete local Logging check: 272 unit cases and 25 PostgreSQL/service integration cases, with zero failures, errors or skips. Eight unit-task cases use actual loopback mTLS against an explicitly synthetic Account handler; coordinator transition/readback cases use controlled owner doubles. These qualify their exercised receiving, transport and storage boundaries only. The intended receiving parent after the reconstructed Entity PRESEEDED boundary has not yet been materialized, so qualification on that parent remains pending. This source preparation supplies no genuine producer, activation or operational-region proof. +The original StartSession receiving candidate retains Account-returned tuple bytes through Logging completion, independent exact authorization readback and the one-time owner-pending handoff. Missing or substituted evidence and ambiguous transport or durable transitions fail closed; the coordinator and clients reject ambient SQL transactions or synchronization. The disabled-by-default composition, passive production reservation owner and absence of a routable StartSession ingress remain in force. The candidate passes the complete fresh local Logging check on the published Entity PRESEEDED receiving parent: 272 unit cases and 25 PostgreSQL/service integration cases, with zero failures, errors or skips. Eight unit-task cases use actual loopback mTLS against an explicitly synthetic Account handler; coordinator transition/readback cases use controlled owner doubles. These qualify their exercised receiving, transport and storage boundaries only. The actual receiving parent is #2967 at `e55cddcbdcd6e0107c9f5dbffe0aeb05bfd0c119`; all selected check tasks rebuilt and executed on that parent, with formatting, static and documentation checks passing. This source preparation supplies no genuine producer, activation or operational-region proof. ## Decision Record diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 1bcf4bcdea..7dedfc3598 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -A provisional Logging authorization receiving candidate is prepared on published parent #3125 at `1b89f28e82ecdae237a9cb71d9324cb5e3437103`. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The complete local Logging check passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. The intended receiving parent after the reconstructed Entity PRESEEDED boundary is unavailable; this candidate is neither published nor qualified on that parent. Account V164 receiving repair remains a separate source-carrier checkpoint. All genuine handoffs and broader Unit 1B remain held. +A Logging authorization receiving candidate is integrated locally on the published Entity PRESEEDED parent #2967 at `e55cddcbdcd6e0107c9f5dbffe0aeb05bfd0c119`. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The complete fresh Logging check on this actual receiving parent passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. All selected check tasks rebuilt and executed; remote publication is the next handoff. Account V164 receiving repair remains a separate source-carrier checkpoint. All genuine handoffs and broader Unit 1B remain held. At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved. From 08500160981e661fee624aa6d016aa2bc8ce612c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 18:52:05 +1300 Subject: [PATCH 03/10] Record qualified Logging carry on the current published parent --- ...adr-0047-logging-admin-as-external-operator-write-ingress.md | 2 +- .../game-authoring-publishing-and-activation.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md index 9d6d2cefdf..af5259049d 100644 --- a/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md +++ b/design/architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md @@ -8,7 +8,7 @@ Accepted This ADR is partially implemented. Logging & Admin has current operator-facing read, investigation, admission-pointer read/audit, and prepared-upgrade proof-read surfaces, but no forwarded owner mutation family is currently supported as an executable external route until its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus owner-side redemption exist. The service-local `/moderation/actions` and `ApplyModerationAction` paths are present legacy transport stubs that now hard fail closed after their narrow tenant/admin checks: HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They have no external Gateway route, persist no separate fixed-category audit evidence, and perform no owner-side enforcement. The target Logging & Admin-owned moderation policy-input/audit path remains gated pending Account authorization-reference issuance plus Logging & Admin receiving-service validation/redemption; it does not require domain-owner redemption. The live `EvaluateModerationPolicy` read remains available only to its internal enforcement owners. Versioned policy propagation and owner enforcement remain target-state work. -The original StartSession receiving candidate retains Account-returned tuple bytes through Logging completion, independent exact authorization readback and the one-time owner-pending handoff. Missing or substituted evidence and ambiguous transport or durable transitions fail closed; the coordinator and clients reject ambient SQL transactions or synchronization. The disabled-by-default composition, passive production reservation owner and absence of a routable StartSession ingress remain in force. The candidate passes the complete fresh local Logging check on the published Entity PRESEEDED receiving parent: 272 unit cases and 25 PostgreSQL/service integration cases, with zero failures, errors or skips. Eight unit-task cases use actual loopback mTLS against an explicitly synthetic Account handler; coordinator transition/readback cases use controlled owner doubles. These qualify their exercised receiving, transport and storage boundaries only. The actual receiving parent is #2967 at `e55cddcbdcd6e0107c9f5dbffe0aeb05bfd0c119`; all selected check tasks rebuilt and executed on that parent, with formatting, static and documentation checks passing. This source preparation supplies no genuine producer, activation or operational-region proof. +The original StartSession receiving candidate retains Account-returned tuple bytes through Logging completion, independent exact authorization readback and the one-time owner-pending handoff. Missing or substituted evidence and ambiguous transport or durable transitions fail closed; the coordinator and clients reject ambient SQL transactions or synchronization. The disabled-by-default composition, passive production reservation owner and absence of a routable StartSession ingress remain in force. The candidate passes the complete fresh local Logging check on the published Entity PRESEEDED receiving parent: 272 unit cases and 25 PostgreSQL/service integration cases, with zero failures, errors or skips. Eight unit-task cases use actual loopback mTLS against an explicitly synthetic Account handler; coordinator transition/readback cases use controlled owner doubles. These qualify their exercised receiving, transport and storage boundaries only. The actual receiving parent is #2967 at `9a1cbecf77857a98b0f300fdb14813e1d1de1496`; all selected check tasks rebuilt and executed on that parent, with formatting, static and documentation checks passing. This source preparation supplies no genuine producer, activation or operational-region proof. ## Decision Record diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 008c7c15a7..ea8c0c5f14 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -A Logging authorization receiving candidate is integrated locally on the published Entity PRESEEDED parent #2967 at `e55cddcbdcd6e0107c9f5dbffe0aeb05bfd0c119`. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The complete fresh Logging check on this actual receiving parent passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. All selected check tasks rebuilt and executed; remote publication is the next handoff. Account V164 receiving repair remains a separate source-carrier checkpoint. All genuine handoffs and broader Unit 1B remain held. +A Logging authorization receiving candidate is integrated locally on the published Entity PRESEEDED parent #2967 at `9a1cbecf77857a98b0f300fdb14813e1d1de1496`. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The complete fresh Logging check on this actual receiving parent passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. All selected check tasks rebuilt and executed; remote publication is the next handoff. Account V164 receiving repair remains a separate source-carrier checkpoint. All genuine handoffs and broader Unit 1B remain held. At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved. From beac96171112eaf5eeaca3edd9dc02de1317792d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 20:19:02 +1300 Subject: [PATCH 04/10] docs: qualify Logging receiving on current Entity parent --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index abf0121578..ad9f509cff 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -A Logging authorization receiving candidate is integrated locally on the published Entity PRESEEDED parent #2967 at `9a1cbecf77857a98b0f300fdb14813e1d1de1496`. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The complete fresh Logging check on this actual receiving parent passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. All selected check tasks rebuilt and executed; remote publication is the next handoff. Account V164 receiving repair remains a separate source-carrier checkpoint. All genuine handoffs and broader Unit 1B remain held. +Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the published Entity PRESEEDED parent #2967 at `cc29b837966f9c62783ab86a6c95d145660d3813`. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The complete fresh Logging check on this actual receiving parent passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. All 79 selected tasks rebuilt and executed. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved. From 0774da1c49c75ab6fd67330c7279b1b4390cdfa2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 20:56:18 +1300 Subject: [PATCH 05/10] Record qualified Logging carry on current published front --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 61f32eac85..d5cb66310a 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the published Entity PRESEEDED parent #2967 at `cc29b837966f9c62783ab86a6c95d145660d3813`. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The complete fresh Logging check on this actual receiving parent passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. All 79 selected tasks rebuilt and executed. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. +Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the published Entity PRESEEDED parent #2967 at `532620c8992a62e54bae0ce37a64736e1c5f2e8e`. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The complete fresh Logging check on this actual receiving parent passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. All 79 selected tasks rebuilt and executed. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved. From 958ba3d3b09808b0c30af82c0309db526188ac1a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:10:20 +1300 Subject: [PATCH 06/10] docs: distinguish preserved Logging proof after published parent carry --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 2c8c601901..f93da7ae83 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the published Entity PRESEEDED parent #2967 at `532620c8992a62e54bae0ce37a64736e1c5f2e8e`. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The complete fresh Logging check on this actual receiving parent passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. All 79 selected tasks rebuilt and executed. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. +Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the published Entity PRESEEDED parent #2967 at `1e1a0bea68ca7c3c18e56f780a62caaa1ff7f47b`. This normal parent carry preserves every Logging and Common dependency postimage from the previously qualified receiving source. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The prior complete fresh check on parent `532620c8992a62e54bae0ce37a64736e1c5f2e8e` passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks; all 79 selected tasks rebuilt and executed. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. That physical execution belongs to its prior source tuple; the unchanged receiving boundary carries forward without claiming a fresh physical run on the new parent. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved. From 24a421709466f5ea19946ae02877503d3ebbe7b0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:40:47 +1300 Subject: [PATCH 07/10] docs: carry unchanged Logging boundary onto latest published front --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index f93da7ae83..c70e19399f 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the published Entity PRESEEDED parent #2967 at `1e1a0bea68ca7c3c18e56f780a62caaa1ff7f47b`. This normal parent carry preserves every Logging and Common dependency postimage from the previously qualified receiving source. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The prior complete fresh check on parent `532620c8992a62e54bae0ce37a64736e1c5f2e8e` passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks; all 79 selected tasks rebuilt and executed. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. That physical execution belongs to its prior source tuple; the unchanged receiving boundary carries forward without claiming a fresh physical run on the new parent. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. +Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the published Entity PRESEEDED parent #2967 at `06b8c5d2432470cc2cc1b83312b861b2971cba36`. This normal parent carry preserves every Logging and Common dependency postimage from the previously qualified receiving source. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The prior complete fresh check on parent `532620c8992a62e54bae0ce37a64736e1c5f2e8e` passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks; all 79 selected tasks rebuilt and executed. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. That physical execution belongs to its prior source tuple; the unchanged receiving boundary carries forward without claiming a fresh physical run on the new parent. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved. From ad2999105c49b2a5280760b54a6a3776aa68bba1 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 23:26:15 +1300 Subject: [PATCH 08/10] Record latest published Entity parent in Logging receiving status --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index c70e19399f..466bf51ed5 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the published Entity PRESEEDED parent #2967 at `06b8c5d2432470cc2cc1b83312b861b2971cba36`. This normal parent carry preserves every Logging and Common dependency postimage from the previously qualified receiving source. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The prior complete fresh check on parent `532620c8992a62e54bae0ce37a64736e1c5f2e8e` passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks; all 79 selected tasks rebuilt and executed. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. That physical execution belongs to its prior source tuple; the unchanged receiving boundary carries forward without claiming a fresh physical run on the new parent. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. +Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the published Entity PRESEEDED parent #2967 at `6d93e3466b51079cb132d103b80b07dc1d3d0794`. This normal parent carry preserves every Logging and Common dependency postimage from the previously qualified receiving source. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The prior complete fresh check on parent `532620c8992a62e54bae0ce37a64736e1c5f2e8e` passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks; all 79 selected tasks rebuilt and executed. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. That physical execution belongs to its prior source tuple; the unchanged receiving boundary carries forward without claiming a fresh physical run on the new parent. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved. From fe34df45775e9ad2a7c7efd2fc819a20f93bd24e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 13 Oct 2026 23:39:22 +1300 Subject: [PATCH 09/10] Carry Logging receiving after passive Account source protection --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 466bf51ed5..4a4fbfb4e0 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the published Entity PRESEEDED parent #2967 at `6d93e3466b51079cb132d103b80b07dc1d3d0794`. This normal parent carry preserves every Logging and Common dependency postimage from the previously qualified receiving source. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The prior complete fresh check on parent `532620c8992a62e54bae0ce37a64736e1c5f2e8e` passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks; all 79 selected tasks rebuilt and executed. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. That physical execution belongs to its prior source tuple; the unchanged receiving boundary carries forward without claiming a fresh physical run on the new parent. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. +Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the passive Account storage parent [#3193](https://github.com/benhook1013/FireMUD/pull/3193) at `11262b79529a3489dc08906b2265275216ed6a9c`, including the published Entity PRESEEDED parent #2967 at `ad8a8f398a6c14e4e415c4980ddda3a24cd85559`. This normal parent carry preserves every Logging and Common dependency postimage from the previously qualified receiving source. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The prior complete fresh check on parent `532620c8992a62e54bae0ce37a64736e1c5f2e8e` passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks; all 79 selected tasks rebuilt and executed. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. That physical execution belongs to its prior source tuple; the unchanged receiving boundary carries forward without claiming a fresh physical run on the new parent. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved. From 139701387716b9f8b46c1a56a1db2a39f10c01d8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Wed, 14 Oct 2026 00:12:55 +1300 Subject: [PATCH 10/10] Carry Logging receiving onto latest Account parent --- .../game-authoring-publishing-and-activation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index c629bcd6fb..46cc8f208b 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status -Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the passive Account storage parent [#3193](https://github.com/benhook1013/FireMUD/pull/3193) at `11262b79529a3489dc08906b2265275216ed6a9c`, including the published Entity PRESEEDED parent #2967 at `ad8a8f398a6c14e4e415c4980ddda3a24cd85559`. This normal parent carry preserves every Logging and Common dependency postimage from the previously qualified receiving source. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The prior complete fresh check on parent `532620c8992a62e54bae0ce37a64736e1c5f2e8e` passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks; all 79 selected tasks rebuilt and executed. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. That physical execution belongs to its prior source tuple; the unchanged receiving boundary carries forward without claiming a fresh physical run on the new parent. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. +Logging receiving in [PR #3190](https://github.com/benhook1013/FireMUD/pull/3190) carries the passive Account storage parent [#3193](https://github.com/benhook1013/FireMUD/pull/3193) at `ec8b55044dce714467994bf2eaac503f26c27f59`, including the published Entity PRESEEDED parent #2967 at `e6d0b1616d3cf54f6597380389a067ca49c7baeb`. This normal parent carry preserves every Logging and Common dependency postimage from the previously qualified receiving source. It retains the original Account tuple through exact durable readback and one-time owner handoff, preserves default-off composition and file-backed mTLS policy, and keeps Account crypto, recovery and expiry protections. The prior complete fresh check on parent `532620c8992a62e54bae0ce37a64736e1c5f2e8e` passes 272 unit and 25 PostgreSQL/service integration cases without failures, errors or skips, plus formatting, static and documentation checks; all 79 selected tasks rebuilt and executed. Eight actual loopback mTLS cases use a synthetic Account handler; controlled coordinator doubles establish transition/readback behavior without genuine Account issuance. That physical execution belongs to its prior source tuple; the unchanged receiving boundary carries forward without claiming a fresh physical run on the new parent. Whole receiving reconciliation and Account protection convergence remain separately unqualified in #3105. All genuine handoffs and broader Unit 1B remain held. At `0c15969765bd0d48bbf78a4ea5ba93e959597c70`, the #3151 candidate freezes the approved asset delivery origin for exact repair and verifies metadata-only snapshots against database-computed source hashes and lengths. It stages one verified source payload at a time in private temporary files before shared object writes, and verifies object readback with bounded streams. V50 preserves retained candidates without an origin and fails their replay closed. Release-v2 selector binding is implemented by `PublishedReleaseBundleContract.requireSelectorBinding`; V49 and V49.1 schema execution is included in the focused migration proof. Source Validation `38205959330` (job `114670029762`) physically executed 400 unit and 75 PostgreSQL cases with zero failures, errors, or skips, including all 7 PublishAttempt cases and 12 snapshot PostgreSQL cases; no per-method counts are inferred. Rebuilt Runtime `38205959393` (job `114669861395`) failed before smoke because the pinned ECR base-image request returned HTTP 429 `Data limit exceeded`, so this head has no rebuilt runtime/smoke proof. Complete Draft mapping/quota admission, durable object-store candidate isolation, global purge fencing, and runtime activation remain unimplemented or unproved.