From 661b1c444023947b56891946ed29866a37f155cb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:46:38 +1300 Subject: [PATCH 01/16] Prepare retained direct-text authenticated lobby and frozen JOIN originals --- .../game-session-service/runtime-and-data.md | 8 + design/project-management/ai-observations.md | 3 + .../player-access-and-session.md | 2 + ...irectTextAuthenticatedLobbyRepository.java | 352 ++++++ .../DirectTextAuthenticatedLobbyCustody.java | 20 + .../DirectTextAuthenticatedLobbyJoin.java | 143 +++ .../DirectTextAuthenticatedLobbyOwner.java | 269 +++++ .../DirectTextAuthenticatedLobbyScope.java | 231 ++++ ...V1052__direct_text_authenticated_lobby.sql | 167 +++ ...TextAuthenticatedLobbyIntegrationTest.java | 1030 +++++++++++++++++ .../DirectTextAuthenticatedLobbyTest.java | 625 ++++++++++ 11 files changed, 2850 insertions(+) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyCustody.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index 47ebd4fce3..02c845519a 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -83,6 +83,14 @@ The sections below define the target-state runtime contract. Current implementat - Credential brute-force defense remains delegated to Account Service, which owns one login-attempt policy across transport paths using trusted source context. Game Session consumes the resulting auth outcomes when binding gameplay sessions but does not implement separate credential-abuse logic. The target ordinary gameplay limiter is an in-process session-front-end token bucket under [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); the current implementation still uses a Redis-backed per-session limiter and does not yet prove the target role isolation or loss behavior. Before a restart or takeover initializes a replacement bucket, the target owner atomically reserves from the binding's shared bounded cumulative handoff budget, so retries or concurrent replacements cannot reset or double-consume the remaining allowance. Optional coarse shared abuse windows remain outside the per-command fast path. - No single Game Session process may become the hidden source of truth for reconnectable gameplay state. If the service needs a value to survive non-edge restart or permit same-type takeover, that value must live in Redis or PostgreSQL-backed coordination rather than only in process memory. Realm admission additionally requires a fresh World lifecycle row/epoch read under [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); Temporal status is coordination evidence, not admission authority. +### Direct-text authenticated lobby companion + +The separately owned `game_session_direct_text_authenticated_lobby_scope`, `game_session_direct_text_authenticated_lobby_current` and `game_session_direct_text_authenticated_lobby_join` tables retain pre-admission lobby scope and JOIN-original state. They reference the original LOGIN journal without adding realm, tenant-admission or JOIN lifecycle to that minimal journal or its closed live-context codec. The [Authentication contract](../../system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) owns the caller-bound scope and logical-attempt behavior. + +New scope and dispatch claims serialize with original LOGIN abandonment through the parent row lock and exact original-coordinate/witness comparison. Current selection is separate from retained attempt history: replacing a selection or observing expiry cannot erase an older uncertain JOIN. A frozen JOIN original is committed and independently read back before dispatch becomes possible; an uncertain reply never resets that original or supplies a new request identity. Positive exact-original receipts may be retained after custody is lost, without applying them to a replacement transport or granting admission. + +This companion preserves the existing SQL retention hold. Direct deletion, truncation and invalid identity/state transitions are refused; no expiry-based release or cleanup API is supplied. Parent token disposal is not a membership JOIN outcome. Full negative-terminal qualification, unknown-result recovery and lawful release remain at their owning later boundary. Rows, decoded state and matching witnesses do not establish live socket authentication; each operation still needs its current verified Account result and protected receiving custody. Credentials and compact tokens are excluded from stored lobby state. Production composition and proof status are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#direct-text-join-client-and-command-receiving-preparation). + ### Protected Human initial-admission storage The protected reservation retains the complete Account protection and original owner association on the Game Session attempt. A separate immutable runtime-completion record binds that protection to the exact launch, captured `STARTING` row version, and completed `RUNNING` row version; this completion changes no admission pointer or terminal. The manually composed, final completion repository explicitly requires its caller's active writable `READ COMMITTED` transaction at runtime, without Spring transaction-proxy registration. The existing initial-admission owner later writes the pointer, matching append-only audit, and immutable protected attempt/intent terminal together, while the Account-purpose read exposes the retained exact terminal for settlement. Protected abort terminalizes only its own retained attempt and intent. Its `EXPECT_CLOSED` storage lookup verifies the immutable original CLOSED request/catalog/audit without locking a later current pointer; positive commit retains the current-origin checks. Legacy unprotected rows remain readable but are not adopted as protected attempts. These local storage owners remain unregistered; the [API contract](./api-contracts.md#initial-admission-bind) owns the cross-owner behavior and the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) records proof and remaining limits. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index c77266ec98..01d708d775 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -10,3 +10,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): Java filesystem read-only checks can miss same-device bind mounts. - A proposed `Files.getFileStore(path).isReadOnly()` guard was rejected before implementation: OpenJDK 21 discovers Linux boundaries using device changes and can attribute a bind mount to an ancestor with different read-only state. Exact current-process mountinfo, visible ancestry and pre/post comparison now preserve the readers’ owner/AtomicWriter guards; twelve physical mount cases pass. Next: qualify actual kubelet projection provenance at the existing held deployment boundary; local read-only evidence does not establish it. See [Game Session projection compatibility](../architecture/microservices/game-session-service/operations.md#protected-readiness-projection-compatibility). + +- `2026-11-01` (Pacific/Auckland): Review selection held without naming its failed source. + - Both initial #3365 channel selections returned only `source_unavailable`, without a linked review operation or actionable diagnostic, while an exact-head source refresh completed and verified the same open, ready comparison. Provider execution was not established. The original selection/source receipts were sent to FireController Worker; normal implementation continues while that owner explains the failed source and supported recovery. Next: retain the owner response and update this entry with the verified cause and outcome. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index fea6069a18..402e1646c9 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -380,6 +380,8 @@ R1407/R1408 prepare the direct-text observation and menu-retention boundary. The The current local source adds a manually composed Redis store and one-key CAS script for the public `WORLDS` UI menu. It retains the bounded ordered menu under the tenantless family owned by [the Redis menu contract](../../architecture/system-architecture-redis.md#direct-text-worlds-ui-menu), correlating the exact observed original proxy UUID separately from the numeric transport session ID. This is menu correlation only: it stores no Account ID, credentials, REALMS scope or JOIN intent, and does not prove authenticated ingress, continuity or admission. The owner and script remain unregistered; production protected-connection binding, authenticated TCP receiving custody and hidden rebind remain gaps, and no deployed ACL change is included. The combined focused gate passes 133 cases, including eight physical standalone-Redis cases, with no failures, errors or skips; selected main/test/integration static checks and full Java formatting pass. The first two aggregates retain binary-array generic-varargs analysis warnings; explicit single-key arrays and narrow, physically justified annotations complete the qualification. This remains controlled component proof, not authenticated transport custody or production registration. See [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status) for the local runtime consequence. +The next local direct-text preparation adds the separately owned [authenticated lobby SQL companion](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion), retaining the exact caller-bound Account scope and a durable frozen JOIN original before dispatch. Its current-selection pointer cannot replace earlier unknown attempts, and the existing original LOGIN journal/codec and retention hold remain. R1414 passes 29 focused unit cases and 16 real-PostgreSQL cases with zero failures, errors or skips. Physical proof migrates a populated pre-companion LOGIN journal, preserves its complete original row, exercises both abandonment/claim lock orders and concurrent dispatch claims, retains uncertain outcomes across owner replacement, rejects direct identity/transition/retention violations, and bounds positive membership identifiers to Account’s canonical positive BIGINT domain. Selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Game Session packaging pass across the combined recovery and final main-analysis gate; the first two aggregates retain broad-catch, generated-immutable-message analysis and test-fixture synchronization failures. The manually composed owner can issue scope and dispatch the frozen original through the existing Account client under a required protected-custody port, but no genuine producer for that port or text-command registration is supplied. Fresh source-built startup qualification is pending. This does not wire live REALMS/JOIN text dispatch, prove genuine receiving custody, register a production owner, settle negative/unknown results, release retained rows or establish admission. + ### Account operation and signer source preparation [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql) adds one immutable cleanup deadline to newly prepared Control-UI owner rows, separate from the JWT `exp` horizon and bound to the same registry bytes and Redis readback receipt. The retained-row migration case in [AccountControlUiIssuancePostgresIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java) confirms that a pre-deadline row keeps its original fields, retains a null deadline, and is denied current use and advancement after migration. Direct PostgreSQL proof that a newly recorded deadline cannot be changed is still missing. The preparation remains source-only under AA-1.3; bounded cleanup and late revocation remain incomplete, and token issuance is not activated. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java new file mode 100644 index 0000000000..ce8ff2ccc6 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java @@ -0,0 +1,352 @@ +package net.firedevops.firemud.gamesession.repository; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.sql.Connection; +import java.sql.SQLException; +import java.time.Clock; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin.State; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered companion owner. Writes require the caller's writable READ COMMITTED transaction; + * independent primary readback is mandatory before remote effects. Protected DB delivery and + * current authenticated custody belong to composition, never to decoded SQL evidence. + */ +public final class DirectTextAuthenticatedLobbyRepository { + public static final String SCOPE = "game_session_direct_text_authenticated_lobby_scope"; + public static final String CURRENT = "game_session_direct_text_authenticated_lobby_current"; + public static final String JOIN = "game_session_direct_text_authenticated_lobby_join"; + private static final String ORIGINAL = "game_session_initial_gameplay_login_journal"; + private final DSLContext dsl; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "The injected transaction-bound DSLContext must remain shared with its owner") + public DirectTextAuthenticatedLobbyRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + /** Serializes with actual parent abandonment, not a companion boolean or an unlocked snapshot. */ + public void verifyOriginal( + InitialGameplayLoginAttemptCoordinates original, CanonicalGameplayLoginResult verified) { + lockOriginal(original, verified, false); + } + + public void retainScope( + DirectTextAuthenticatedLobbyScope scope, CanonicalGameplayLoginResult verified, Clock clock) { + lockOriginal(scope.original(), verified, false); + requireEvidence(scope, verified); + scope.requireCurrent(scope.original(), verified, scope.transport(), clock); + byte[] bytes = scope.encode(); + var e = verified.evidence(); + dsl.execute( + "INSERT INTO " + + SCOPE + + " (scope_record_id, original_request_id," + + " original_caller_context_id, original_attempt_fence, account_id, proxy_connection_id," + + " transport_session_id, verified_token_jti, verified_token_sha256," + + " verified_token_generation, verified_issuance_fence, scope_bytes)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + scope.recordId(), + scope.original().requestId(), + scope.original().callerContextId(), + scope.original().expectedAttemptFence(), + e.accountId(), + scope.transport().proxyConnectionId(), + scope.transport().transportSessionId(), + e.tokenJti(), + e.tokenSha256(), + Long.parseLong(e.tokenGeneration()), + Long.parseLong(e.issuanceFence()), + bytes); + var retained = requiredScope(dsl, scope.recordId()); + requireExact(scope, retained); + dsl.execute( + "INSERT INTO " + + CURRENT + + " (original_request_id, scope_record_id, scope_sequence)" + + " SELECT original_request_id, scope_record_id, scope_sequence FROM " + + SCOPE + + " WHERE scope_record_id = ? ON CONFLICT (original_request_id) DO UPDATE" + + " SET scope_record_id = EXCLUDED.scope_record_id, scope_sequence = EXCLUDED.scope_sequence", + scope.recordId()); + } + + public DirectTextAuthenticatedLobbyScope current( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + ObservedDirectTextTransport transport, + Clock clock) { + lockOriginal(original, verified, false); + Record row = + dsl.fetchOne( + "SELECT s.* FROM " + + SCOPE + + " s JOIN " + + CURRENT + + " c ON c.scope_record_id = s.scope_record_id WHERE c.original_request_id = ?", + original.requestId()); + if (row == null) throw unavailable(); + var scope = decodeScope(row); + scope.requireCurrent(original, verified, transport, clock); + return scope; + } + + /** Exactly one attempt per retained scope; concurrent continuations read the winner's request. */ + public DirectTextAuthenticatedLobbyJoin freezeCurrentJoin( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + ObservedDirectTextTransport transport, + Clock clock) { + var scope = current(original, verified, transport, clock); + Record prior = joinRow(dsl, scope.recordId()); + if (prior != null) return decodeJoin(scope, prior); + UUID requestId; + do { + requestId = UUID.randomUUID(); + } while (requestId.equals(original.requestId()) + || requestId.equals(original.callerContextId()) + || requestId.equals(scope.recordId()) + || requestId.equals(transport.proxyConnectionId()) + || requestId.equals(verified.evidence().tokenJti())); + var frozen = + new DirectTextAuthenticatedLobbyJoin( + scope, + DirectTextAuthenticatedLobbyJoin.requestFor(scope, requestId), + State.NEVER_DISPATCHED, + Optional.empty()); + dsl.execute( + "INSERT INTO " + + JOIN + + " (scope_record_id, join_request_id, request_bytes, state) VALUES (?, ?, ?, 'NEVER_DISPATCHED')", + scope.recordId(), + requestId, + frozen.request().toByteArray()); + return decodeJoin(scope, Objects.requireNonNull(joinRow(dsl, scope.recordId()))); + } + + /** One irreversible authorization. A false result NEVER permits an additional Account call. */ + public boolean claimDispatch( + DirectTextAuthenticatedLobbyJoin expected, + CanonicalGameplayLoginResult verified, + ObservedDirectTextTransport transport, + Clock clock) { + var scope = current(expected.scope().original(), verified, transport, clock); + requireExact(expected.scope(), scope); + var retained = decodeJoin(scope, Objects.requireNonNull(joinRow(dsl, scope.recordId()))); + requireSameRequest(expected, retained); + if (retained.state() != State.NEVER_DISPATCHED) return false; + if (dsl.execute( + "UPDATE " + + JOIN + + " SET state = 'DISPATCH_POSSIBLE' WHERE scope_record_id = ? AND state = 'NEVER_DISPATCHED'", + scope.recordId()) + != 1) throw unavailable(); + return true; + } + + /** + * Historical retention only. Exact in-flight success can survive abandonment, custody loss, + * expiry and a newer selection; none of these writes applies a result to a transport. + */ + public void recordPositiveReply( + DirectTextAuthenticatedLobbyJoin expected, + CanonicalGameplayLoginResult verified, + JoinPublicProductionMembershipResponse reply) { + var scope = expected.scope(); + lockOriginal(scope.original(), verified, true); + requireEvidence(scope, verified); + DirectTextAuthenticatedLobbyJoin.requirePositiveReply(scope, reply); + var retainedScope = requiredScope(dsl, scope.recordId()); + requireExact(scope, retainedScope); + var retained = + decodeJoin(retainedScope, Objects.requireNonNull(joinRow(dsl, scope.recordId()))); + requireSameRequest(expected, retained); + if (retained.state() == State.COMPLETED) { + if (!retained.reply().filter(reply::equals).isPresent()) throw unavailable(); + return; + } + if (retained.state() != State.DISPATCH_POSSIBLE) throw unavailable(); + dsl.execute( + "UPDATE " + JOIN + " SET state = 'COMPLETED', reply_bytes = ? WHERE scope_record_id = ?", + reply.toByteArray(), + scope.recordId()); + } + + public DirectTextAuthenticatedLobbyScope readCommittedScope( + DirectTextAuthenticatedLobbyScope expected) { + requireNoTransaction(); + return dsl.connectionResult( + connection -> { + requireConnection(connection, false); + var result = + requiredScope(DSL.using(connection, SQLDialect.POSTGRES), expected.recordId()); + requireExact(expected, result); + return result; + }); + } + + public DirectTextAuthenticatedLobbyJoin readCommittedJoin( + DirectTextAuthenticatedLobbyJoin expected) { + requireNoTransaction(); + return dsl.connectionResult( + connection -> { + requireConnection(connection, false); + var reader = DSL.using(connection, SQLDialect.POSTGRES); + var scope = requiredScope(reader, expected.scope().recordId()); + requireExact(expected.scope(), scope); + Record row = joinRow(reader, scope.recordId()); + if (row == null) throw unavailable(); + var result = decodeJoin(scope, row); + requireSameRequest(expected, result); + return result; + }); + } + + private void lockOriginal( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + boolean allowAbandoned) { + requireMutation(); + var e = Objects.requireNonNull(verified).evidence(); + if (!original.requestId().equals(e.requestId()) + || !original.callerContextId().equals(e.callerContextId())) throw unavailable(); + Record row = + dsl.fetchOne( + "SELECT * FROM " + ORIGINAL + " WHERE request_id = ? FOR UPDATE", original.requestId()); + if (row == null + || !original.callerContextId().equals(row.get("caller_context_id", UUID.class)) + || !Long.valueOf(original.expectedAttemptFence()) + .equals(row.get("expected_attempt_fence", Long.class)) + || row.get("abandoned", Boolean.class) == null + || !allowAbandoned && !Boolean.FALSE.equals(row.get("abandoned", Boolean.class)) + || !e.tokenJti().equals(row.get("verified_token_jti", UUID.class)) + || !e.tokenSha256().equals(row.get("verified_token_sha256", String.class)) + || !Long.valueOf(Long.parseLong(e.tokenGeneration())) + .equals(row.get("verified_token_generation", Long.class)) + || !Long.valueOf(Long.parseLong(e.issuanceFence())) + .equals(row.get("verified_issuance_fence", Long.class))) throw unavailable(); + } + + private static DirectTextAuthenticatedLobbyScope requiredScope(DSLContext reader, UUID id) { + Record row = reader.fetchOne("SELECT * FROM " + SCOPE + " WHERE scope_record_id = ?", id); + if (row == null) throw unavailable(); + return decodeScope(row); + } + + private static DirectTextAuthenticatedLobbyScope decodeScope(Record row) { + var scope = DirectTextAuthenticatedLobbyScope.decode(row.get("scope_bytes", byte[].class)); + var e = scope.evidence(); + if (!scope.recordId().equals(row.get("scope_record_id", UUID.class)) + || !scope.original().requestId().equals(row.get("original_request_id", UUID.class)) + || !scope + .original() + .callerContextId() + .equals(row.get("original_caller_context_id", UUID.class)) + || !Long.valueOf(scope.original().expectedAttemptFence()) + .equals(row.get("original_attempt_fence", Long.class)) + || !e.accountId().equals(row.get("account_id", UUID.class)) + || !scope.transport().proxyConnectionId().equals(row.get("proxy_connection_id", UUID.class)) + || !scope + .transport() + .transportSessionId() + .equals(row.get("transport_session_id", String.class)) + || !e.tokenJti().equals(row.get("verified_token_jti", UUID.class)) + || !e.tokenSha256().equals(row.get("verified_token_sha256", String.class)) + || !Long.valueOf(Long.parseLong(e.tokenGeneration())) + .equals(row.get("verified_token_generation", Long.class)) + || !Long.valueOf(Long.parseLong(e.issuanceFence())) + .equals(row.get("verified_issuance_fence", Long.class))) throw unavailable(); + return scope; + } + + private static Record joinRow(DSLContext reader, UUID scopeId) { + return reader.fetchOne("SELECT * FROM " + JOIN + " WHERE scope_record_id = ?", scopeId); + } + + private static DirectTextAuthenticatedLobbyJoin decodeJoin( + DirectTextAuthenticatedLobbyScope scope, Record row) { + var request = + DirectTextAuthenticatedLobbyJoin.decodeRequest(row.get("request_bytes", byte[].class)); + byte[] bytes = row.get("reply_bytes", byte[].class); + var result = + new DirectTextAuthenticatedLobbyJoin( + scope, + request, + State.valueOf(row.get("state", String.class)), + bytes == null + ? Optional.empty() + : Optional.of(DirectTextAuthenticatedLobbyJoin.decodeReply(scope, bytes))); + if (!scope.recordId().equals(row.get("scope_record_id", UUID.class)) + || !result.requestId().equals(row.get("join_request_id", UUID.class))) throw unavailable(); + return result; + } + + private static void requireEvidence( + DirectTextAuthenticatedLobbyScope scope, CanonicalGameplayLoginResult verified) { + if (!scope.evidence().equals(verified.evidence())) throw unavailable(); + } + + private static void requireExact( + DirectTextAuthenticatedLobbyScope expected, DirectTextAuthenticatedLobbyScope actual) { + if (!Arrays.equals(expected.encode(), actual.encode())) throw unavailable(); + } + + private static void requireSameRequest( + DirectTextAuthenticatedLobbyJoin expected, DirectTextAuthenticatedLobbyJoin actual) { + if (!expected.request().equals(actual.request())) throw unavailable(); + } + + private void requireMutation() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) + throw unavailable(); + dsl.connectionResult( + connection -> { + requireConnection(connection, true); + return null; + }); + } + + private static void requireConnection(Connection connection, boolean mutation) + throws SQLException { + if (connection.getAutoCommit() == mutation + || connection.isReadOnly() + || mutation + && connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + throw unavailable(); + Record settings = + DSL.using(connection, SQLDialect.POSTGRES) + .fetchOne( + "SELECT pg_is_in_recovery() AS recovery, current_setting('synchronous_commit') AS durability"); + if (settings == null + || !Boolean.FALSE.equals(settings.get("recovery", Boolean.class)) + || !List.of("on", "remote_write", "remote_apply") + .contains(settings.get("durability", String.class))) throw unavailable(); + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Exact retained direct-text lobby state is unavailable"); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyCustody.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyCustody.java new file mode 100644 index 0000000000..18b3afd951 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyCustody.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.gamesession.service.directtext; + +import java.util.function.Function; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; + +/** + * Missing protected receiving producer, deliberately not a bean or an observation-to-authority + * adapter. Implementations must authenticate the current exact original/result association and pin + * its private-result and transport custody for the entire callback, excluding replacement, closure + * and reset. A UUID observation, SQL witness or boolean current flag cannot implement this + * contract. Implementations must not retain the borrowed result beyond the current invocation. + */ +public interface DirectTextAuthenticatedLobbyCustody { + T withCurrent( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult borrowedResult, + Function action); +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java new file mode 100644 index 0000000000..d23c662859 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyJoin.java @@ -0,0 +1,143 @@ +package net.firedevops.firemud.gamesession.service.directtext; + +import com.google.protobuf.InvalidProtocolBufferException; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipRequest; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.shared.v1.PlayerExecutionContext; + +/** Exact frozen request and optional historical positive reply; never a gameplay binding. */ +@SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "Generated protobuf messages are immutable; no builders are retained or exposed") +public record DirectTextAuthenticatedLobbyJoin( + DirectTextAuthenticatedLobbyScope scope, + JoinPublicProductionMembershipRequest request, + State state, + Optional reply) { + public static final int MAX_REQUEST_BYTES = 8192; + public static final int MAX_REPLY_BYTES = 1024; + + public enum State { + NEVER_DISPATCHED, + DISPATCH_POSSIBLE, + COMPLETED + } + + public DirectTextAuthenticatedLobbyJoin { + if (scope == null || request == null || state == null || reply == null) throw invalid(); + UUID id; + try { + id = UUID.fromString(request.getRequestId()); + DirectTextAuthenticatedLobbyScope.requireV4(id); + } catch (RuntimeException malformed) { + throw invalid(); + } + if (!id.toString().equals(request.getRequestId()) + || id.equals(scope.original().requestId()) + || id.equals(scope.original().callerContextId()) + || id.equals(scope.recordId()) + || id.equals(scope.transport().proxyConnectionId()) + || id.equals(scope.evidence().tokenJti()) + || request.getSerializedSize() > MAX_REQUEST_BYTES + || !request.equals(requestFor(scope, id)) + || (state == State.COMPLETED) != reply.isPresent()) throw invalid(); + reply.ifPresent(value -> requirePositiveReply(scope, value)); + } + + public UUID requestId() { + return UUID.fromString(request.getRequestId()); + } + + public static PlayerExecutionContext contextFor( + DirectTextAuthenticatedLobbyScope scope, UUID id) { + return contextFor( + scope.evidence().accountId().toString(), scope.transport(), scope.issued().target(), id); + } + + public static PlayerExecutionContext contextFor( + String accountId, + net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport transport, + net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget target, + UUID id) { + DirectTextAuthenticatedLobbyScope.requireV4(id); + return PlayerExecutionContext.newBuilder() + .setAccountId(accountId) + .setTenantId(target.tenantId()) + .setRealmId(target.realmId()) + .setPlayableStateNamespaceId(target.playableStateNamespaceId()) + .setPlayableStateScope(target.playableStateScope()) + .setGameInstanceId(target.gameInstanceId()) + .setSessionId(transport.transportSessionId()) + .setRequestId(id.toString()) + .build(); + } + + public static JoinPublicProductionMembershipRequest requestFor( + DirectTextAuthenticatedLobbyScope scope, UUID id) { + return JoinPublicProductionMembershipRequest.newBuilder() + .setPlayerContext(contextFor(scope, id)) + .setConnectScopeId(scope.issued().connectScopeId()) + .setRequestId(id.toString()) + .build(); + } + + public static JoinPublicProductionMembershipRequest decodeRequest(byte[] bytes) { + try { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_REQUEST_BYTES) throw invalid(); + var request = JoinPublicProductionMembershipRequest.parseFrom(bytes); + if (!request.getUnknownFields().asMap().isEmpty() + || !request.hasPlayerContext() + || !request.getPlayerContext().getUnknownFields().asMap().isEmpty() + || !Arrays.equals(bytes, request.toByteArray())) throw invalid(); + return request; + } catch (InvalidProtocolBufferException | RuntimeException failure) { + throw invalid(); + } + } + + public static JoinPublicProductionMembershipResponse decodeReply( + DirectTextAuthenticatedLobbyScope scope, byte[] bytes) { + try { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_REPLY_BYTES) throw invalid(); + var reply = JoinPublicProductionMembershipResponse.parseFrom(bytes); + requirePositiveReply(scope, reply); + if (!Arrays.equals(bytes, reply.toByteArray())) throw invalid(); + return reply; + } catch (InvalidProtocolBufferException | RuntimeException failure) { + throw invalid(); + } + } + + /** AccountClient's locally manufactured errors cannot prove a negative terminal operation. */ + public static void requirePositiveReply( + DirectTextAuthenticatedLobbyScope scope, JoinPublicProductionMembershipResponse reply) { + if (reply == null + || !reply.getUnknownFields().asMap().isEmpty() + || reply.hasError() + || !reply.getSuccess() + || !Set.of("JOINED", "ALREADY_ACTIVE").contains(reply.getOutcomeCode()) + || !scope.evidence().accountId().toString().equals(reply.getAccountId()) + || !scope.issued().target().tenantId().equals(reply.getTenantId()) + || !reply.getMembershipId().matches("[1-9][0-9]{0,18}") + || reply.getMembershipVersion() <= 0 + || reply.getMembershipAuthorityGeneration() <= 0 + || reply.getSerializedSize() > MAX_REPLY_BYTES) throw invalid(); + RequestIdValidation.requirePositiveLong(reply.getMembershipId(), "membershipId"); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact bounded lobby JOIN original required"); + } + + @Override + public String toString() { + return "DirectTextAuthenticatedLobbyJoin[nonsecret,non-admitting]"; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java new file mode 100644 index 0000000000..7ba5b8c1ff --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java @@ -0,0 +1,269 @@ +package net.firedevops.firemud.gamesession.service.directtext; + +import java.time.Clock; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.DirectTextAuthenticatedLobbyRepository; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Manually composed, unregistered public-only lobby preparation. It borrows the current verified + * private LOGIN result on every operation, never stores it on the service, and never calls + * Authenticate, performs cleanup, selects an actor, binds gameplay or publishes wire success. + */ +public final class DirectTextAuthenticatedLobbyOwner { + private final DirectTextAuthenticatedLobbyRepository repository; + private final DirectTextWorldSelectionService selections; + private final AccountClient account; + private final Clock clock; + private final TransactionTemplate transaction; + + public DirectTextAuthenticatedLobbyOwner( + DirectTextAuthenticatedLobbyRepository repository, + DirectTextWorldSelectionService selections, + AccountClient account, + PlatformTransactionManager transactionManager, + Clock clock) { + this.repository = Objects.requireNonNull(repository); + this.selections = Objects.requireNonNull(selections); + this.account = Objects.requireNonNull(account); + this.clock = Objects.requireNonNull(clock); + transaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + + /** + * One fresh explicit REALMS intent, from this selection owner's genuine guarded public handle. + * Scope issuance has no recoverable request identity: an unknown response is never reissued. + * Returned evidence is internal composition data, not a client-facing response. + */ + public DirectTextAuthenticatedLobbyScope realms( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + DirectTextAuthenticatedLobbyCustody custody, + DirectTextWorldSelectionService.SelectionSnapshot menu, + String selector) { + requireNoTransaction(); + return current( + original, + verified, + custody, + transport -> { + transaction.executeWithoutResult(status -> repository.verifyOriginal(original, verified)); + var target = + selections + .resolve(menu, selector) + .orElseThrow(DirectTextAuthenticatedLobbyOwner::unavailable); + var accountTarget = DirectTextAuthenticatedLobbyScope.targetFor(target); + UUID scopeRecordId = distinctId(original, verified, transport, null); + UUID scopeRequestId = distinctId(original, verified, transport, scopeRecordId); + var context = + DirectTextAuthenticatedLobbyJoin.contextFor( + verified.evidence().accountId().toString(), + transport, + accountTarget, + scopeRequestId); + DirectTextAuthenticatedLobbyScope.requireLiveResult(original, verified, clock); + // Account call is outside SQL. No fallback, retry, private/playtest branch or arbitrary + // target. + var response = account.issueDirectTextConnectScope(context, accountTarget); + if (response == null + || response.getSerializedSize() > 8192 + || !response.getUnknownFields().asMap().isEmpty()) throw unavailable(); + var issued = + DirectTextIssuedConnectScope.fromAccountResponse( + verified.evidence().accountId().toString(), accountTarget, response, clock); + var scope = + new DirectTextAuthenticatedLobbyScope( + scopeRecordId, + InitialGameplayLoginContextState.installed(original, verified), + transport, + target, + issued); + scope.requireCurrent(original, verified, transport, clock); + transaction.executeWithoutResult( + status -> repository.retainScope(scope, verified, clock)); + var committed = repository.readCommittedScope(scope); + committed.requireCurrent(original, verified, transport, clock); + return committed; + }); + } + + /** + * Explicit JOIN of the retained CURRENT scope only. Concurrent or interrupted continuations use + * the same committed request. Only the single dispatch-claim winner calls Account; neither this + * owner nor a replacement owner re-arms a dispatch-possible original. AccountClient's bounded + * same-invocation retry uses the identical frozen request, not another logical attempt. + */ + public Observation join( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + DirectTextAuthenticatedLobbyCustody custody) { + requireNoTransaction(); + var frozen = + current( + original, + verified, + custody, + transport -> + transaction.execute( + status -> repository.freezeCurrentJoin(original, verified, transport, clock))); + var committed = repository.readCommittedJoin(Objects.requireNonNull(frozen)); + boolean claimed = + current( + original, + verified, + custody, + transport -> + Boolean.TRUE.equals( + transaction.execute( + status -> + repository.claimDispatch(committed, verified, transport, clock)))); + if (!claimed) return observe(committed, original, verified, custody); + + // An ambiguous claim COMMIT/readback throws before Account. The persisted possible state is + // irreversible even if no RPC actually happened; later continuations cannot invent rollback. + var possible = repository.readCommittedJoin(committed); + if (possible.state() != DirectTextAuthenticatedLobbyJoin.State.DISPATCH_POSSIBLE) + throw unavailable(); + JoinPublicProductionMembershipResponse response = + current( + original, + verified, + custody, + transport -> { + possible.scope().requireCurrent(original, verified, transport, clock); + transaction.executeWithoutResult( + status -> { + var selected = repository.current(original, verified, transport, clock); + if (!selected.recordId().equals(possible.scope().recordId())) + throw unavailable(); + }); + var request = possible.request(); + return account.joinPublicProductionMembership( + request.getPlayerContext(), + request.getConnectScopeId(), + request.getRequestId(), + possible.scope().issued().connectScopeExpiresAtInstant()); + }); + try { + DirectTextAuthenticatedLobbyJoin.requirePositiveReply(possible.scope(), response); + } catch (IllegalArgumentException unknown) { + // Includes every generic local/transport/preflight error. No false terminal receipt. + return observe(possible, original, verified, custody); + } + // A positively correlated in-flight reply remains retainable even if custody is now lost or + // the original abandoned. This is historical SQL persistence, NOT reply application. + transaction.executeWithoutResult( + status -> repository.recordPositiveReply(possible, verified, response)); + var retained = repository.readCommittedJoin(possible); + if (!retained.reply().filter(response::equals).isPresent()) throw unavailable(); + return observe(retained, original, verified, custody); + } + + private Observation observe( + DirectTextAuthenticatedLobbyJoin originalJoin, + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + DirectTextAuthenticatedLobbyCustody custody) { + var retained = repository.readCommittedJoin(originalJoin); + try { + return current( + original, + verified, + custody, + transport -> { + var selected = + transaction.execute( + status -> repository.current(original, verified, transport, clock)); + if (selected == null || !selected.recordId().equals(retained.scope().recordId())) + throw unavailable(); + retained.scope().requireCurrent(original, verified, transport, clock); + return new Observation( + retained.scope().recordId(), + retained.requestId(), + retained.reply().isPresent() + ? Status.COMPLETED_CURRENT_NON_ADMITTING + : Status.RETAINED_UNRESOLVED, + retained.reply()); + }); + } catch (RuntimeException noCurrentAuthority) { + return new Observation( + retained.scope().recordId(), + retained.requestId(), + Status.HISTORICAL_ONLY, + Optional.empty()); + } + } + + private T current( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + DirectTextAuthenticatedLobbyCustody custody, + Function action) { + DirectTextAuthenticatedLobbyScope.requireLiveResult(original, verified, clock); + return Objects.requireNonNull(custody) + .withCurrent( + original, + verified, + transport -> { + Objects.requireNonNull(transport); + DirectTextAuthenticatedLobbyScope.requireLiveResult(original, verified, clock); + return action.apply(transport); + }); + } + + private static UUID distinctId( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + ObservedDirectTextTransport transport, + UUID other) { + UUID id; + do { + id = UUID.randomUUID(); + } while (id.equals(original.requestId()) + || id.equals(original.callerContextId()) + || id.equals(transport.proxyConnectionId()) + || id.equals(verified.evidence().tokenJti()) + || id.equals(other)); + return id; + } + + private static void requireNoTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException( + "Current authenticated direct-text lobby custody is unavailable"); + } + + public enum Status { + RETAINED_UNRESOLVED, + COMPLETED_CURRENT_NON_ADMITTING, + HISTORICAL_ONLY + } + + /** + * Historical membership observation only; currentReply is AS-OF this protected call's final + * selection check. It cannot authenticate, install a binding, or authorize actor selection/PLAY. + */ + public record Observation( + UUID scopeRecordId, + UUID requestId, + Status status, + Optional currentReply) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java new file mode 100644 index 0000000000..375b357d69 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyScope.java @@ -0,0 +1,231 @@ +package net.firedevops.firemud.gamesession.service.directtext; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.gamesession.client.DirectTextConnectScopeTarget; +import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.MapperFeature; +import tools.jackson.databind.json.JsonMapper; + +/** Immutable nonsecret historical evidence. Neither construction nor decoding authenticates. */ +public final class DirectTextAuthenticatedLobbyScope { + public static final int MAX_BYTES = 128 * 1024; + private static final String SCHEMA = "direct-text-authenticated-lobby/v1"; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .enable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + .build(); + + private final UUID recordId; + private final InitialGameplayLoginContextState login; + private final ObservedDirectTextTransport transport; + private final CanonicalPlayableTarget publicTarget; + private final DirectTextIssuedConnectScope issued; + + public DirectTextAuthenticatedLobbyScope( + UUID recordId, + InitialGameplayLoginContextState login, + ObservedDirectTextTransport transport, + CanonicalPlayableTarget publicTarget, + DirectTextIssuedConnectScope issued) { + requireV4(recordId); + this.recordId = recordId; + this.login = Objects.requireNonNull(login); + this.transport = Objects.requireNonNull(transport); + this.publicTarget = Objects.requireNonNull(publicTarget); + this.issued = Objects.requireNonNull(issued); + if (login.state() != InitialGameplayLoginContextState.State.INSTALLED + || !login.evidence().accountId().toString().equals(issued.accountId()) + || !targetFor(publicTarget).equals(issued.target()) + || recordId.equals(login.coordinates().requestId()) + || recordId.equals(login.coordinates().callerContextId()) + || recordId.equals(transport.proxyConnectionId()) + || recordId.equals(login.evidence().tokenJti()) + || transport.transportSessionId().length() > 32) throw invalid(); + } + + public UUID recordId() { + return recordId; + } + + public InitialGameplayLoginAttemptCoordinates original() { + return login.coordinates(); + } + + public CanonicalGameplayLoginResult.NonSecretEvidence evidence() { + return login.evidence(); + } + + public ObservedDirectTextTransport transport() { + return transport; + } + + public CanonicalPlayableTarget publicTarget() { + return publicTarget; + } + + public DirectTextIssuedConnectScope issued() { + return issued; + } + + public void requireCurrent( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + ObservedDirectTextTransport currentTransport, + Clock clock) { + if (!original().equals(original) + || !evidence().equals(verified.evidence()) + || !transport.equals(currentTransport) + || clock.instant().isBefore(issued.evaluatedAtInstant()) + || !issued.isLive(clock)) throw invalid(); + requireLiveResult(original, verified, clock); + } + + /** Checks private lifecycle without retaining, returning or serializing compact bytes. */ + public static void requireLiveResult( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult verified, + Clock clock) { + var evidence = Objects.requireNonNull(verified).evidence(); + long now = clock.instant().getEpochSecond(); + if (!original.requestId().equals(evidence.requestId()) + || !original.callerContextId().equals(evidence.callerContextId()) + || now < evidence.issuedAtEpochSecond() + || now < evidence.notBeforeEpochSecond() + || now >= evidence.expiresAtEpochSecond()) throw invalid(); + byte[] borrowed = verified.compactJwtBytes(); + Arrays.fill(borrowed, (byte) 0); + } + + public byte[] encode() { + try { + var output = new BoundedOutput(); + JSON.writeValue( + output, + new Envelope( + SCHEMA, + recordId, + new String(login.encode(), StandardCharsets.UTF_8), + transport, + publicTarget, + issued.connectScopeId(), + issued.evaluatedAt(), + issued.connectScopeExpiresAt())); + return output.toByteArray(); + } catch (Exception failure) { + throw invalid(); + } + } + + public static DirectTextAuthenticatedLobbyScope decode(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) throw invalid(); + try { + Envelope value = JSON.readValue(bytes, Envelope.class); + if (value == null + || !SCHEMA.equals(value.schema()) + || value.loginState() == null + || value.loginState().length() > InitialGameplayLoginContextState.MAX_BYTES + || value.evaluatedAt() == null + || value.evaluatedAt().length() > 40 + || value.expiresAt() == null + || value.expiresAt().length() > 40) throw invalid(); + var login = + InitialGameplayLoginContextState.decode( + value.loginState().getBytes(StandardCharsets.UTF_8)); + // Historical decoding uses the ORIGINAL evaluation instant only to reconstruct the existing + // immutable value. It never extends expiry or establishes permission to use an expired scope. + var issued = + DirectTextIssuedConnectScope.fromAccountResponse( + login.evidence().accountId().toString(), + targetFor(value.publicTarget()), + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId(value.connectScopeId()) + .setEvaluatedAt(value.evaluatedAt()) + .setConnectScopeExpiresAt(value.expiresAt()) + .build(), + Clock.fixed(Instant.parse(value.evaluatedAt()), ZoneOffset.UTC)); + var result = + new DirectTextAuthenticatedLobbyScope( + value.recordId(), login, value.transport(), value.publicTarget(), issued); + if (!Arrays.equals(bytes, result.encode())) throw invalid(); + return result; + } catch (RuntimeException failure) { + throw invalid(); + } + } + + public static DirectTextConnectScopeTarget targetFor(CanonicalPlayableTarget target) { + Objects.requireNonNull(target); + return new DirectTextConnectScopeTarget( + Long.toString(target.gameSessionTenantId()), + target.worldSlug(), + target.realmSlug(), + target.realmId().toString(), + target.playableStateNamespaceId().toString(), + target.playableStateScope(), + Long.toString(target.gameInstanceId()), + target.catalogRevision(), + target.pointerVersion()); + } + + public static void requireV4(UUID value) { + if (value == null || value.version() != 4 || value.variant() != 2) throw invalid(); + } + + private record Envelope( + String schema, + UUID recordId, + String loginState, + ObservedDirectTextTransport transport, + CanonicalPlayableTarget publicTarget, + String connectScopeId, + String evaluatedAt, + String expiresAt) {} + + private static final class BoundedOutput extends ByteArrayOutputStream { + @Override + public synchronized void write(int value) { + requireCapacity(1); + super.write(value); + } + + @Override + public synchronized void write(byte[] bytes, int offset, int length) { + Objects.checkFromIndexSize(offset, length, bytes.length); + requireCapacity(length); + super.write(bytes, offset, length); + } + + private void requireCapacity(int additional) { + if (additional > MAX_BYTES - count) throw invalid(); + } + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Exact authenticated lobby evidence required"); + } + + @Override + public String toString() { + return "DirectTextAuthenticatedLobbyScope[nonsecret,non-admitting]"; + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql b/services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql new file mode 100644 index 0000000000..6ebfa4131c --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql @@ -0,0 +1,167 @@ +-- Unregistered, non-admitting SQL companion. The minimal original LOGIN journal is unchanged. +-- No credential, compact token, cleanup horizon or release authority belongs to these relations. +CREATE TABLE game_session_direct_text_authenticated_lobby_scope ( + scope_record_id UUID PRIMARY KEY, + scope_sequence BIGINT GENERATED ALWAYS AS IDENTITY UNIQUE, + original_request_id UUID NOT NULL REFERENCES game_session_initial_gameplay_login_journal(request_id), + original_caller_context_id UUID NOT NULL, + original_attempt_fence BIGINT NOT NULL CHECK (original_attempt_fence > 0), + account_id UUID NOT NULL CHECK (account_id <> '00000000-0000-0000-0000-000000000000'::uuid), + proxy_connection_id UUID NOT NULL, + transport_session_id VARCHAR(32) NOT NULL CHECK (transport_session_id ~ '^[0-9]{1,32}$'), + verified_token_jti UUID NOT NULL, + verified_token_sha256 VARCHAR(64) NOT NULL CHECK (verified_token_sha256 ~ '^[0-9a-f]{64}$'), + verified_token_generation BIGINT NOT NULL CHECK (verified_token_generation = 1), + verified_issuance_fence BIGINT NOT NULL CHECK (verified_issuance_fence > 0), + scope_bytes BYTEA NOT NULL CHECK (octet_length(scope_bytes) BETWEEN 1 AND 131072), + UNIQUE (original_request_id, scope_record_id, scope_sequence), + CHECK (scope_record_id::TEXT ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND proxy_connection_id::TEXT ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + AND scope_record_id NOT IN (original_request_id, original_caller_context_id, proxy_connection_id, verified_token_jti)) +); + +CREATE TABLE game_session_direct_text_authenticated_lobby_current ( + original_request_id UUID PRIMARY KEY, + scope_record_id UUID NOT NULL UNIQUE, + scope_sequence BIGINT NOT NULL CHECK (scope_sequence > 0), + FOREIGN KEY (original_request_id, scope_record_id, scope_sequence) + REFERENCES game_session_direct_text_authenticated_lobby_scope + (original_request_id, scope_record_id, scope_sequence) +); + +CREATE TABLE game_session_direct_text_authenticated_lobby_join ( + scope_record_id UUID PRIMARY KEY REFERENCES game_session_direct_text_authenticated_lobby_scope(scope_record_id), + join_request_id UUID NOT NULL UNIQUE, + request_bytes BYTEA NOT NULL CHECK (octet_length(request_bytes) BETWEEN 1 AND 8192), + state VARCHAR(32) NOT NULL CHECK (state IN ('NEVER_DISPATCHED', 'DISPATCH_POSSIBLE', 'COMPLETED')), + reply_bytes BYTEA, + CHECK (join_request_id::TEXT ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + CHECK ((state = 'COMPLETED' AND reply_bytes IS NOT NULL + AND octet_length(reply_bytes) BETWEEN 1 AND 1024) + OR (state <> 'COMPLETED' AND reply_bytes IS NULL)) +); + +-- [jooq ignore start] +-- Every new claim takes the ACTUAL original row lock, including direct SQL writers. These +-- comparisons protect storage only: current authenticated Account/custody evidence is mandatory +-- at the manually composed Java owner and is not manufactured by this function. +CREATE FUNCTION require_gs_direct_text_lobby_original(s game_session_direct_text_authenticated_lobby_scope, allow_abandoned BOOLEAN) +RETURNS VOID AS $$ +DECLARE + original game_session_initial_gameplay_login_journal%ROWTYPE; +BEGIN + SELECT * INTO original FROM game_session_initial_gameplay_login_journal + WHERE request_id = s.original_request_id FOR UPDATE; + IF NOT FOUND OR (original.abandoned AND NOT allow_abandoned) + OR original.verified_token_jti IS NULL + OR ROW(original.caller_context_id, original.expected_attempt_fence, + original.verified_token_jti, original.verified_token_sha256, + original.verified_token_generation, original.verified_issuance_fence) + IS DISTINCT FROM ROW(s.original_caller_context_id, s.original_attempt_fence, + s.verified_token_jti, s.verified_token_sha256, + s.verified_token_generation, s.verified_issuance_fence) THEN + RAISE EXCEPTION 'Direct-text lobby original is unavailable' USING ERRCODE = '23514'; + END IF; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_gs_direct_text_lobby_scope() RETURNS TRIGGER AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Direct-text lobby scope retention is held' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF NEW IS DISTINCT FROM OLD THEN + RAISE EXCEPTION 'Direct-text lobby scope is immutable' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + PERFORM require_gs_direct_text_lobby_original(NEW, FALSE); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER gs_direct_text_lobby_scope_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_direct_text_authenticated_lobby_scope + FOR EACH ROW EXECUTE FUNCTION guard_gs_direct_text_lobby_scope(); +CREATE TRIGGER gs_direct_text_lobby_scope_retention + BEFORE TRUNCATE ON game_session_direct_text_authenticated_lobby_scope + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_direct_text_lobby_scope(); + +CREATE FUNCTION guard_gs_direct_text_lobby_current() RETURNS TRIGGER AS $$ +DECLARE + s game_session_direct_text_authenticated_lobby_scope%ROWTYPE; +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Direct-text lobby selection retention is held' USING ERRCODE = '23514'; + END IF; + SELECT * INTO s FROM game_session_direct_text_authenticated_lobby_scope + WHERE scope_record_id = NEW.scope_record_id; + IF NOT FOUND OR s.original_request_id <> NEW.original_request_id + OR s.scope_sequence <> NEW.scope_sequence THEN + RAISE EXCEPTION 'Direct-text lobby selection differs from retained scope' USING ERRCODE = '23514'; + END IF; + PERFORM require_gs_direct_text_lobby_original(s, FALSE); + IF TG_OP = 'UPDATE' AND (NEW.original_request_id <> OLD.original_request_id + OR NEW.scope_sequence <= OLD.scope_sequence) THEN + RAISE EXCEPTION 'Direct-text lobby selection cannot regress or rebind' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER gs_direct_text_lobby_current_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_direct_text_authenticated_lobby_current + FOR EACH ROW EXECUTE FUNCTION guard_gs_direct_text_lobby_current(); +CREATE TRIGGER gs_direct_text_lobby_current_retention + BEFORE TRUNCATE ON game_session_direct_text_authenticated_lobby_current + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_direct_text_lobby_current(); + +CREATE FUNCTION guard_gs_direct_text_lobby_join() RETURNS TRIGGER AS $$ +DECLARE + s game_session_direct_text_authenticated_lobby_scope%ROWTYPE; +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Direct-text lobby JOIN retention is held' USING ERRCODE = '23514'; + END IF; + SELECT * INTO s FROM game_session_direct_text_authenticated_lobby_scope + WHERE scope_record_id = NEW.scope_record_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Direct-text lobby JOIN scope is missing' USING ERRCODE = '23514'; + END IF; + IF NEW.join_request_id IN (s.scope_record_id, s.original_request_id, + s.original_caller_context_id, s.proxy_connection_id, s.verified_token_jti) THEN + RAISE EXCEPTION 'Direct-text lobby JOIN requires its own identity' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'UPDATE' THEN + IF ROW(NEW.scope_record_id, NEW.join_request_id, NEW.request_bytes) + IS DISTINCT FROM ROW(OLD.scope_record_id, OLD.join_request_id, OLD.request_bytes) THEN + RAISE EXCEPTION 'Direct-text lobby JOIN identity is immutable' USING ERRCODE = '23514'; + END IF; + -- A delayed exact positive result may be retained even after abandonment or replacement. + -- It never moves the current selection or applies membership/authentication to a transport. + IF OLD.state = 'DISPATCH_POSSIBLE' AND NEW.state = 'COMPLETED' + AND NEW.reply_bytes IS NOT NULL THEN + PERFORM require_gs_direct_text_lobby_original(s, TRUE); + RETURN NEW; + END IF; + IF NOT (OLD.state = 'NEVER_DISPATCHED' AND NEW.state = 'DISPATCH_POSSIBLE' + AND NEW.reply_bytes IS NULL) THEN + RAISE EXCEPTION 'Direct-text lobby JOIN cannot reset or overwrite an original' USING ERRCODE = '23514'; + END IF; + ELSIF NEW.state <> 'NEVER_DISPATCHED' OR NEW.reply_bytes IS NOT NULL THEN + RAISE EXCEPTION 'Direct-text lobby JOIN must begin never-dispatched' USING ERRCODE = '23514'; + END IF; + PERFORM require_gs_direct_text_lobby_original(s, FALSE); + IF NOT EXISTS (SELECT 1 FROM game_session_direct_text_authenticated_lobby_current + WHERE original_request_id = s.original_request_id AND scope_record_id = s.scope_record_id) THEN + RAISE EXCEPTION 'Direct-text lobby JOIN selection is no longer current' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; +CREATE TRIGGER gs_direct_text_lobby_join_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_direct_text_authenticated_lobby_join + FOR EACH ROW EXECUTE FUNCTION guard_gs_direct_text_lobby_join(); +CREATE TRIGGER gs_direct_text_lobby_join_retention + BEFORE TRUNCATE ON game_session_direct_text_authenticated_lobby_join + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_direct_text_lobby_join(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java new file mode 100644 index 0000000000..2651e44807 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java @@ -0,0 +1,1030 @@ +package integration.net.firedevops.firemud.gamesession.service.directtext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.interfaces.RSAPublicKey; +import java.sql.DriverManager; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.GameplayLoginSourceContext; +import net.firedevops.firemud.account.v1.GameplayLoginTransportClass; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; +import net.firedevops.firemud.common.security.AccountPublicJwksCache; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.RealmView; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog.WorldView; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.DirectTextAuthenticatedLobbyRepository; +import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyCustody; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin.State; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; + +/** + * Native PostgreSQL migration/owner proof with controlled RSA Account responses, guarded catalog + * reads and custody fixtures. No live ingress, protected production DB delivery, PKI, hidden + * rebind, registration, cleanup, enrollment, activation, actor selection or gameplay admission is + * proved. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class DirectTextAuthenticatedLobbyIntegrationTest { + private static final Instant NOW = Instant.parse("2026-11-01T12:00:00Z"); + private static final Clock VERIFY_CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final String PARENT = "game_session_initial_gameplay_login_journal"; + private static final String SCOPE = DirectTextAuthenticatedLobbyRepository.SCOPE; + private static final String CURRENT = DirectTextAuthenticatedLobbyRepository.CURRENT; + private static final String JOIN = DirectTextAuthenticatedLobbyRepository.JOIN; + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static KeyPair keys; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DriverManagerDataSource source; + private DSLContext dsl; + private DataSourceTransactionManager manager; + private TransactionTemplate tx; + private InitialGameplayLoginCoordinationJournalRepository journal; + private DirectTextAuthenticatedLobbyRepository repository; + private DirectTextAuthenticatedLobbyOwner owner; + private DirectTextWorldSelectionService selection; + private AccountClient account; + private CanonicalGameplayLoginResult verified; + private InitialGameplayLoginAttemptCoordinates original; + private ControlledCustody custody; + private final MutableClock clock = new MutableClock(); + private CanonicalPlayableTarget target; + private String parentBeforeMigration; + + @BeforeAll + static void signingAndPostgres() throws Exception { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + var generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + keys = generator.generateKeyPair(); + } + + @BeforeEach + void migratePopulatedOriginalThenComposeInactiveOwner() throws Exception { + schema = "gs_direct_text_lobby_" + UUID.randomUUID().toString().replace("-", ""); + source = new DriverManagerDataSource(); + source.setDriverClassName("org.postgresql.Driver"); + source.setUrl(postgres.getJdbcUrl()); + source.setUsername(postgres.getUsername()); + source.setPassword(postgres.getPassword()); + source.setSchema(schema); + migration("1051").migrate(); + dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + manager = new DataSourceTransactionManager(source); + tx = new TransactionTemplate(manager); + tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + tx.setTimeout(15); + journal = new InitialGameplayLoginCoordinationJournalRepository(dsl); + original = new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 7); + verified = verified(original, ACCOUNT, UUID.randomUUID(), "5"); + tx.executeWithoutResult( + status -> { + journal.reserve(original); + journal.recordVerifiedResult(original, verified); + }); + parentBeforeMigration = parentJson(); + migration(null).migrate(); + repository = new DirectTextAuthenticatedLobbyRepository(dsl); + account = mock(AccountClient.class); + target = target(); + var routes = mock(CanonicalPlayerRouteReadService.class); + when(routes.readVisiblePublicProductionTargets()).thenReturn(List.of(target)); + when(routes.readCurrentTarget(target)).thenReturn(target); + var world = + new WorldView( + target.worldSlug(), + target.worldDisplayName(), + List.of( + new RealmView( + target.realmSlug(), + target.realmDisplayName(), + target.gameSessionTenantId(), + target.gameInstanceId(), + target.pointerVersion(), + true, + true, + false, + target.playableStateScope(), + target.characterCreationPolicy(), + target.catalogRevision(), + target.realmId(), + target.playableStateNamespaceId()))); + selection = + new DirectTextWorldSelectionService( + GameplayWorldCatalog.forWorldSupplier(() -> List.of(world)), routes, clock); + custody = + new ControlledCustody( + original, verified, new ObservedDirectTextTransport("00042", UUID.randomUUID())); + when(account.issueDirectTextConnectScope(any(), any())) + .thenAnswer( + call -> + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("opaque-" + UUID.randomUUID()) + .setEvaluatedAt(NOW.minusSeconds(1).toString()) + .setConnectScopeExpiresAt(NOW.plusSeconds(60).toString()) + .build()); + owner = owner(repository, manager); + } + + private Flyway migration(String targetVersion) { + var config = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .locations( + "filesystem:" + + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize()); + if (targetVersion != null) config.target(targetVersion); + return config.load(); + } + + @AfterEach + void closeOnlyOwnedResultAndSchema() throws Exception { + if (verified != null) verified.close(); + if (schema != null) { + try (var connection = + DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); + } + } + } + + @Test + void forwardMigrationPreservesPopulatedMinimalParentAndFullExactNonsecretScope() { + assertThat(parentJson()).isEqualTo(parentBeforeMigration); + var scope = realms(); + var stored = repository.readCommittedScope(scope); + assertThat(stored.encode()).containsExactly(scope.encode()); + assertThat(stored.publicTarget()).isEqualTo(target); + assertThat(stored.evidence()).isEqualTo(verified.evidence()); + assertThat(stored.transport()).isEqualTo(custody.transport); + assertThat(stored.issued().evaluatedAt()).isEqualTo(NOW.minusSeconds(1).toString()); + assertThat(stored.issued().connectScopeExpiresAt()).isEqualTo(NOW.plusSeconds(60).toString()); + assertThat(new String(stored.encode(), StandardCharsets.UTF_8)) + .doesNotContain("fixture-transient-secret", "eyJhbGci", "authToken", "password"); + assertThat(parentJson()).isEqualTo(parentBeforeMigration); + reject("DELETE FROM " + PARENT + " WHERE request_id = ?", original.requestId()); + } + + @Test + void actualOwnerReadsCommittedExactRequestBeforeAccountAndRetainsPositiveReply() { + var scope = realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var row = + dsl.fetchSingle( + "SELECT * FROM " + JOIN + " WHERE scope_record_id = ?", scope.recordId()); + assertThat(row.get("state", String.class)).isEqualTo("DISPATCH_POSSIBLE"); + var request = + DirectTextAuthenticatedLobbyJoin.decodeRequest( + row.get("request_bytes", byte[].class)); + assertThat(request.getPlayerContext()) + .isEqualTo( + call.getArgument( + 0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); + assertThat(request.getConnectScopeId()).isEqualTo(call.getArgument(1, String.class)); + assertThat(request.getRequestId()).isEqualTo(call.getArgument(2, String.class)); + assertThat(call.getArgument(3, Instant.class)) + .isEqualTo(scope.issued().connectScopeExpiresAtInstant()); + return positive(); + }); + var completed = owner.join(original, verified, custody); + assertThat(completed.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING); + assertThat(completed.currentReply()).contains(positive()); + var continuation = owner(repository, manager).join(original, verified, custody); + assertThat(continuation.requestId()).isEqualTo(completed.requestId()); + verify(account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + } + + @Test + void independentConnectionsAllocateOneFrozenWinnerAndOnlyOneDispatchClaim() throws Exception { + realms(); + var gate = new CountDownLatch(1); + var executor = Executors.newFixedThreadPool(2); + try { + var one = + executor.submit( + () -> { + await(gate); + return freeze(); + }); + var two = + executor.submit( + () -> { + await(gate); + return freeze(); + }); + gate.countDown(); + var first = one.get(10, TimeUnit.SECONDS); + var second = two.get(10, TimeUnit.SECONDS); + assertThat(second.request()).isEqualTo(first.request()); + assertThat(first.requestId()) + .isNotIn( + original.requestId(), + original.callerContextId(), + first.scope().recordId(), + custody.transport.proxyConnectionId(), + verified.evidence().tokenJti()); + var a = executor.submit(() -> claim(first)); + var b = executor.submit(() -> claim(second)); + assertThat(List.of(a.get(10, TimeUnit.SECONDS), b.get(10, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + assertThat(repository.readCommittedJoin(first).state()).isEqualTo(State.DISPATCH_POSSIBLE); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isEqualTo(1); + } finally { + gate.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void actualParentAbandonmentAndDispatchClaimSerializeInBothOrders(boolean abandonmentFirst) + throws Exception { + realms(); + var frozen = freeze(); + var locked = new CountDownLatch(1); + var release = new CountDownLatch(1); + var followerStarted = new CountDownLatch(1); + var followerPid = new AtomicInteger(); + var executor = Executors.newFixedThreadPool(2); + try { + var winner = + executor.submit( + () -> + tx.execute( + status -> { + repository.verifyOriginal(original, verified); + if (abandonmentFirst) journal.abandon(original); + else + assertThat( + repository.claimDispatch( + frozen, verified, custody.transport, clock)) + .isTrue(); + locked.countDown(); + await(release); + return true; + })); + assertThat(locked.await(5, TimeUnit.SECONDS)).isTrue(); + var follower = + executor.submit( + () -> { + try { + return tx.execute( + status -> { + followerPid.set( + dsl.fetchSingle("SELECT pg_backend_pid() AS pid") + .get("pid", Integer.class)); + followerStarted.countDown(); + if (abandonmentFirst) + return repository.claimDispatch( + frozen, verified, custody.transport, clock); + journal.abandon(original); + return true; + }); + } catch (IllegalStateException denied) { + return false; + } + }); + assertThat(followerStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitActualLockWait(followerPid.get()); + assertThat(follower.isDone()).isFalse(); + release.countDown(); + assertThat(winner.get(10, TimeUnit.SECONDS)).isTrue(); + assertThat(follower.get(10, TimeUnit.SECONDS)).isEqualTo(!abandonmentFirst); + var retained = repository.readCommittedJoin(frozen); + assertThat(retained.state()) + .isEqualTo(abandonmentFirst ? State.NEVER_DISPATCHED : State.DISPATCH_POSSIBLE); + assertThat(journal.readCommitted(original).orElseThrow().abandoned()).isTrue(); + assertThatThrownBy(() -> claim(frozen)).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(this::realms).isInstanceOf(IllegalStateException.class); + verify(account, times(1)).issueDirectTextConnectScope(any(), any()); + if (!abandonmentFirst) { + tx.executeWithoutResult( + status -> repository.recordPositiveReply(retained, verified, positive())); + assertThat(repository.readCommittedJoin(retained).reply()).contains(positive()); + } + } finally { + release.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void freshExplicitRealmsPreservesOlderUnknownAndForbidsStaleDispatch() { + var older = realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())).thenReturn(unknown()); + var first = owner.join(original, verified, custody); + var oldOriginal = + dsl.fetchSingle( + "SELECT request_bytes FROM " + JOIN + " WHERE scope_record_id = ?", + older.recordId()) + .get("request_bytes", byte[].class); + var newer = realms(); + assertThat(newer.recordId()).isNotEqualTo(older.recordId()); + assertThat(repository.readCommittedScope(older).encode()).containsExactly(older.encode()); + assertThat( + dsl.fetchSingle( + "SELECT request_bytes FROM " + JOIN + " WHERE scope_record_id = ?", + older.recordId()) + .get("request_bytes", byte[].class)) + .containsExactly(oldOriginal); + var oldJoin = + new DirectTextAuthenticatedLobbyJoin( + older, + DirectTextAuthenticatedLobbyJoin.decodeRequest(oldOriginal), + State.DISPATCH_POSSIBLE, + Optional.empty()); + assertThatThrownBy(() -> claim(oldJoin)).isInstanceOf(IllegalStateException.class); + var second = owner.join(original, verified, custody); + assertThat(second.requestId()).isNotEqualTo(first.requestId()); + assertThat(dsl.fetchCount(DSL.table(SCOPE))).isEqualTo(2); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isEqualTo(2); + assertThat(parentJson()).isEqualTo(parentBeforeMigration); + } + + @Test + void lostReplyLeavesOriginalUnresolvedAcrossOwnerReplacementAndExpiryOrResetDoesNotEraseIt() { + realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenThrow(new IllegalStateException("Controlled lost reply")); + assertThatThrownBy(() -> owner.join(original, verified, custody)) + .isInstanceOf(IllegalStateException.class); + var continued = owner(repository, manager).join(original, verified, custody); + assertThat(continued.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.RETAINED_UNRESOLVED); + var before = joinJson(); + clock.now = NOW.plusSeconds(60); + assertThatThrownBy(() -> owner.join(original, verified, custody)) + .isInstanceOf(IllegalArgumentException.class); + clock.now = NOW; + custody.reset(); + assertThatThrownBy(() -> owner.join(original, verified, custody)) + .isInstanceOf(IllegalStateException.class); + assertThat(joinJson()).isEqualTo(before); + verify(account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void lostCommittedFreezeOrDispatchResponseRetainsSameOriginalWithoutAutomaticReissue( + boolean loseFreeze) { + realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())).thenReturn(positive()); + var loseCommit = new AtomicBoolean(); + var instrumented = spy(repository); + if (loseFreeze) { + doAnswer( + call -> { + Object value = call.callRealMethod(); + loseCommit.set(true); + return value; + }) + .when(instrumented) + .freezeCurrentJoin(any(), any(), any(), any()); + } else { + doAnswer( + call -> { + Object value = call.callRealMethod(); + loseCommit.set(true); + return value; + }) + .when(instrumented) + .claimDispatch(any(), any(), any(), any()); + } + var losingManager = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return manager.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + manager.commit(status); + if (loseCommit.getAndSet(false)) + throw new IllegalStateException("Controlled committed owner reply loss"); + } + + @Override + public void rollback(TransactionStatus status) { + manager.rollback(status); + } + }; + assertThatThrownBy(() -> owner(instrumented, losingManager).join(original, verified, custody)) + .isInstanceOf(IllegalStateException.class); + UUID retainedId = + dsl.fetchSingle("SELECT join_request_id FROM " + JOIN).get("join_request_id", UUID.class); + verify(account, times(0)).joinPublicProductionMembership(any(), any(), any(), any()); + var continued = owner(repository, manager).join(original, verified, custody); + assertThat(continued.requestId()).isEqualTo(retainedId); + assertThat(continued.status()) + .isEqualTo( + loseFreeze + ? DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING + : DirectTextAuthenticatedLobbyOwner.Status.RETAINED_UNRESOLVED); + verify(account, times(loseFreeze ? 1 : 0)) + .joinPublicProductionMembership(any(), any(), any(), any()); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isEqualTo(1); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void lostResultPersistenceOutcomeNeverRearmsOrOverwrites(boolean committedBeforeLoss) { + realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())).thenReturn(positive()); + var loseAfterCommit = new AtomicBoolean(); + var instrumented = spy(repository); + doAnswer( + call -> { + call.callRealMethod(); + if (committedBeforeLoss) loseAfterCommit.set(true); + else throw new IllegalStateException("Controlled result transaction rollback"); + return null; + }) + .when(instrumented) + .recordPositiveReply(any(), any(), any()); + var losingManager = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return manager.getTransaction(definition); + } + + @Override + public void commit(TransactionStatus status) { + manager.commit(status); + if (loseAfterCommit.getAndSet(false)) + throw new IllegalStateException("Controlled committed reply loss"); + } + + @Override + public void rollback(TransactionStatus status) { + manager.rollback(status); + } + }; + assertThatThrownBy(() -> owner(instrumented, losingManager).join(original, verified, custody)) + .isInstanceOf(IllegalStateException.class); + var continued = owner(repository, manager).join(original, verified, custody); + assertThat(continued.status()) + .isEqualTo( + committedBeforeLoss + ? DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING + : DirectTextAuthenticatedLobbyOwner.Status.RETAINED_UNRESOLVED); + verify(account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isEqualTo(1); + } + + @Test + void positiveInflightResultAfterAbandonmentAndTransportResetIsHistoricalOnly() { + var scope = realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenAnswer( + call -> { + tx.executeWithoutResult(status -> journal.abandon(original)); + custody.resetAfterCurrentCallback(); + return positive(); + }); + var observed = owner.join(original, verified, custody); + assertThat(observed.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.HISTORICAL_ONLY); + assertThat(observed.currentReply()).isEmpty(); + byte[] reply = + dsl.fetchSingle( + "SELECT reply_bytes FROM " + JOIN + " WHERE scope_record_id = ?", scope.recordId()) + .get("reply_bytes", byte[].class); + assertThat(DirectTextAuthenticatedLobbyJoin.decodeReply(scope, reply)).isEqualTo(positive()); + } + + @Test + void delayedPositiveResultDoesNotMoveANewerCurrentScope() { + var old = realms(); + when(account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenAnswer( + call -> { + var newer = realms(); + assertThat(newer.recordId()).isNotEqualTo(old.recordId()); + return positive(); + }); + var observed = owner.join(original, verified, custody); + assertThat(observed.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.HISTORICAL_ONLY); + assertThat(observed.currentReply()).isEmpty(); + var currentId = + dsl.fetchSingle("SELECT scope_record_id FROM " + CURRENT) + .get("scope_record_id", UUID.class); + assertThat(currentId).isNotEqualTo(old.recordId()); + assertThat( + dsl.fetchSingle( + "SELECT state FROM " + JOIN + " WHERE scope_record_id = ?", old.recordId()) + .get("state", String.class)) + .isEqualTo("COMPLETED"); + } + + @Test + void currentVerifiedIdentityAndCompleteWitnessAreRequiredNotMerelyMatchingSqlOrFlags() + throws Exception { + realms(); + try (var differentAccount = + verified(original, UUID.randomUUID(), verified.evidence().tokenJti(), "5"); + var differentWitness = verified(original, ACCOUNT, UUID.randomUUID(), "6")) { + assertThatThrownBy( + () -> + tx.execute( + status -> + repository.current(original, differentAccount, custody.transport, clock))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + tx.execute( + status -> + repository.current(original, differentWitness, custody.transport, clock))) + .isInstanceOf(IllegalStateException.class); + } + var wrongFence = + new InitialGameplayLoginAttemptCoordinates( + original.requestId(), original.callerContextId(), 8); + assertThatThrownBy( + () -> + tx.executeWithoutResult(status -> repository.verifyOriginal(wrongFence, verified))) + .isInstanceOf(IllegalStateException.class); + var missing = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 1); + try (var result = verified(missing, ACCOUNT, UUID.randomUUID(), "1")) { + assertThatThrownBy( + () -> tx.executeWithoutResult(status -> repository.verifyOriginal(missing, result))) + .isInstanceOf(IllegalStateException.class); + tx.executeWithoutResult(status -> journal.reserve(missing)); + assertThatThrownBy( + () -> tx.executeWithoutResult(status -> repository.verifyOriginal(missing, result))) + .isInstanceOf(IllegalStateException.class); + } + verified.close(); + assertThatThrownBy(() -> owner.join(original, verified, custody)) + .isInstanceOf(IllegalStateException.class); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isZero(); + } + + @Test + void directSqlProtectsEveryCompanionAndRefusesInvalidIdentityTransitionsAndPointerRegression() { + var oldScope = realms(); + var frozen = freeze(); + reject( + "UPDATE " + JOIN + " SET state = 'COMPLETED', reply_bytes = ?", positive().toByteArray()); + reject("UPDATE " + JOIN + " SET join_request_id = ?", original.requestId()); + reject("UPDATE " + JOIN + " SET request_bytes = ?", new byte[] {1}); + assertThat(claim(frozen)).isTrue(); + reject("UPDATE " + JOIN + " SET state = 'NEVER_DISPATCHED'"); + tx.executeWithoutResult(status -> repository.recordPositiveReply(frozen, verified, positive())); + reject( + "UPDATE " + JOIN + " SET reply_bytes = ?", + positive().toBuilder().setReplayed(true).build().toByteArray()); + reject("UPDATE " + SCOPE + " SET account_id = ?", UUID.randomUUID()); + reject("UPDATE " + SCOPE + " SET scope_bytes = ?", new byte[] {1}); + realms(); + reject( + "UPDATE " + + CURRENT + + " SET scope_record_id = ?, scope_sequence = (SELECT scope_sequence FROM " + + SCOPE + + " WHERE scope_record_id = ?)", + oldScope.recordId(), + oldScope.recordId()); + for (String table : List.of(JOIN, CURRENT, SCOPE)) { + assertThatThrownBy(() -> dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("retention is held") + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> dsl.execute("TRUNCATE " + table + " CASCADE")) + .hasMessageContaining("retention is held") + .isInstanceOf(DataAccessException.class); + } + assertThat(dsl.fetchCount(DSL.table(SCOPE))).isEqualTo(2); + assertThat(dsl.fetchCount(DSL.table(JOIN))).isEqualTo(1); + } + + @Test + void nonDurableUnjoinedOrAmbientTransactionsCannotSupplyReadbackOrDispatchEvidence() { + realms(); + assertThatThrownBy(this::freezeWithoutTransaction).isInstanceOf(IllegalStateException.class); + var frozen = freeze(); + assertThatThrownBy(() -> tx.execute(status -> repository.readCommittedJoin(frozen))) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy( + () -> + tx.execute( + status -> { + dsl.execute("SET LOCAL synchronous_commit = 'off'"); + return repository.claimDispatch(frozen, verified, custody.transport, clock); + })) + .isInstanceOf(IllegalStateException.class); + var unjoined = + new DirectTextAuthenticatedLobbyRepository(DSL.using(source, SQLDialect.POSTGRES)); + assertThatThrownBy( + () -> + tx.execute( + status -> unjoined.claimDispatch(frozen, verified, custody.transport, clock))) + .isInstanceOf(IllegalStateException.class); + assertThat(repository.readCommittedJoin(frozen).state()).isEqualTo(State.NEVER_DISPATCHED); + } + + private DirectTextAuthenticatedLobbyOwner owner( + DirectTextAuthenticatedLobbyRepository repo, PlatformTransactionManager transactions) { + return new DirectTextAuthenticatedLobbyOwner(repo, selection, account, transactions, clock); + } + + private DirectTextAuthenticatedLobbyScope realms() { + return owner.realms(original, verified, custody, selection.browse().orElseThrow(), "1"); + } + + private DirectTextAuthenticatedLobbyJoin freeze() { + return tx.execute(status -> freezeWithoutTransaction()); + } + + private DirectTextAuthenticatedLobbyJoin freezeWithoutTransaction() { + return repository.freezeCurrentJoin(original, verified, custody.transport, clock); + } + + private boolean claim(DirectTextAuthenticatedLobbyJoin frozen) { + return Boolean.TRUE.equals( + tx.execute(status -> repository.claimDispatch(frozen, verified, custody.transport, clock))); + } + + private String parentJson() { + return dsl.fetchSingle( + "SELECT to_jsonb(p)::text AS value FROM " + PARENT + " p WHERE request_id = ?", + original.requestId()) + .get("value", String.class); + } + + private String joinJson() { + return dsl.fetchSingle("SELECT to_jsonb(j)::text AS value FROM " + JOIN + " j") + .get("value", String.class); + } + + private void reject(String sql, Object... values) { + assertThatThrownBy(() -> dsl.execute(sql, values)) + .isInstanceOfSatisfying( + DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + } + + private void awaitActualLockWait(int pid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + if (Boolean.TRUE.equals( + dsl.fetchSingle("SELECT cardinality(pg_blocking_pids(?)) > 0 AS waiting", pid) + .get("waiting", Boolean.class))) return; + Thread.onSpinWait(); + } + throw new IllegalStateException( + "Independent original owner did not reach a PostgreSQL lock wait"); + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Bounded lobby fixture timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Lobby fixture interrupted", failure); + } + } + + private static JoinPublicProductionMembershipResponse positive() { + return JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("JOINED") + .setAccountId(ACCOUNT.toString()) + .setTenantId("101") + .setMembershipId("90") + .setMembershipVersion(3) + .setMembershipAuthorityGeneration(1) + .build(); + } + + private static JoinPublicProductionMembershipResponse unknown() { + return JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode("AUTH_UNAVAILABLE") + .setError(ErrorDetail.newBuilder().setCode("AUTH_UNAVAILABLE")) + .build(); + } + + private static CanonicalPlayableTarget target() { + return new CanonicalPlayableTarget( + "gameplay", + "studio", + UUID.randomUUID(), + "forest", + "Forest", + UUID.randomUUID(), + "public", + "Live", + 101, + 202, + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + UUID.randomUUID(), + 303, + 1, + 7, + "d".repeat(64), + 82, + "original-open", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "c".repeat(64), + 27, + "sha256:" + "f".repeat(64), + Outcome.COMMITTED, + false, + NOW.minusSeconds(1), + "ALLOW_NEW"); + } + + /** Controlled protected-call exclusion only; no claim of a real TCP/private-result producer. */ + private static final class ControlledCustody implements DirectTextAuthenticatedLobbyCustody { + private final InitialGameplayLoginAttemptCoordinates original; + private final CanonicalGameplayLoginResult result; + private final ObservedDirectTextTransport transport; + private boolean live = true; + private boolean resetAfterCallback; + + ControlledCustody( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult result, + ObservedDirectTextTransport transport) { + this.original = original; + this.result = result; + this.transport = transport; + } + + synchronized void reset() { + live = false; + } + + synchronized void resetAfterCurrentCallback() { + resetAfterCallback = true; + } + + @Override + public synchronized T withCurrent( + InitialGameplayLoginAttemptCoordinates coordinates, + CanonicalGameplayLoginResult borrowed, + Function action) { + if (!live || !original.equals(coordinates) || borrowed != result) + throw new IllegalStateException("Controlled custody unavailable"); + try { + return action.apply(transport); + } finally { + if (resetAfterCallback) live = false; + } + } + } + + private static final class MutableClock extends Clock { + private Instant now = NOW; + + @Override + public ZoneId getZone() { + return ZoneOffset.UTC; + } + + @Override + public Clock withZone(ZoneId zone) { + return Clock.fixed(now, zone); + } + + @Override + public Instant instant() { + return now; + } + } + + /** Real signature/aggregate validation with locally controlled keys, not real Account custody. */ + private static CanonicalGameplayLoginResult verified( + InitialGameplayLoginAttemptCoordinates original, UUID accountId, UUID jti, String fence) + throws Exception { + long now = NOW.getEpochSecond(); + var claims = + new LinkedHashMap( + Map.ofEntries( + Map.entry("iss", GameSessionAccountDelegationProfile.ISSUER), + Map.entry("aud", GameSessionAccountDelegationProfile.AUDIENCE), + Map.entry("sub", accountId.toString()), + Map.entry("accountId", accountId.toString()), + Map.entry("jti", jti.toString()), + Map.entry("iat", now - 2), + Map.entry("nbf", now - 2), + Map.entry("exp", now + 120), + Map.entry("tokenGeneration", "1"), + Map.entry("issuanceFence", fence), + Map.entry("membershipVersion", Map.of()), + Map.entry( + "authorityTuple", GameSessionAccountDelegationProfile.authorityTuple(1, 1)))); + var encoder = Base64.getUrlEncoder().withoutPadding(); + String input = + encoder.encodeToString( + "{\"alg\":\"RS256\",\"kid\":\"test-key\",\"typ\":\"JWT\"}" + .getBytes(StandardCharsets.UTF_8)) + + "." + + encoder.encodeToString(JSON.writeValueAsBytes(claims)); + var signer = Signature.getInstance("SHA256withRSA"); + signer.initSign(keys.getPrivate()); + signer.update(input.getBytes(StandardCharsets.US_ASCII)); + String token = input + "." + encoder.encodeToString(signer.sign()); + var request = + AuthenticateRequest.newBuilder() + .setRequestId(original.requestId().toString()) + .setEmail("player@example.test") + .setPassword("fixture-transient-secret") + .setSourceContext( + GameplayLoginSourceContext.newBuilder() + .setCallerContextId(original.callerContextId().toString()) + .setCanonicalClientAddress("203.0.113.10") + .setTransportClass( + GameplayLoginTransportClass + .GAMEPLAY_LOGIN_TRANSPORT_CLASS_TRUSTED_TCP_PROXY)) + .build(); + var response = + AuthenticateResponse.newBuilder() + .setAuthToken(token) + .setAccountId(accountId.toString()) + .setRequestId(original.requestId().toString()) + .setCallerContextId(original.callerContextId().toString()) + .setTokenJti(jti.toString()) + .setTokenSha256( + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(token.getBytes(StandardCharsets.US_ASCII)))) + .setTokenProfile(GameSessionAccountDelegationProfile.PROFILE) + .setIssuedAtEpochSeconds(now - 2) + .setNotBeforeEpochSeconds(now - 2) + .setExpiresAtEpochSeconds(now + 120) + .setTokenGeneration("1") + .setIssuanceFence(fence) + .setAuthorityTupleCanonicalJson(canonical(claims.get("authorityTuple"))) + .setOutboxCheckpointsCanonicalJson( + canonical( + List.of( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:account/" + accountId, + "outboxSequence", + "0"), + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:issuer/firemud-account-service", + "outboxSequence", + "0")))) + .setOutboxSourceEventEvidenceCanonicalJson(canonical(List.of())) + .build(); + var pin = + new AccountPublicJwksCache.SourceIdentity( + "test", + "cluster-a", + "11111111-1111-4111-8111-111111111111", + "test", + "22222222-2222-4222-8222-222222222222", + "33333333-3333-4333-8333-333333333333", + "binding-7", + "https://kubernetes.example:6443", + "a".repeat(64)); + var key = (RSAPublicKey) keys.getPublic(); + String jwks = + JSON.writeValueAsString( + Map.of( + "keys", + List.of( + Map.of( + "kty", + "RSA", + "use", + "sig", + "alg", + "RS256", + "kid", + "test-key", + "n", + unsigned(key.getModulus().toByteArray()), + "e", + unsigned(key.getPublicExponent().toByteArray()))))); + var cache = + new AccountPublicJwksCache( + () -> + new AccountPublicJwksCache.PublicJwksSnapshot( + pin, jwks.getBytes(StandardCharsets.UTF_8)), + pin, + VERIFY_CLOCK, + Duration.ofSeconds(30)); + return CanonicalGameplayLoginResult.fromAuthenticatedResponse( + response, request, new AccountAsymmetricJwtVerifier(cache, VERIFY_CLOCK), VERIFY_CLOCK); + } + + private static ByteString canonical(Object value) throws Exception { + return ByteString.copyFrom( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } + + private static String unsigned(byte[] bytes) { + return Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + bytes.length > 1 && bytes[0] == 0 ? Arrays.copyOfRange(bytes, 1, bytes.length) : bytes); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java new file mode 100644 index 0000000000..b9818dc627 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java @@ -0,0 +1,625 @@ +package unit.net.firedevops.firemud.gamesession.service.directtext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; +import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.client.AccountClient; +import net.firedevops.firemud.gamesession.client.DirectTextIssuedConnectScope; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.ObservedDirectTextTransport; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest.OriginKind; +import net.firedevops.firemud.gamesession.dto.CanonicalPlayableTarget; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.repository.DirectTextAuthenticatedLobbyRepository; +import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextState; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyCustody; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyJoin.State; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.SimpleTransactionStatus; +import tools.jackson.databind.json.JsonMapper; + +/** + * Controlled Account-result/custody/repository fixtures, NOT authenticated ingress or SQL proof. + */ +class DirectTextAuthenticatedLobbyTest { + private static final Instant NOW = Instant.parse("2026-11-01T12:00:00Z"); + private static final Clock CLOCK = Clock.fixed(NOW, ZoneOffset.UTC); + private static final UUID ACCOUNT = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final JsonMapper JSON = JsonMapper.builder().build(); + + @Test + void codecPreservesWholeIdentityTargetAndOriginalAccountTimesWithoutPrivateBytes() { + var f = new Fixture(); + byte[] bytes = f.scope.encode(); + var restored = DirectTextAuthenticatedLobbyScope.decode(bytes); + assertThat(restored.encode()).containsExactly(bytes); + assertThat(restored.evidence()).isEqualTo(f.result.evidence()); + assertThat(restored.publicTarget()).isEqualTo(f.scope.publicTarget()); + assertThat(restored.transport()).isEqualTo(f.transport); + assertThat(restored.issued().evaluatedAt()).isEqualTo(NOW.minusSeconds(1).toString()); + assertThat(restored.issued().connectScopeExpiresAt()).isEqualTo(NOW.plusSeconds(60).toString()); + assertThat(new String(bytes, StandardCharsets.UTF_8)) + .doesNotContain("fixture-private-token", "password", "authToken", "compactJwt"); + // Historical decode after expiry is still possible, but use cannot renew its deadline. + assertThatThrownBy( + () -> + restored.requireCurrent( + f.original, + f.result, + f.transport, + Clock.fixed(NOW.plusSeconds(60), ZoneOffset.UTC))) + .isInstanceOf(IllegalArgumentException.class); + verify(f.result, never()).close(); + } + + @ParameterizedTest + @ValueSource( + strings = {"duplicate", "unknown", "trailing", "coerced", "missing", "malformed", "oversize"}) + void codecRefusesNoncanonicalOrUnboundedState(String change) { + var f = new Fixture(); + String text = new String(f.scope.encode(), StandardCharsets.UTF_8); + byte[] bytes = + switch (change) { + case "duplicate" -> + text.replace("\"schema\":", "\"schema\":\"duplicate\",\"schema\":") + .getBytes(StandardCharsets.UTF_8); + case "unknown" -> + text.replaceFirst("\\{", "{\"credential\":\"untrusted\",") + .getBytes(StandardCharsets.UTF_8); + case "trailing" -> (text + "{}").getBytes(StandardCharsets.UTF_8); + case "coerced" -> + text.replace("\"gameInstanceId\":202", "\"gameInstanceId\":\"202\"") + .getBytes(StandardCharsets.UTF_8); + case "missing" -> + text.replace("\"expectedPriorPointerVersion\":null,", "") + .getBytes(StandardCharsets.UTF_8); + case "oversize" -> new byte[DirectTextAuthenticatedLobbyScope.MAX_BYTES + 1]; + default -> new byte[] {(byte) 0xc3, (byte) 0x28}; + }; + assertThatThrownBy(() -> DirectTextAuthenticatedLobbyScope.decode(bytes)) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"0", "-1", "01", "+1", "9223372036854775808"}) + void positiveReplyRejectsNoncanonicalOrOverflowingAccountMembershipIds(String membershipId) { + var f = new Fixture(); + var response = positive().toBuilder().setMembershipId(membershipId).build(); + assertThatThrownBy( + () -> DirectTextAuthenticatedLobbyJoin.decodeReply(f.scope, response.toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void positiveReplyPreservesTheFullPositiveAccountBigintBoundary() { + var f = new Fixture(); + var response = positive().toBuilder().setMembershipId(Long.toString(Long.MAX_VALUE)).build(); + assertThat(DirectTextAuthenticatedLobbyJoin.decodeReply(f.scope, response.toByteArray())) + .isEqualTo(response); + } + + @Test + void frozenRequestKeepsTransportCorrelationSeparateFromProxyOriginalContextAndJoinIds() { + var f = new Fixture(); + var context = f.frozen.request().getPlayerContext(); + assertThat(context.getSessionId()) + .isEqualTo(f.transport.transportSessionId()) + .isEqualTo("00042"); + assertThat(context.getRequestId()).isEqualTo(f.frozen.request().getRequestId()); + assertThat( + List.of( + context.getSessionId(), + f.original.callerContextId().toString(), + f.transport.proxyConnectionId().toString(), + f.original.requestId().toString(), + f.scope.recordId().toString(), + context.getRequestId())) + .doesNotHaveDuplicates(); + } + + @Test + void maximumNonAsciiOpaqueScopeIdRoundTripsExactlyInFrozenRequest() { + var f = new Fixture(); + String opaqueId = "\u4e16".repeat(2048); + assertThat(opaqueId).hasSize(2048); + assertThat(opaqueId.getBytes(StandardCharsets.UTF_8)).hasSize(6144); + var response = scopeResponse().toBuilder().setConnectScopeId(opaqueId).build(); + var scope = + new DirectTextAuthenticatedLobbyScope( + UUID.randomUUID(), + InitialGameplayLoginContextState.installed(f.original, f.result), + f.transport, + f.scope.publicTarget(), + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT.toString(), f.scope.issued().target(), response, CLOCK)); + var retainedScope = DirectTextAuthenticatedLobbyScope.decode(scope.encode()); + var frozen = + new DirectTextAuthenticatedLobbyJoin( + retainedScope, + DirectTextAuthenticatedLobbyJoin.requestFor(retainedScope, UUID.randomUUID()), + State.NEVER_DISPATCHED, + Optional.empty()); + byte[] bytes = frozen.request().toByteArray(); + assertThat(bytes.length) + .isGreaterThan(4096) + .isLessThanOrEqualTo(DirectTextAuthenticatedLobbyJoin.MAX_REQUEST_BYTES); + var restoredRequest = DirectTextAuthenticatedLobbyJoin.decodeRequest(bytes); + var restored = + new DirectTextAuthenticatedLobbyJoin( + retainedScope, restoredRequest, State.NEVER_DISPATCHED, Optional.empty()); + assertThat(restored.request()).isEqualTo(frozen.request()); + assertThat(restored.request().toByteArray()).containsExactly(bytes); + assertThat(retainedScope.issued().connectScopeId()).isEqualTo(opaqueId); + assertThat(restored.request().getConnectScopeId().getBytes(StandardCharsets.UTF_8)) + .containsExactly(opaqueId.getBytes(StandardCharsets.UTF_8)); + } + + @Test + void scopeEncodingRefusesOverBoundEnvelopeAfterSuccessfulConstruction() { + var f = new Fixture(); + // Only display text grows; routing selectors and every constructor-validated identity stay + // valid. + // The display has fewer UTF16 code units than MAX_BYTES but exceeds it as UTF8 before headers. + String display = "\u4e16".repeat(DirectTextAuthenticatedLobbyScope.MAX_BYTES / 3 + 1); + var target = target(display); + var oversized = + new DirectTextAuthenticatedLobbyScope( + UUID.randomUUID(), + InitialGameplayLoginContextState.installed(f.original, f.result), + f.transport, + target, + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT.toString(), + DirectTextAuthenticatedLobbyScope.targetFor(target), + scopeResponse(), + CLOCK)); + assertThat(oversized.publicTarget().worldDisplayName()).isEqualTo(display); + assertThatThrownBy(oversized::encode).isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsUnknownHiddenAndDuplicateProtobufData() { + var f = new Fixture(); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + var request = f.frozen.request(); + assertThatThrownBy( + () -> + DirectTextAuthenticatedLobbyJoin.decodeRequest( + request.toBuilder().setUnknownFields(unknown).build().toByteArray())) + .isInstanceOf(IllegalArgumentException.class); + var hidden = + request.toBuilder() + .setPlayerContext( + request.getPlayerContext().toBuilder().setCharacterId(UUID.randomUUID().toString())) + .build(); + assertThatThrownBy( + () -> + new DirectTextAuthenticatedLobbyJoin( + f.scope, hidden, State.NEVER_DISPATCHED, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + byte[] duplicate = new byte[request.getSerializedSize() * 2]; + System.arraycopy(request.toByteArray(), 0, duplicate, 0, request.getSerializedSize()); + System.arraycopy( + request.toByteArray(), + 0, + duplicate, + request.getSerializedSize(), + request.getSerializedSize()); + assertThatThrownBy(() -> DirectTextAuthenticatedLobbyJoin.decodeRequest(duplicate)) + .isInstanceOf(IllegalArgumentException.class); + for (UUID reused : + List.of( + f.original.requestId(), + f.original.callerContextId(), + f.scope.recordId(), + f.transport.proxyConnectionId(), + f.result.evidence().tokenJti())) { + assertThatThrownBy( + () -> + new DirectTextAuthenticatedLobbyJoin( + f.scope, + DirectTextAuthenticatedLobbyJoin.requestFor(f.scope, reused), + State.NEVER_DISPATCHED, + Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void onlyGenuineSelectionCanIssueScopeAndAnUnknownIssuanceIsNeverRetried() { + var f = new Fixture(); + when(f.selection.resolve(null, "private")).thenReturn(Optional.empty()); + assertThatThrownBy(() -> f.owner.realms(f.original, f.result, f.custody, null, "private")) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(f.account); + when(f.selection.resolve(null, "public")).thenReturn(Optional.of(f.scope.publicTarget())); + when(f.account.issueDirectTextConnectScope(any(), any())) + .thenReturn( + IssueDirectTextConnectScopeResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("AUTH_UNAVAILABLE")) + .build()); + assertThatThrownBy(() -> f.owner.realms(f.original, f.result, f.custody, null, "public")) + .isInstanceOf(IllegalArgumentException.class); + verify(f.account, times(1)).issueDirectTextConnectScope(any(), any()); + verify(f.repository, never()).retainScope(any(), any(), any()); + } + + @Test + void freshScopeIsRetainedAndIndependentlyReadAfterCommit() { + var f = new Fixture(); + when(f.selection.resolve(null, "public")).thenReturn(Optional.of(f.scope.publicTarget())); + when(f.account.issueDirectTextConnectScope(any(), any())).thenReturn(scopeResponse()); + when(f.repository.readCommittedScope(any())) + .thenAnswer( + call -> { + assertThat(f.events.getLast()).isEqualTo("COMMIT"); + return call.getArgument(0); + }); + var retained = f.owner.realms(f.original, f.result, f.custody, null, "public"); + assertThat(retained.issued().evaluatedAt()).isEqualTo(scopeResponse().getEvaluatedAt()); + assertThat(retained.issued().connectScopeExpiresAt()) + .isEqualTo(scopeResponse().getConnectScopeExpiresAt()); + verify(f.repository).retainScope(retained, f.result, CLOCK); + } + + @Test + void committedExactRequestAndPossibleStatePrecedeAccountAndReplyPersistence() { + var f = new Fixture(); + when(f.account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenAnswer( + call -> { + assertThat(f.events) + .containsSubsequence("FREEZE", "COMMIT", "READ", "CLAIM", "COMMIT", "READ"); + assertThat( + call.getArgument( + 0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)) + .isEqualTo(f.frozen.request().getPlayerContext()); + assertThat(call.getArgument(2, String.class)) + .isEqualTo(f.frozen.request().getRequestId()); + return positive(); + }); + var observation = f.owner.join(f.original, f.result, f.custody); + assertThat(observation.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING); + assertThat(observation.currentReply()).contains(positive()); + verify(f.account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + verify(f.result, never()).close(); + verify(f.account, never()).authenticate(any(), any()); + } + + @ParameterizedTest + @ValueSource( + strings = { + "AUTH_UNAVAILABLE", + "CONNECT_SCOPE_INVALID", + "JOIN_FAILED", + "INVALID_ARGUMENT", + "IDEMPOTENCY_CONFLICT" + }) + void genericErrorsNeverFabricateTerminalCompletionOrRearm(String code) { + var f = new Fixture(); + when(f.account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenReturn( + JoinPublicProductionMembershipResponse.newBuilder() + .setOutcomeCode(code) + .setError(ErrorDetail.newBuilder().setCode(code)) + .build()); + var first = f.owner.join(f.original, f.result, f.custody); + var continuation = f.owner.join(f.original, f.result, f.custody); + assertThat(first.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.RETAINED_UNRESOLVED); + assertThat(continuation.requestId()).isEqualTo(first.requestId()); + verify(f.repository, never()).recordPositiveReply(any(), any(), any()); + verify(f.account, times(1)).joinPublicProductionMembership(any(), any(), any(), any()); + } + + @Test + void positiveReplyAfterCustodyLossIsRetainedButNeverAppliedToReplacementTransport() { + var f = new Fixture(); + when(f.account.joinPublicProductionMembership(any(), any(), any(), any())) + .thenAnswer( + call -> { + f.resetAfterCallback.set( + true); // Controlled reset at callback exit, not real receiving proof. + return positive(); + }); + var observation = f.owner.join(f.original, f.result, f.custody); + assertThat(observation.status()) + .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.HISTORICAL_ONLY); + assertThat(observation.currentReply()).isEmpty(); + assertThat(f.retained.get().reply()).contains(positive()); + } + + @Test + void lostClaimCommitCannotDispatchOrAllocateACompetitor() { + var f = new Fixture(); + f.failClaimCommit.set(true); + assertThatThrownBy(() -> f.owner.join(f.original, f.result, f.custody)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(f.account); + assertThat(f.retained.get().state()).isEqualTo(State.DISPATCH_POSSIBLE); + f.failClaimCommit.set(false); + var continuation = f.owner.join(f.original, f.result, f.custody); + assertThat(continuation.requestId()).isEqualTo(f.frozen.requestId()); + verifyNoInteractions(f.account); + } + + @Test + void resetExpiredPrivateResultAndChangedTransportDenyBeforeEffects() { + var f = new Fixture(); + f.live.set(false); + assertThatThrownBy(() -> f.owner.join(f.original, f.result, f.custody)) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(f.repository, f.account); + f.live.set(true); + assertThatThrownBy( + () -> + f.scope.requireCurrent( + f.original, + f.result, + new ObservedDirectTextTransport("42", UUID.randomUUID()), + CLOCK)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + f.scope.requireCurrent( + f.original, + f.result, + f.transport, + Clock.fixed(NOW.plusSeconds(120), ZoneOffset.UTC))) + .isInstanceOf(IllegalArgumentException.class); + } + + private static final class Fixture { + final InitialGameplayLoginAttemptCoordinates original = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 7); + final ObservedDirectTextTransport transport = + new ObservedDirectTextTransport("00042", UUID.randomUUID()); + final CanonicalGameplayLoginResult result = mock(CanonicalGameplayLoginResult.class); + final DirectTextAuthenticatedLobbyRepository repository = + mock(DirectTextAuthenticatedLobbyRepository.class); + final DirectTextWorldSelectionService selection = mock(DirectTextWorldSelectionService.class); + final AccountClient account = mock(AccountClient.class); + final AtomicBoolean live = new AtomicBoolean(true); + final AtomicBoolean resetAfterCallback = new AtomicBoolean(); + final AtomicBoolean failClaimCommit = new AtomicBoolean(); + final List events = new ArrayList<>(); + final DirectTextAuthenticatedLobbyScope scope; + final DirectTextAuthenticatedLobbyJoin frozen; + final AtomicReference retained = new AtomicReference<>(); + final DirectTextAuthenticatedLobbyOwner owner; + final DirectTextAuthenticatedLobbyCustody custody = + new DirectTextAuthenticatedLobbyCustody() { + @Override + public T withCurrent( + InitialGameplayLoginAttemptCoordinates coordinates, + CanonicalGameplayLoginResult borrowed, + Function action) { + if (!live.get() || !original.equals(coordinates) || borrowed != result) + throw new IllegalStateException("Controlled custody unavailable"); + try { + return action.apply(transport); + } finally { + if (resetAfterCallback.get()) live.set(false); + } + } + }; + + Fixture() { + when(result.evidence()).thenReturn(evidence(original)); + when(result.compactJwtBytes()) + .thenAnswer(call -> "fixture-private-token".getBytes(StandardCharsets.US_ASCII)); + var target = target("Forest"); + scope = + new DirectTextAuthenticatedLobbyScope( + UUID.randomUUID(), + InitialGameplayLoginContextState.installed(original, result), + transport, + target, + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT.toString(), + DirectTextAuthenticatedLobbyScope.targetFor(target), + scopeResponse(), + CLOCK)); + frozen = + new DirectTextAuthenticatedLobbyJoin( + scope, + DirectTextAuthenticatedLobbyJoin.requestFor(scope, UUID.randomUUID()), + State.NEVER_DISPATCHED, + Optional.empty()); + retained.set(frozen); + when(repository.current(any(), any(), any(), any())).thenReturn(scope); + when(repository.freezeCurrentJoin(any(), any(), any(), any())) + .thenAnswer( + call -> { + events.add("FREEZE"); + return retained.get(); + }); + when(repository.readCommittedJoin(any())) + .thenAnswer( + call -> { + events.add("READ"); + return retained.get(); + }); + when(repository.claimDispatch(any(), any(), any(), any())) + .thenAnswer( + call -> { + events.add("CLAIM"); + if (retained.get().state() != State.NEVER_DISPATCHED) return false; + retained.set( + new DirectTextAuthenticatedLobbyJoin( + scope, frozen.request(), State.DISPATCH_POSSIBLE, Optional.empty())); + return true; + }); + doAnswer( + call -> { + retained.set( + new DirectTextAuthenticatedLobbyJoin( + scope, + frozen.request(), + State.COMPLETED, + Optional.of(call.getArgument(2)))); + return null; + }) + .when(repository) + .recordPositiveReply(any(), any(), any()); + var transactions = + new PlatformTransactionManager() { + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + return new SimpleTransactionStatus(); + } + + @Override + public void commit(TransactionStatus status) { + events.add("COMMIT"); + if (failClaimCommit.get() && retained.get().state() == State.DISPATCH_POSSIBLE) + throw new IllegalStateException("Lost commit reply"); + } + + @Override + public void rollback(TransactionStatus status) { + events.add("ROLLBACK"); + } + }; + owner = + new DirectTextAuthenticatedLobbyOwner( + repository, selection, account, transactions, CLOCK); + } + } + + private static CanonicalGameplayLoginResult.NonSecretEvidence evidence( + InitialGameplayLoginAttemptCoordinates original) { + try { + return new CanonicalGameplayLoginResult.NonSecretEvidence( + ACCOUNT, + original.requestId(), + original.callerContextId(), + UUID.randomUUID(), + "a".repeat(64), + GameSessionAccountDelegationProfile.PROFILE, + NOW.minusSeconds(2).getEpochSecond(), + NOW.minusSeconds(2).getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + "1", + "5", + canonical(GameSessionAccountDelegationProfile.authorityTuple(1, 1)), + canonical( + List.of( + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:account/" + ACCOUNT, + "outboxSequence", + "0"), + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:issuer/firemud-account-service", + "outboxSequence", + "0"))), + canonical(List.of())); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + } + + private static ByteString canonical(Object value) throws Exception { + return ByteString.copyFrom( + Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value))); + } + + private static IssueDirectTextConnectScopeResponse scopeResponse() { + return IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("opaque-account-scope") + .setEvaluatedAt(NOW.minusSeconds(1).toString()) + .setConnectScopeExpiresAt(NOW.plusSeconds(60).toString()) + .build(); + } + + private static JoinPublicProductionMembershipResponse positive() { + return JoinPublicProductionMembershipResponse.newBuilder() + .setSuccess(true) + .setOutcomeCode("JOINED") + .setAccountId(ACCOUNT.toString()) + .setTenantId("101") + .setMembershipId("90") + .setMembershipVersion(3) + .setMembershipAuthorityGeneration(1) + .build(); + } + + private static CanonicalPlayableTarget target(String display) { + return new CanonicalPlayableTarget( + "gameplay", + "studio", + UUID.randomUUID(), + "forest", + display, + UUID.randomUUID(), + "public", + "Live", + 101, + 202, + UUID.randomUUID(), + "SHARED", + UUID.randomUUID(), + UUID.randomUUID(), + 303, + 1, + 7, + "d".repeat(64), + 82, + "original-open", + "a".repeat(64), + OriginKind.NO_PRIOR_POINTER, + null, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "c".repeat(64), + 27, + "sha256:" + "f".repeat(64), + Outcome.COMMITTED, + false, + NOW.minusSeconds(1), + "ALLOW_NEW"); + } +} From fd136e1037607b188c3b6af562809c4f2bb53f16 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 03:57:12 +1300 Subject: [PATCH 02/16] Record fresh authenticated lobby startup qualification --- .../implementation-tracking/player-access-and-session.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 402e1646c9..27d8786e2c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -380,7 +380,7 @@ R1407/R1408 prepare the direct-text observation and menu-retention boundary. The The current local source adds a manually composed Redis store and one-key CAS script for the public `WORLDS` UI menu. It retains the bounded ordered menu under the tenantless family owned by [the Redis menu contract](../../architecture/system-architecture-redis.md#direct-text-worlds-ui-menu), correlating the exact observed original proxy UUID separately from the numeric transport session ID. This is menu correlation only: it stores no Account ID, credentials, REALMS scope or JOIN intent, and does not prove authenticated ingress, continuity or admission. The owner and script remain unregistered; production protected-connection binding, authenticated TCP receiving custody and hidden rebind remain gaps, and no deployed ACL change is included. The combined focused gate passes 133 cases, including eight physical standalone-Redis cases, with no failures, errors or skips; selected main/test/integration static checks and full Java formatting pass. The first two aggregates retain binary-array generic-varargs analysis warnings; explicit single-key arrays and narrow, physically justified annotations complete the qualification. This remains controlled component proof, not authenticated transport custody or production registration. See [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status) for the local runtime consequence. -The next local direct-text preparation adds the separately owned [authenticated lobby SQL companion](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion), retaining the exact caller-bound Account scope and a durable frozen JOIN original before dispatch. Its current-selection pointer cannot replace earlier unknown attempts, and the existing original LOGIN journal/codec and retention hold remain. R1414 passes 29 focused unit cases and 16 real-PostgreSQL cases with zero failures, errors or skips. Physical proof migrates a populated pre-companion LOGIN journal, preserves its complete original row, exercises both abandonment/claim lock orders and concurrent dispatch claims, retains uncertain outcomes across owner replacement, rejects direct identity/transition/retention violations, and bounds positive membership identifiers to Account’s canonical positive BIGINT domain. Selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Game Session packaging pass across the combined recovery and final main-analysis gate; the first two aggregates retain broad-catch, generated-immutable-message analysis and test-fixture synchronization failures. The manually composed owner can issue scope and dispatch the frozen original through the existing Account client under a required protected-custody port, but no genuine producer for that port or text-command registration is supplied. Fresh source-built startup qualification is pending. This does not wire live REALMS/JOIN text dispatch, prove genuine receiving custody, register a production owner, settle negative/unknown results, release retained rows or establish admission. +The #3366 direct-text preparation adds the separately owned [authenticated lobby SQL companion](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion), retaining the exact caller-bound Account scope and a durable frozen JOIN original before dispatch. Its current-selection pointer cannot replace earlier unknown attempts, and the existing original LOGIN journal/codec and retention hold remain. R1414 passes 29 focused unit cases and 16 real-PostgreSQL cases with zero failures, errors or skips. Physical proof migrates a populated pre-companion LOGIN journal, preserves its complete original row, exercises both abandonment/claim lock orders and concurrent dispatch claims, retains uncertain outcomes across owner replacement, rejects direct identity/transition/retention violations, and bounds positive membership identifiers to Account’s canonical positive BIGINT domain. Selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Game Session packaging pass across the combined recovery and final main-analysis gate; the first two aggregates retain broad-catch, generated-immutable-message analysis and test-fixture synchronization failures. The manually composed owner can issue scope and dispatch the frozen original through the existing Account client under a required protected-custody port, but no genuine producer for that port or text-command registration is supplied. Fresh source-built held-admission smoke on `85d4568536` passes the actual backend WORLDS → LOGIN → PLAY → LOOK → LOGOUT flow and Gateway/Telnet denial checks. Canonical cleanup completes, and independent exact-project checks find no containers, networks or volumes. This proves startup and the isolated held flow, not successful public admission or a production custody producer. This does not wire live REALMS/JOIN text dispatch, prove genuine receiving custody, register a production owner, settle negative/unknown results, release retained rows or establish admission. ### Account operation and signer source preparation From 8e8d1f9543a8038a349c7291d776b1978928d34e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:11:50 +1300 Subject: [PATCH 03/16] Contain legacy Account callers and verify email token consumption atomically --- .github/workflows/ci.yml | 4 + .../account-service/api-contracts.md | 20 +- .../account-service/configuration.md | 8 + .../account-service/runtime-and-data.md | 2 + .../runtime-and-data.md | 2 +- design/project-management/ai-observations.md | 4 +- .../player-access-and-session.md | 10 + dev-tools/README.md | 2 + dev-tools/certs/README.md | 11 +- dev-tools/certs/clean-dev-certs.sh | 21 +- dev-tools/certs/ensure-dev-certs.sh | 27 +- dev-tools/certs/generate-dev-certs.sh | 90 +- .../account-workload-namespace-contract.sh | 102 +++ .../tests/dev-certs-retention-contract.sh | 134 +++ docker/docker-compose.yml | 3 + .../account-service/templates/deployment.yaml | 7 + .../EmailVerificationTokenRepository.java | 31 + .../service/impl/AccountGrpcService.java | 262 +++--- .../service/impl/AccountServiceImpl.java | 26 +- .../impl/VirtualCurrencyGrpcService.java | 99 +-- .../src/main/resources/application-prod.yml | 2 +- .../src/main/resources/application.yml | 5 +- .../AccountApplicationIntegrationTest.java | 613 +++++++++++++ .../EmailVerificationHttpAuthWiringTest.java | 154 ++++ .../AccountCredentialPeerGrpcMtlsTest.java | 332 +++++++ .../service/impl/AccountGrpcServiceTest.java | 811 ++++++++++++------ .../service/impl/AccountServiceImplTest.java | 115 ++- .../impl/VirtualCurrencyGrpcServiceTest.java | 188 ++-- 28 files changed, 2391 insertions(+), 694 deletions(-) create mode 100644 dev-tools/tests/account-workload-namespace-contract.sh create mode 100644 dev-tools/tests/dev-certs-retention-contract.sh create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3429d36b1c..0ad6a48a97 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -509,6 +509,8 @@ jobs: time bash ./dev-tools/tests/kubectl-version-skew-contract.sh TIMEFORMAT='bash ./dev-tools/tests/helm-transaction-proof-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/helm-transaction-proof-contract.sh + TIMEFORMAT='bash ./dev-tools/tests/account-workload-namespace-contract.sh: real=%3R user=%3U sys=%3S' + time bash ./dev-tools/tests/account-workload-namespace-contract.sh TIMEFORMAT='bash ./dev-tools/tests/preview-image-tag-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/preview-image-tag-contract.sh TIMEFORMAT='bash ./dev-tools/tests/preview-merge-image-tag-contract.sh: real=%3R user=%3U sys=%3S' @@ -525,6 +527,8 @@ jobs: time bash ./dev-tools/tests/ensure-local-compose-env-contract.sh TIMEFORMAT='bash ./dev-tools/tests/local-compose-mtls-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/local-compose-mtls-contract.sh + TIMEFORMAT='bash ./dev-tools/tests/dev-certs-retention-contract.sh: real=%3R user=%3U sys=%3S' + time bash ./dev-tools/tests/dev-certs-retention-contract.sh TIMEFORMAT='bash ./dev-tools/tests/smoke-image-env-contract.sh: real=%3R user=%3U sys=%3S' time bash ./dev-tools/tests/smoke-image-env-contract.sh TIMEFORMAT='bash ./dev-tools/tests/minio-pr-smoke-bootstrap-contract.sh: real=%3R user=%3U sys=%3S' diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index ee61471a42..bc5df0c3e0 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -90,7 +90,7 @@ Account has unregistered individual Creator Party, hosted-terms catalog, and ind `CommitTenantCapacityAdmission` is target-only. Its canonical request contract requires the stable identity, expected complete applicable `authorityTuple`, separate expected `entitlementVersion`, exact expected billing stream/checkpoint evidence, capacity delta, and versioned `mutationDigest`, but no proto RPC, durable authority/usage ledger, caller integration, or reservation-finalization path is implemented. The target replay rule is exact identity-and-payload replay with any changed tuple, entitlement, checkpoint, delta, or digest producing an idempotency conflict; implementation and focused proof remain future capability work rather than a nonfunctional service seam. -The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` and `ExportAccount` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. PostgreSQL runtime proof for retry/recovery after an unknown commit outcome and direct text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. For text `PLAY`, the consumer currently proceeds only when `membershipExists` and `gameplayAdmissionAllowed` are true; it does not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`. This text consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. +The account lifecycle API, export surfaces, and deletion-precondition contracts are defined at the current Account Service boundary, but lifecycle state-transition execution remains partial as recorded in [Runtime & Data](./runtime-and-data.md). Account is the authority and transaction boundary for the committed transition, authority-generation/version advance, and durable event/outbox evidence. Downstream revocation, projection, cleanup, and provider reconciliation are ordered transition execution; partial downstream completion must be reported separately and must not be mistaken for a rolled-back lifecycle state or completed enforcement outcome. The current `GET /accounts/{accountId}/export` implementation is Account/profile-local, with identity projections governed by [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity). This is partial data, not the canonical target portable-data export lifecycle, which is `POST /accounts/{accountId}/exports` followed by the stable status and content resources defined below. `ExportTenantData` targets the separate tenant-admin route `GET /tenant-admin/tenants/{tenantId}/export`, which is tenant-wide and selects no account subject; the current account-targeted gRPC and legacy tenant-export wiring remain implementation drift. Password reset, username reminder, and email-verification tokens are account-scoped rather than tenant-keyed. Profiles are tenant-scoped under ADR 0042, so the current account-only `/profiles/{accountId}` route and policy remain implementation drift pending direct convergence on tenant-qualified routes. The legacy profile selector and authorization consequences are recorded under [REST APIs](#rest-apis); membership-authority-generation validation remains unimplemented. Public registration follows the response identity contract below and writes that same public identity in its platform audit outbox row; it creates only global Account state and does not create a profile or tenant membership. Explicit public-production `JOIN` / `Join & Play` is implemented locally through `JoinPublicProductionMembership`. Account first persists a policy-independent request-intent digest and `PENDING` operation, then evaluates current public-join entitlement. Only an authoritative `AVAILABLE` evaluation creates the versioned policy-bound operation digest and stores the exact `allowPublicJoin` and `entitlementVersion`; an unavailable attempt records its failure and availability and leaves the operation `PENDING` without invented policy evidence. A matching retry can re-evaluate that pending operation, and the membership commit gate revalidates the same digest and policy evidence. The operation, membership transition, and tenant audit outbox evidence are committed together. Focused local PostgreSQL retry/rollback proof is recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-email-verification-and-deferred-currency-containment); original-outcome observation after retry authority expires and direct-text end-to-end proof remain open. The current runtime membership response carries `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, `membershipLifecycleState`, `membershipAuthorityGeneration`, and `evaluatedAt`, with `accountId` and `tenantId` context. Current `/auth/connect-token` issuance returns `AUTH_UNAVAILABLE` after bootstrap and scope validation, before replay or admission-authority reads, token minting, or replay/session mutation; cached-success replay and current membership, entitlement, grant, and pointer checks do not execute on this path. For text `PLAY`, the consumer currently proceeds only when `membershipExists` and `gameplayAdmissionAllowed` are true; it does not enforce the emitted `membershipLifecycleState` or `membershipAuthorityGeneration`. For eligible public-production text `PLAY`, missing or existing non-admitting membership may currently produce `JOIN_REQUIRED`. This text consumer therefore does not distinguish `INACTIVE` from another existing non-admitting state even though Account emits the lifecycle field. Current non-public or non-visible target handling remains split across existing discovery, membership, and grant surfaces; the complete grant/entitlement admission predicate at connect-token issuance remains target-only. The obsolete implicit membership-writer surface has been removed and is not a compatibility operation. `/auth/player-bootstrap` is account-first and factor-aware. The browser connect-token body and OpenAPI response are defined as metadata-only; any issued raw token is carried only in the HttpOnly cookie. The registry-backed issuance, refresh, revocation, durable retry, and authority-generation behaviors below are target state, including the contracts for `Authenticate`, `RefreshGameplayServiceToken`, `/auth/player-bootstrap`, `/auth/logout`, and `/auth/logout-all`; `/auth/login` is currently routable but still lacks the complete registry-backed target behavior. Current Account sessions use the legacy `session:auth:account::` key and, for tenant-scoped sessions, the companion `session:auth:tenant::` key rather than the canonical single `session:auth:token:` registry record. The `player-bootstrap` credential/result profile uses the persisted Account UUID in its result `accountId` and matching JWT subject/Account claim; its Account-owned reader rejects noncanonical, numeric or mismatched identity before resolving the private storage row. The final ordinary receiving composition also carries UUID ordinary login results/credentials, UUID shared intake and forwarding, UUID internal selectors and UUID Account references in downstream consumers; tenant identifiers remain numeric. Full token-profile/registry qualification remains held. Derived `bootstrap-connect-scope` artifacts use the persisted Account UUID in their signed subject/Account claim, through the shared browser/direct-text producer and dedicated Account reader. Profile self-binding and REST caller identity use UUID `SessionContext`; private Account SQL rows remain numeric. The legacy GameInstance owner/StartSession boundary remains separately numeric and unqualified. The bounded response and REST selector identity contract is defined below. Scoped-role population and tenant-switching proof remain target-state work: current `authenticate` issuance provides `globalRoles` but does not yet populate or prove `scopedRoles[tenantId]` as authorization evidence. ### Account UUID Response and REST Selector Identity @@ -104,7 +104,7 @@ The final ordinary receiving composition carries UUID ordinary JWT subjects/Acco ### Current vs Target Export Lifecycle -The current `GET /accounts/{accountId}/export` route and current `ExportAccount` implementation are synchronous Account/profile-local exports. They return only the Account-owned local result, have no cross-service required-owner fan-in, and do not satisfy ADR 0050; neither the route nor the current implementation may be described as a complete portable-data export. +The current `GET /accounts/{accountId}/export` route returns a synchronous Account/profile-local result. It has no cross-service required-owner fan-in and does not satisfy ADR 0050. The legacy `ExportAccount` gRPC adapter is unavailable before selector parsing or owner reads because no authorized internal caller is configured; this containment does not change the separately authorized REST/service export. The target lifecycle is the asynchronous `POST /accounts/{accountId}/exports` operation followed by its stable status and content resources. Target `ExportAccount` gRPC behavior is the protocol equivalent of that lifecycle: Account durably creates or replays one export job, gathers every required owning-service contribution, exposes a versioned manifest with explicit owner outcomes, and makes content available only after the required fan-in reaches its terminal contract. Each initiation uses the already established caller `requestId`; Account computes a canonical, versioned `requestDigest` from the normalized export operation and persists one `export_operation` before fan-in, assigning its stable `exportId`. A retry with the same request identity and matching digest replays that operation and `exportId`, including after a lost response; reusing the request identity with a different digest is an idempotency conflict and cannot create another export. The current local implementation is known drift from this target. @@ -137,16 +137,16 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `UpdateProfile` – modifies the caller's profile relationship through canonical `PUT /tenants/{tenantId}/profiles/{accountId}` under the same `tenant_regular` authorization and caller-subject binding. Membership authority follows [Account Runtime and Data](./runtime-and-data.md#membership-and-entitlement-authority); the local API triggers notification emails. The response projection returns `PRIVATE` for a retained legacy `HIDDEN_STAFF` value without rewriting the stored row; normative policy remains in [ADR 0046](../../decisions/adr-0046-bounded-friend-presence-with-private-by-failure-redaction.md). The legacy `/profiles/{accountId}` route is implementation drift and `platformAdmin` is not an override. - `ListPresenceVisibilityPolicies` – bounded internal bulk read of current tenant-scoped profile visibility policy for up to 100 canonical Account UUIDs. Account resolves known subjects through one local UUID batch query with the same persisted provenance and source-row checks as scalar identity reads, then returns policies keyed by UUID. Unknown or unproven entries are intentionally omitted so Social applies complete `PRIVATE` redaction. -- `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current implementation behind this method remains the local legacy export described above. +- `ExportAccount` – **target-state RPC** equivalent of `POST /accounts/{accountId}/exports`; starts or reads the persisted export operation for the caller's `requestId` and matching versioned `requestDigest`, returning the same stable `exportId` on replay and an idempotency conflict on digest mismatch. It gathers every required owning-service contribution and exposes a versioned portable-data manifest with explicit complete, partial, omitted, redacted, unavailable, retryable, failed, and separately retained owner outcomes; this is not a promise of every account-related record or secret. The current gRPC adapter returns `FAILED_PRECONDITION` before selector parsing or owner reads; this does not implement the target export operation. - `CommitTenantCapacityAdmission` – **target-state internal RPC** called only by Game Session or World Management after a fresh entitlement evaluation, through exactly one complete caller-policy alternative: Game Session presents the exact **Game Session caller mTLS identity** with typed `PlayerExecutionContext` and its live player-binding checks, or World Management presents the exact **World Management caller mTLS identity** with tenant/operation-bound instance-lifecycle context and its live lifecycle checks. The request carries stable outer `(tenantId, requestId, admissionId)`, a fresh per-attempt `admissionAttemptId`, the current `capacityRearmFence`, the exact complete Account-authenticated evidence bundle returned by `GetTenantEntitlementsForRuntime` including `bundleVersion`, `snapshotIdentity`, `evaluationIdentity`, all entitlement fields, the complete applicable `authorityTuple`, exact applicable `tenantBillingCutoff`, and complete `outboxCheckpoints[]`; it also carries bounded `capacityDelta`. A versioned `mutationDigest` is required over the attempt identity, fence, and complete payload. Account compares the outer identity and complete attempt payload in one transaction before creating or replaying the reservation; an exact retry replays, while any changed bundle field, cutoff/checkpoint, delta, attempt ID, fence, or digest is an idempotency conflict before usage mutation. Stale evidence, exhausted quota, unavailable authority, malformed identity, and conflicting retries fail closed. No proto RPC, caller integration, durable usage ledger, or reservation lifecycle is implemented yet. See the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). - `CommitTenantCapacityAdmission` reservation retries use one durable reservation. The initial attempt requires no rearm CAS and binds its fresh `admissionAttemptId`, current `capacityRearmFence`, exact payload, and digest. A fresh attempt is accepted only after an Account-owned atomic CAS over the same outer identity, the terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` predecessor and durable no-commit proof, the current fence, and the prior digest; the CAS advances the fence and binds the fresh attempt, payload, and digest without allocating a second reservation or capacity claim. Exact attempt-and-fence retries replay; a changed field without a matching rearm returns `IDEMPOTENCY_CONFLICT`, while a stale or losing fence returns `FENCE_REJECTED` only with the required no-accept/no-runtime-mutation proof and never rearms. -- `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only; the current account-targeted gRPC request is implementation drift. +- `ExportTenantData` – tenant-wide billing-safe export for one tenant, available to the caller's live `tenantAdmin` membership while gameplay is billing-blocked and limited to tenant-owned exportable records plus minimum stable subject references. The target request is tenant-only. The legacy account-targeted gRPC handler returns `FAILED_PRECONDITION` before parsing selectors or reading Account data because no authorized internal caller is configured; the target tenant-only transport and authorization remain unimplemented. This containment does not change the separately authorized REST/service export path. - `DeleteAccount` – begins or completes global account deletion according to the account lifecycle state machine; it is not a tenant-scoped membership deletion. - Pending-deletion access is a separate opaque Account credential, not a JWT or normal account session. The non-export deletion-specific routes are `GET /accounts/{accountId}/deletion`, `POST /accounts/{accountId}/deletion/cancel`, and `POST /accounts/{accountId}/deletion/billing-settlement`; each is classified `pending_deletion_scoped` for its exact action and bound to the Account-owned deletion workflow registry. The account export lifecycle is state-dependent but always uses the canonical asynchronous `POST /accounts/{accountId}/exports`, `GET /accounts/{accountId}/exports/{exportId}`, and `GET /accounts/{accountId}/exports/{exportId}/content` resources: active accounts use the ordinary authenticated account subject, while pending-deletion accounts use the pending-deletion credential and `pending_deletion_scoped` classification on that same lifecycle. These target routes are not currently routable. - `POST /auth/pending-deletion/recovery/challenge` and `POST /auth/pending-deletion/recovery` are dedicated target recovery routes classified `public`; they may issue only `pending-deletion-access`, never normal login, bootstrap, connect-token, tenant, purchase, or gameplay authority. These target routes are not currently routable. - `RequestPasswordReset` – initiate a password reset email. Public initiation returns the same neutral success for known and unknown normalized email addresses; an unknown address creates no token and schedules no delivery. - `CompletePasswordReset` – update the password using a token. An Account without its required owner-proven authority baseline fails with `AUTH_UNAVAILABLE` (HTTP 503) instead of completing a security-relevant write; its password update and reset-token consumption do not commit. Retained pre-V40 Accounts are not automatically enrolled or backfilled. Deployment/activation and proof limits are recorded in the [retained Account source prerequisite](../../../project-management/implementation-tracking/player-access-and-session.md#retained-account-source-prerequisite). -- External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The obsolete caller-asserted `POST /accounts/{accountId}/external` controller route is removed and denied at the public edge; the persistence and internal service scaffold remains unsupported implementation drift and is not evidence of an available provider integration. No provider route may become routable until the target globally bound flow is implemented and proved. +- External identity binding and lifecycle are owned by [Account Runtime and Data](./runtime-and-data.md). Provider-specific linking is planned but not currently routable. The obsolete caller-asserted `POST /accounts/{accountId}/external` controller route is removed and denied at the public edge; the persistence and internal service scaffold remains unsupported implementation drift and is not evidence of an available provider integration. The legacy `LinkExternalAccount` gRPC adapter returns `FAILED_PRECONDITION` before parsing, lookup or mutation. No provider route may become routable until the target globally bound flow is implemented and proved. - `IssuePlayerBootstrapToken` – authenticate a first-party player account and issue the short-lived `player-bootstrap` token profile used only for gameplay bootstrap. - `ListBootstrapWorlds` – list caller-visible worlds for first-party gameplay bootstrap. - `ListBootstrapRealms` – list caller-visible realms for a selected world during first-party gameplay bootstrap. @@ -164,8 +164,8 @@ Ordinary Account gRPC methods use canonical Account UUID text for Account-valued - `GetRealmAccessGrant(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` / `ListRealmAccessGrantsForAccount(accountId, tenantId, worldSlug, realmSlug, playtestLifecycleId, requestId)` – authoritative internal realm-grant reads for non-public realm bootstrap discovery and gameplay admission; the lifecycle-bound target is mandatory and a tenant-global `realmSlug` lookup is invalid. - `GetTenantEntitlementsTenant` – caller-bound tenant-admin entitlement view for billing-safe control-plane UX. - `GetTenantEntitlementsCrossTenantSupportSafe` – cross-tenant support-safe entitlement view with redacted, high-level fields only. -- `RequestEmailVerification` – send an account-scoped verification email. The public REST initiation resolves a normalized email address and returns the same neutral success for known and unknown addresses; the internal gRPC method retains its account-ID request. Unknown public requests create no token and schedule no delivery. -- `VerifyEmail` – confirm an email verification token. An Account without its required owner-proven authority baseline fails with `AUTH_UNAVAILABLE` (HTTP 503) instead of committing the verification write; the email-verification change and token consumption do not commit. Retained pre-V40 Accounts are not automatically enrolled or backfilled. Deployment/activation and proof limits are recorded in the [retained Account source prerequisite](../../../project-management/implementation-tracking/player-access-and-session.md#retained-account-source-prerequisite). +- `RequestEmailVerification` – send an account-scoped verification email. The public REST initiation resolves a normalized email address and returns the same neutral success for known and unknown addresses. The unused Account-ID gRPC initiation adapter returns `FAILED_PRECONDITION` before lookup or mail dispatch until an explicit receiving caller policy is supplied; its retained request shape grants no workload or caller-subject permission. Unknown public requests create no token and schedule no delivery. +- `VerifyEmail` – confirm a single-use email verification token while it is strictly unexpired. Token consumption and the verified-email change commit together under the Account owner transaction; a rejected claim cannot mutate the Account. An Account without its required owner-proven authority baseline fails with `AUTH_UNAVAILABLE` (HTTP 503) instead of committing the verification write; the email-verification change and token consumption do not commit. Retained pre-V40 Accounts are not automatically enrolled or backfilled. Deployment/activation and proof limits are recorded in the [retained Account source prerequisite](../../../project-management/implementation-tracking/player-access-and-session.md#retained-account-source-prerequisite). - `CreatePaymentIntent` – legacy generic Stripe substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before service or provider invocation; the retained underlying service method remains unsupported substrate and is not a v1 hosting-billing operation or entitlement path. The [Stripe Integration](./stripe-integration.md) target requires exact authenticated mTLS workload/method allowlisting, not a bearer-token variant; that allowlist is not currently implemented. - `CreateSubscription` – target operation for creating one recurring hosting subscription under the canonical [Subscription Management](./subscription-management.md) lifecycle and [Stripe Integration](./stripe-integration.md) provider-binding contract. The local proto carries only tenant/account/plan fields and cannot establish the required caller-bound billing owner, instrument, stable request identity, or provider-confirmed lifecycle. The current handler therefore returns `FAILED_PRECONDITION` before mutation until that complete boundary is implemented. - `CreateDonation` – legacy generic donation substrate; unsupported/deferred and gated. The RPC now returns `FAILED_PRECONDITION` before service or provider invocation; its retained underlying service method remains unsupported and cannot create a FireMUD entitlement. Its [Stripe Integration](./stripe-integration.md) target requires exact authenticated mTLS workload/method allowlisting; that allowlist is not currently implemented. @@ -256,6 +256,12 @@ The prepared original activation-protection methods authenticate the exact same- `AccountStartSessionAdmissionProtectionService.AcquireStartSessionAdmissionProtection` is an internal schema-1 Game Session-to-Account method defined by the [acquisition proto](../../../../protos/account/v1/start_session_admission_protection_acquisition.proto). It transports the complete canonical Account protection request, bounded to 768 KiB, and returns complete owner-produced protection evidence, bounded to 8 MiB; the receiver's wire bound includes the codec's finite 8-byte protobuf envelope allowance. The manually constructed receiver requires the exact same-namespace Game Session mTLS identity and rejects authenticated end-user context before decoding or owner work. The request is binding/comparison input, not caller authority or terminal evidence. Account's acquisition owner independently checks the original attempt and current source, retains or replays the immutable protection, and verifies its exact current readback without extending the original lease. The method remains unregistered and is not a public API. Account's terminal settlement is a separate owner operation; its authenticated Game Session read contract is defined in [Game Session API Contracts](../game-session-service/api-contracts.md#account-purpose-initial-admission-settlement-read). +### Legacy credential RPC and local demo fixture + +The registered legacy `Authenticate`, `RequestEmailLoginOtp` and `VerifyEmailLoginOtp` handlers require certificate-derived exact same-namespace Game Session identity before invoking credential owners. The OTP methods have no Entity caller exception. Workload peer authorization does not replace normal credential verification, persisted Account UUID provenance or source-owner checks. + +`Authenticate` alone has a separate local demo fixture branch for the exact same-namespace Entity Management certificate identity. Account must explicitly enable `firemud.account.local-demo-authentication.enabled`, configure the demo email identity, and run with the `local-fixture` profile without `prod`. The flag defaults to false and the configured identity defaults empty; an enabled local fixture with no valid configured identity fails startup. The request must match that configured identity before ordinary Account password verification runs. A caller-side seed flag, bearer or claimed peer header cannot enable the receiving branch, and enabling it never permits Entity OTP requests or general Entity credential access. This is the bounded local/run-fixture used by [Entity demo seeding](../entity-management-service/runtime-and-data.md#implementation-status); it does not activate the separate canonical private LOGIN receiver, production registration or gameplay admission. + ## REST APIs Implemented Account-valued REST selectors and response fields use canonical Account UUID text. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, and `ProfileDto.accountId` serialize as JSON strings; Account-issued login and bootstrap tokens carry the same UUID in `sub` and `accountId`. Current `/accounts/{accountId}` and profile handlers resolve those identities through Account's persisted UUID/provenance boundary before using private local rows. Tenant identifiers retain their existing representation. The Account identity contract is owned here with [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md); this paragraph records the local wire and storage boundary. diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index ac85376d71..ce8775571a 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -22,6 +22,14 @@ In player-facing environments, the interim `jwt-signing-keys` private bundle is The configurable cleanup margin controls issued-token registry retention only. Gameplay continuity is a separate Game Session policy documented in [Reconnection](../../system-architecture-reconnection.md); Account configuration does not derive or widen that lifetime. +### Kubernetes Workload Namespace + +The Account Helm Deployment supplies `FIREMUD_GRPC_WORKLOAD_NAMESPACE` from the pod's `metadata.namespace` through the Kubernetes downward API. The chart reserves this variable and rejects an `extraEnv` entry with the same name; other `extraEnv` entries remain available. Account uses this configured namespace for the workload-peer checks described in the [Account API contract](./api-contracts.md). + +### Local Demo Authentication Fixture + +The Account receiving flag `FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_ENABLED` defaults to `false`, and `FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_EMAIL` defaults empty. Local/run-owned Compose explicitly enables the flag, configures its demo email and selects `local-fixture` for Account. Active `prod` excludes this fixture even when the flag is set. These settings supply only the Account-local delivery described by the [credential fixture contract](./api-contracts.md#legacy-credential-rpc-and-local-demo-fixture); the Entity seeding flag supplies no receiving authority. + ## Implementation Status The current runtime still uses the shared-HMAC compatibility profile for issuance and validation and has no asymmetric non-exportable signer delegation. Any Secret-backed asymmetric materialization is the explicit interim fallback/drift, not canonical target custody; the current preflight/manifests still treat signing paths and `jwt-signing-keys` mounts as shared workload configuration rather than enforcing Account as the sole private-material consumer, and the classpath fallback remains permitted when the configured JWKS file is absent. The runtime also retains the legacy creator-share percentage setting and provider-mutating code paths; they are unsupported implementation drift, not an accepted fee policy or product capability. These target-state requirements are not proof of current startup, custody, mount enforcement, or creator-commerce disablement; runtime, preflight, and manifest alignment is outside this documentation slice. diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index cd41e4b505..c2436f53a7 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -350,6 +350,8 @@ Account owns the sole supported v1 Stripe integration for FireMUD hosting-plan b This service sends verification and password reset emails using a configured SMTP provider. Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when a known-account post-commit SMTP send throws; those exceptions are caught and logged, while unknown requests create no token and schedule no email. **Current gap:** these sends still run synchronously after commit, so SMTP latency remains a timing oracle; durable asynchronous delivery is absent. Focused service tests prove exception containment, not timing resistance, HTTP-level timing parity, or durable delivery, so this is not full account-enumeration resistance. Public email-verification initiation no longer accepts a numeric account selector, while the internal gRPC method remains account-ID based. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). +Email verification uses the token association only to locate the Account, then locks the current complete Account row before claiming the exact original token. The conditional SQL consumption matches token row ID, opaque token, Account owner and original expiry, requiring expiry strictly after the captured process-local time. The claim and Account/source update share the writable owner transaction; losing, changed or expired claims cannot mutate Account state, and a failed source update rolls the claim back. Current password, role, email, login modes and UUID provenance come from that locked owner rather than the earlier partial token join. This preserves the existing local timestamp basis described above; it adds no cross-node timezone or retained-row migration claim. Focused implementation and proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-email-verification-and-deferred-currency-containment). + The configured default verification URL is a `GET /auth/verify-email` link while Account exposes verification as `POST /auth/verify-email`; the default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). The shipped defaults therefore do not route users to the canonical POST APIs ([Account API Contracts](./api-contracts.md#rest-apis)); deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live. ## Original StartSession Source-Protection Storage diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index f64797775a..3811ee1653 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -5,7 +5,7 @@ This document defines Entity Management’s runtime model, persistence ownership ## Implementation Status - Ordinary Account ownership uses the existing `characters.account_uuid` carrier; V1024 permits fresh ordinary rows without fabricated numeric source evidence and adds an ordinary UUID roster index. It leaves retained numeric/unresolved rows unchanged and does not promote canonical actor provenance. Representation and admission consequences belong to [API Contracts](./api-contracts.md#ordinary-account-ownership); implementation/proof status belongs to the [Entity tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#ordinary-account-uuid-ownership). -- Explicit local demo seeding authenticates the actual demo credentials through the normal Account mTLS `Authenticate` API and takes its canonical UUID response. It fails on unavailable identity or a retained demo character with missing/different UUID ownership, without repairing ownership by name or numeric row. The mTLS Compose profile starts Entity after Account health. This fixture operation grants no production registration, creation or admission authority. +- Explicit local demo seeding authenticates the actual demo credentials through the normal Account mTLS `Authenticate` API and takes its canonical UUID response. Account separately enables its narrowly gated [local credential fixture](../account-service/api-contracts.md#legacy-credential-rpc-and-local-demo-fixture); Entity seed enablement alone grants no receiving authority, OTP access or general credential permission. It fails on unavailable identity or a retained demo character with missing/different UUID ownership, without repairing ownership by name or numeric row. The mTLS Compose profile starts Entity after Account health. This fixture operation grants no production registration, creation or admission authority. - The current crafting REST adapter is runtime-reachable legacy implementation drift, not a supported or advertised boundary: the crafting paths and schemas are omitted from the ping-only authoritative OpenAPI, whose root `security: []` applies only to the health contract, so the adapter remains unsupported/nonconformant. The deployed interceptor requires any `AUTHENTICATED` bearer because this non-public path is not in the public-route list, but neither layer provides tenant binding; there is no controller `SessionContext` tenant guard. `CraftingServiceImpl` trusts the DTO's `tenantId`, `resultItemId`, and ingredient item IDs; `CraftingRecipeRepository.findWithIngredientsById` and the update branch use recipe ID alone, while ingredient loading also uses recipe ID alone. The tenant-qualified list methods first select IDs but then re-enter that unqualified lookup, so they are not evidence of an end-to-end tenant predicate. Existing crafting tests do not establish caller-tenant authorization, cross-tenant recipe isolation, or same-tenant result/ingredient ownership. - World owns guarded, manually composed initial `character_location` storage and its unregistered placement/read boundary. General movement, occupancy and NPC location remain unqualified; `room_instance` is topology, and a Game Session room binding is not World location authority. Entity Management must not add competing location persistence or treat a cache/projection as authoritative. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 01d708d775..420a4e383f 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -11,5 +11,5 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): Java filesystem read-only checks can miss same-device bind mounts. - A proposed `Files.getFileStore(path).isReadOnly()` guard was rejected before implementation: OpenJDK 21 discovers Linux boundaries using device changes and can attribute a bind mount to an ancestor with different read-only state. Exact current-process mountinfo, visible ancestry and pre/post comparison now preserve the readers’ owner/AtomicWriter guards; twelve physical mount cases pass. Next: qualify actual kubelet projection provenance at the existing held deployment boundary; local read-only evidence does not establish it. See [Game Session projection compatibility](../architecture/microservices/game-session-service/operations.md#protected-readiness-projection-compatibility). -- `2026-11-01` (Pacific/Auckland): Review selection held without naming its failed source. - - Both initial #3365 channel selections returned only `source_unavailable`, without a linked review operation or actionable diagnostic, while an exact-head source refresh completed and verified the same open, ready comparison. Provider execution was not established. The original selection/source receipts were sent to FireController Worker; normal implementation continues while that owner explains the failed source and supported recovery. Next: retain the owner response and update this entry with the verified cause and outcome. +- `2026-11-01` (Pacific/Auckland): API helper inputs and reply-file shape required local recovery. + - A read-only helper correctly refused its supplied external proof directory. Root copied and hash-verified the authorized inputs inside the worktree, without changing permissions, then resumed it. The reply command help omitted the required JSON array-of-string-arrays shape, so Root read its validator to construct the response. Next: add a concise help example in the owning API wrapper; this was reported to Overseer and is not a repository runtime blocker. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 27d8786e2c..1fe7dd5e73 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -636,6 +636,16 @@ Gateway owns the downstream `/ws/game/**` socket and a stable edge transport ses Shared coordination state carries reconnect/connect-context tracking, disconnect deduplication, gameplay-identity screen-buffer access, and bounded takeover information, while the in-process socket remains local. These stores do not produce authenticated first-party ingress. Shipped close-metadata proof covers missing or unattributed metadata on a public WebSocket emitting close `1011`/`internal_error`, and missing or invalid top-level metadata on an established authenticated TCP Proxy bridge rendering `DISCONNECT backend_unavailable ...`; it does not establish a successful first-party handshake, command/byte replay, the broader handler taxonomy, or the complete continuity contract. Remaining gaps are tracked in [TCP Proxy Operations](../../architecture/microservices/tcp-proxy-service/operations.md#implementation-status); duplicate and missing disconnect hints remain separately metered. +### Account email verification and deferred currency containment + +Local receiving work for #2848 prepares the [Account-owned email confirmation boundary](../../architecture/microservices/account-service/runtime-and-data.md#email-and-notification-design): an exact still-valid token claim and a fresh locked Account/source update share one transaction. It preserves current UUID and source-baseline guards and the stronger password-reset owner. The deferred `GetBalance`, `AddCurrency` and `SpendCurrency` RPCs now refuse before balance/service access, in line with the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis). R1416 passes eight focused unit cases and six actual PostgreSQL/Spring cases, with zero failures, errors or skips, plus selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Account packaging. The database cases cover single-use races, strict expiry, exact-token changes, owner/source rollback and preservation of a separately committed current Account update. Its missing-baseline fixture is a synthetic retained-style row, not historical migration proof. Fresh source-built runtime qualification remains pending. The remaining #2848 JOIN reconciliation, receipt and caller-proof obligations are separate and incomplete. This correction changes no JOIN expiry policy, activates no unsupported commerce and makes no complete Account recovery claim. + +R1418 additionally contains the legacy account-targeted `ExportTenantData` gRPC before selector parsing or owner reads; five focused gRPC/REST cases pass, with the separate REST/service authorization retained. The local Helm namespace render and development-certificate retention contracts pass, together with scoped ShellCheck and documentation checks. New credential receivers use exact Game Session certificate identity for OTP and the separately gated [Account-local Entity demo fixture](../../architecture/microservices/account-service/api-contracts.md#legacy-credential-rpc-and-local-demo-fixture) for Authenticate only. The first credential aggregate fails a missing test assertion import before test execution. Its corrected source passes 162 fresh Account cases, including eleven physical loopback-mTLS cases with a mocked credential owner; six unchanged Entity demo cases are up to date, not fresh executions. Subsequent main/test analysis recoveries pass after removing an unnecessary constructor suppression and retaining the channel shutdown return value; the eleven physical cases pass again without failures, errors or skips. These are separate scoped results across retained failed aggregates, not one complete Account suite or genuine credential verification. Fresh source-built held smoke remains pending. + +The same local containment suspends the unused `ExportAccount`, caller-asserted `LinkExternalAccount` and Account-ID `RequestEmailVerification` gRPC adapters before request parsing or owner access. Target export/link capabilities and an authorized internal verification-initiation caller remain incomplete. Separately authorized REST/service exports, neutral email-based initiation and the stronger token-based reset/verification owners remain. The combined current gate passes all 172 selected cases (163 Account unit/loopback cases, including eleven physical mTLS and six actual-profile HTTP wiring cases, plus nine actual PostgreSQL/Spring cases) with zero failures, errors or skips, selected main/test/integration static analysis, full formatting, fresh packaging and documentation checks. The three public-v1 JOIN cases prove actual commit followed by lost acknowledgement/readback, rollback followed by same-original continuation, and unchanged retained committed evidence after scope expiry. Controlled routing/caller inputs and injected failures establish no deployed RPC recovery or production authority. Public POST verification is selected by actual base/prod YAML; GET supplies no verification route or bypass. The email-link/browser handoff remains outside this local API proof. + +Current writer inspection also narrows the retained JOIN recovery gap: the public owner commits membership, transition audit and its terminal together after a separate durable intent. Unknown acknowledgement can leave either that intent without membership effects or a complete terminal; it does not establish the donor's manufactured positive-PENDING state. A lost committed result may remain unobservable after scope expiry, changed replay policy or lost caller binding. Same-original retry and this later outcome-observation limitation require distinct proof; the existing unknown-recovery and lawful-release holds remain. The proposed audit projection-version marker likewise has no implemented Logging receipt/projection producer here and must not be inferred from receiver IDs, payload replay or stamped test rows. No historical producer provenance, new receiver, recovery RPC or release authority is supplied. + ### Fail-Closed Boundary Convergence The auth/session/routing guardrail family is complete at its current bounded seams and is now a standing regression boundary, not a claim that every future ingress path has been audited. Shared helpers and direct adopters cover: diff --git a/dev-tools/README.md b/dev-tools/README.md index 1c5800aeb0..ac578f83ba 100644 --- a/dev-tools/README.md +++ b/dev-tools/README.md @@ -49,6 +49,8 @@ FireController is maintained outside this repository. Use the `firecontroller-us - `smoke/` – shared smoke defaults and the run-owned Compose claim/capability helper. - `seed/` – local and test data seeding helpers. - `tests/` – contract tests for repo-owned tooling. +- `tests/account-workload-namespace-contract.sh` – offline Helm-render contract for Account's Kubernetes workload namespace binding and reserved environment variable. +- `tests/dev-certs-retention-contract.sh` – validates retained development certificate bundles and proves refusal/preservation for incomplete material and linked paths. - `validation/` – repo policy and static validation scripts used by Gradle and CI. The documentation lock is sourced from the unpinned direct roots in `config/docs/requirements.in` and generated into `config/docs/requirements.txt` with the repository Python version and `pip-compile --allow-unsafe --generate-hashes --index-url=https://pypi.org/simple --output-file=config/docs/requirements.txt config/docs/requirements.in`. The existing lock seeds compilation and preserves satisfying package pins unless you explicitly request an upgrade. When the installed pip-tools version mis-serializes its default index options into an unsupported header, set `CUSTOM_COMPILE_COMMAND` to that exact command so the generated header remains parseable. Keep the source roots and lock hashes in sync; do not edit lock hashes manually. diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index 9a5b79dd34..e473f1046a 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -6,10 +6,11 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map -- `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target is provided. -- `dev-tools/certs/generate-dev-certs.sh --workload` signs local development or test-only gRPC workload leaves for the five publication services, Account, Game Session, and Social Groups with the exact SPIFFE URI and service DNS SANs. The Account, Game Session, and Entity Management leaves support the canonical local Compose gameplay proof, while the remaining local Compose services may use the shared development leaf. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. +- `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target or `CERT_DIR` is provided. A complete retained bundle is validated for certificate/key/CA agreement and reused without changing bytes or permissions. Incomplete or invalid retained material fails closed; preserve it and select a fresh dedicated directory for replacement material. All managed paths and their directory ancestors are checked before writes; symlinks, nonregular files, and hardlinked files are refused. Generation changes only its named outputs, leaving unrelated entries untouched. +- `dev-tools/certs/generate-dev-certs.sh --workload` signs local development or test-only gRPC workload leaves for the five publication services, Account, Game Session, and Social Groups with the exact SPIFFE URI and service DNS SANs. This mode supports all eleven Java application workload identities and requires fresh output paths; callers stage replacement leaves before installing them. Ordinary local development uses the dedicated per-workload helper described below; run-owned smoke uses the qualified fixture described below. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. - Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume eight cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. +- `dev-tools/certs/ensure-local-compose-mtls.sh` owns ordinary local development certificates for all eleven application workloads. See [ordinary local Compose setup and retained-certificate recovery](../../docker/README.md#local-compose-mtls-certificate-recovery); this authority remains separate from run-owned smoke fixtures. - `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. -- `dev-tools/certs/ensure-dev-certs.sh --compose-mtls ` creates the dedicated canonical smoke fixture beneath the active run-owned Compose state directory. The authority and CA private key remain in a host-only mode-0700 directory; each of the eleven Java application containers receives a read-only `/app/certs` mount containing only that service's leaf key, certificate, and public CA certificate. Account, Game Session, Entity Management, and World Management receive distinct `dev`-namespace SPIFFE leaves; World Management's leaf supports its authenticated Game Session owner-read path for the initial admission bind. This is local Compose wiring only; hosted deployments continue to use their separate certificate issuer. The remaining services use the shared local development leaf. The fixture is intentionally retained while its Compose project may be restarted and should be removed only after that exact project is torn down. -- The three canonical runtime-proof entrypoints layer `docker/docker-compose.grpc-mtls.override.yml` last. Ordinary `docker/docker-compose.override.yml` remains the plaintext local debugging profile. Hosted certificate provisioning is separate: hosted runtime namespaces receive cert-manager-issued standalone workload leaves and never mount the local CA private key. -- `dev-tools/certs/clean-dev-certs.sh` removes generated certificate files from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. +- `dev-tools/certs/ensure-dev-certs.sh --compose-mtls ` creates the dedicated canonical smoke fixture beneath the active run-owned Compose state directory. The authority and CA private key remain in a host-only mode-0700 directory; each of the eleven Java application containers receives a read-only `/app/certs` mount containing only that service's leaf key, certificate, and public CA certificate. Account, Game Session, Entity Management, World Management, and Game Design receive distinct `dev`-namespace SPIFFE leaves; World Management's leaf supports its authenticated Game Session owner-read path for the initial admission bind. This is local Compose wiring only; hosted deployments continue to use their separate certificate issuer. The remaining services use the shared local development leaf. The fixture is intentionally retained while its Compose project may be restarted and should be removed only after that exact project is torn down. +- The three canonical runtime-proof entrypoints layer `docker/docker-compose.grpc-mtls.override.yml` last. Ordinary local development layers `docker/docker-compose.local-mtls.override.yml` over its base local settings; see the [Docker guide](../../docker/README.md). Hosted certificate provisioning is separate: hosted runtime namespaces receive cert-manager-issued standalone workload leaves and never mount the local CA private key. +- `dev-tools/certs/clean-dev-certs.sh` removes only recognized generated regular files without hardlinks from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. It refuses a symlinked directory or ancestor, never recurses, and reports preserved entries, including foreign files, directories, and symlinks. Symlink targets are untouched. diff --git a/dev-tools/certs/clean-dev-certs.sh b/dev-tools/certs/clean-dev-certs.sh index 3139c39eb0..66833c4679 100644 --- a/dev-tools/certs/clean-dev-certs.sh +++ b/dev-tools/certs/clean-dev-certs.sh @@ -12,6 +12,18 @@ else CERT_DIR="${CERT_DIR:-$SCRIPT_DIR}" fi +directory_path="$CERT_DIR" +[[ "$directory_path" == /* ]] || directory_path="$PWD/$directory_path" +while [[ "$directory_path" != / && "$directory_path" == */ ]]; do directory_path="${directory_path%/}"; done +while :; do + if [[ -L "$directory_path" || ( -e "$directory_path" && ! -d "$directory_path" ) ]]; then + echo "Certificate cleanup refuses linked or non-directory paths: $directory_path" >&2 + exit 1 + fi + [[ "$directory_path" != / ]] || break + directory_path="$(dirname -- "$directory_path")" +done + if [ ! -d "$CERT_DIR" ]; then echo "No certificate directory at $CERT_DIR" exit 0 @@ -34,8 +46,8 @@ generated_files=( removed_any=false for filename in "${generated_files[@]}"; do - if [ -e "$CERT_DIR/$filename" ]; then - rm -f "$CERT_DIR/$filename" + if [[ -f "$CERT_DIR/$filename" && ! -L "$CERT_DIR/$filename" && "$(stat -c %h -- "$CERT_DIR/$filename")" == 1 ]]; then + rm -f -- "$CERT_DIR/$filename" removed_any=true fi done @@ -45,3 +57,8 @@ if [ "$removed_any" = true ]; then else echo "No generated certificates found in $CERT_DIR" fi + +# Never recurse: scripts, foreign files, directories and links belong to callers. +while IFS= read -r -d '' entry; do + echo "Preserved certificate-directory entry: $entry" +done < <(find "$CERT_DIR" -mindepth 1 -maxdepth 1 -print0) diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 4da960bbc7..dd5d1a4223 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -2,7 +2,7 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -CERT_DIR="${1:-$SCRIPT_DIR}" +CERT_DIR="${1:-${CERT_DIR:-$SCRIPT_DIR}}" GENERATOR="$SCRIPT_DIR/generate-dev-certs.sh" COMPOSE_MTLS_STAGE_ROOT="" COMPOSE_MTLS_STAGE_DIR="" @@ -246,28 +246,5 @@ if [[ "${1:-}" == "--compose-mtls" ]]; then exit $? fi -required_files=( - "$CERT_DIR/ca.crt" - "$CERT_DIR/client.crt" - "$CERT_DIR/client.key" - "$CERT_DIR/dev-ca.pem" - "$CERT_DIR/dev-cert.pem" - "$CERT_DIR/dev-key.pem" - "$CERT_DIR/server.crt" - "$CERT_DIR/server.key" -) - -missing=0 -for file in "${required_files[@]}"; do - if [[ ! -f "$file" ]]; then - missing=1 - break - fi -done - -if [[ "$missing" == "0" ]]; then - echo "Development certificates already exist in $CERT_DIR" - exit 0 -fi - +# The generator owns complete-bundle validation and read-only retained reuse. "$GENERATOR" "$CERT_DIR" diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index 99fef4c51a..8020e2f1f1 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -3,6 +3,37 @@ set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +# Check lexical ancestors before mkdir/OpenSSL can follow a retained link. +require_safe_directory_path() { + local path="$1" + [[ "$path" == /* ]] || path="$PWD/$path" + while [[ "$path" != / && "$path" == */ ]]; do path="${path%/}"; done + while :; do + if [[ -L "$path" || ( -e "$path" && ! -d "$path" ) ]]; then + echo "Certificate directory and ancestors must be real directories: $path" >&2 + return 1 + fi + [[ "$path" != / ]] || break + path="$(dirname -- "$path")" + done +} + +require_safe_file_path() { + local path="$1" + require_safe_directory_path "$(dirname -- "$path")" || return 1 + if [[ -L "$path" || ( -e "$path" && ( ! -f "$path" || "$(stat -c %h -- "$path")" != 1 ) ) ]]; then + echo "Certificate paths must be regular files without symlinks or hardlinks: $path" >&2 + return 1 + fi +} + +certificate_matches_key() { + local cert_public key_public + cert_public="$(openssl x509 -in "$1" -pubkey -noout | openssl pkey -pubin -outform DER | sha256sum)" || return 1 + key_public="$(openssl pkey -in "$2" -passin pass: -pubout -outform DER | sha256sum)" || return 1 + [[ "$cert_public" == "$key_public" ]] +} + if [[ "${1:-}" == "--workload" ]]; then umask 077 if [[ $# -ne 7 ]]; then @@ -16,6 +47,20 @@ if [[ "${1:-}" == "--workload" ]]; then output_key="$5" runtime_namespace="$6" workload="$7" + # Preflight every input/output before creating directories or writing a key. + for managed_file in "$ca_cert" "$ca_key" "$output_cert" "$output_key"; do + require_safe_file_path "$managed_file" + done + for output_file in "$output_cert" "$output_key"; do + if [[ -e "$output_file" ]]; then + echo "Refusing to overwrite retained workload output: $output_file" >&2 + exit 1 + fi + done + certificate_matches_key "$ca_cert" "$ca_key" || { + echo "Invalid workload certificate authority or mismatched key." >&2 + exit 1 + } for required_file in "$ca_cert" "$ca_key"; do [[ -f "$required_file" ]] || { echo "missing certificate authority file: $required_file" >&2 @@ -90,7 +135,44 @@ else CERT_DIR="${CERT_DIR:-$SCRIPT_DIR}" fi -if [ -f "$CERT_DIR/dev-cert.pem" ] && [ -f "$CERT_DIR/dev-key.pem" ] && [ -f "$CERT_DIR/dev-ca.pem" ]; then +required_files=(ca.crt ca.key server.crt server.key client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem) +managed_files=("${required_files[@]}" ca.srl server.csr dev-cert.cnf) +require_safe_directory_path "$CERT_DIR" +retained=0 +for filename in "${managed_files[@]}"; do + require_safe_file_path "$CERT_DIR/$filename" + if [[ -e "$CERT_DIR/$filename" ]]; then + retained=1 + fi +done + +if ((retained)); then + for filename in "${required_files[@]}"; do + if [[ ! -f "$CERT_DIR/$filename" ]]; then + echo "Incomplete retained development certificate bundle; refusing to replace material: $CERT_DIR" >&2 + exit 1 + fi + done + # Validate without changing retained bytes, modes, or directory permissions. + valid=1 + certificate_matches_key "$CERT_DIR/ca.crt" "$CERT_DIR/ca.key" || valid=0 + openssl verify -check_ss_sig -CAfile "$CERT_DIR/ca.crt" "$CERT_DIR/ca.crt" >/dev/null 2>&1 || valid=0 + cmp -s "$CERT_DIR/ca.crt" "$CERT_DIR/dev-ca.pem" || valid=0 + for name in server client dev; do + if [[ "$name" == dev ]]; then + certificate="$CERT_DIR/dev-cert.pem" + private_key="$CERT_DIR/dev-key.pem" + else + certificate="$CERT_DIR/$name.crt" + private_key="$CERT_DIR/$name.key" + fi + certificate_matches_key "$certificate" "$private_key" || valid=0 + openssl verify -CAfile "$CERT_DIR/ca.crt" "$certificate" >/dev/null 2>&1 || valid=0 + done + if (( ! valid )); then + echo "Invalid retained development certificate bundle; refusing to replace material: $CERT_DIR" >&2 + exit 1 + fi echo "Dev certificates already exist in $CERT_DIR" exit 0 fi @@ -151,13 +233,15 @@ cp "$CERT_DIR/ca.crt" "$CERT_DIR/dev-ca.pem" cp "$CERT_DIR/client.crt" "$CERT_DIR/dev-cert.pem" cp "$CERT_DIR/client.key" "$CERT_DIR/dev-key.pem" -rm -f "$CERT_DIR"/*.csr "$CERT_DIR"/*.srl +rm -f -- "$CERT_DIR/server.csr" "$CERT_DIR/ca.srl" rm -f "$CERT_DIR/dev-cert.cnf" # Containers run as a non-root application user in CI and local Docker. # Make the generated development certificates world-readable so bind mounts # remain readable inside the container regardless of host UID/GID. chmod 755 "$CERT_DIR" -chmod 644 "$CERT_DIR"/*.crt "$CERT_DIR"/*.key "$CERT_DIR"/*.pem +for filename in "${required_files[@]}"; do + chmod 644 "$CERT_DIR/$filename" +done echo "Certificates generated in $(cd "$CERT_DIR" && pwd)" diff --git a/dev-tools/tests/account-workload-namespace-contract.sh b/dev-tools/tests/account-workload-namespace-contract.sh new file mode 100644 index 0000000000..e4348c5a1c --- /dev/null +++ b/dev-tools/tests/account-workload-namespace-contract.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +CHART_DIR="$ROOT_DIR/k8s/helm/account-service" +TMP_DIR="$(mktemp -d)" +trap 'rm -rf "$TMP_DIR"' EXIT + +if ! command -v helm >/dev/null 2>&1; then + echo "helm is required to render the Account workload namespace contract" >&2 + exit 1 +fi + +render_and_check() { + local namespace="$1" + local rendered="$2" + local check_extra_env="$3" + shift 3 + + helm template "account-contract-$namespace" "$CHART_DIR" \ + --namespace "$namespace" \ + "$@" \ + >"$rendered" + + python3 - "$rendered" "$namespace" "$check_extra_env" <<'PY' +import pathlib +import sys + +import yaml + +rendered_path = pathlib.Path(sys.argv[1]) +namespace = sys.argv[2] +check_extra_env = sys.argv[3] == "true" +documents = [ + document + for document in yaml.safe_load_all(rendered_path.read_text(encoding="utf-8")) + if isinstance(document, dict) +] +deployment = next( + ( + document + for document in documents + if document.get("kind") == "Deployment" + and document.get("metadata", {}).get("name") == "account-service" + ), + None, +) +if deployment is None: + raise SystemExit(f"render in namespace {namespace!r} omitted Account Deployment") + +containers = deployment.get("spec", {}).get("template", {}).get("spec", {}).get("containers", []) +account_container = next( + (container for container in containers if container.get("name") == "account-service"), + None, +) +if account_container is None: + raise SystemExit(f"render in namespace {namespace!r} omitted Account container") + +env = account_container.get("env", []) +namespace_entries = [ + entry + for entry in env + if isinstance(entry, dict) + and entry.get("name") == "FIREMUD_GRPC_WORKLOAD_NAMESPACE" +] +expected = { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, +} +if namespace_entries != [expected]: + raise SystemExit( + f"render in namespace {namespace!r} must derive exactly one workload namespace " + f"from metadata.namespace, found {namespace_entries!r}" + ) + +if check_extra_env: + sentinel = [entry for entry in env if entry.get("name") == "ACCOUNT_CONTRACT_SENTINEL"] + if sentinel != [{"name": "ACCOUNT_CONTRACT_SENTINEL", "value": "preserved"}]: + raise SystemExit(f"ordinary extraEnv value was not preserved: {sentinel!r}") +PY +} + +render_and_check default "$TMP_DIR/default.yaml" false +render_and_check account-contract-custom "$TMP_DIR/custom.yaml" true \ + --set-string extraEnv.ACCOUNT_CONTRACT_SENTINEL=preserved + +if helm template account-contract-collision "$CHART_DIR" \ + --namespace account-contract-collision \ + --set-string extraEnv.FIREMUD_GRPC_WORKLOAD_NAMESPACE=override \ + >"$TMP_DIR/collision.out" 2>"$TMP_DIR/collision.err"; then + echo "Account chart accepted extraEnv collision with FIREMUD_GRPC_WORKLOAD_NAMESPACE" >&2 + exit 1 +fi +if ! grep -Fq \ + "extraEnv must not set FIREMUD_GRPC_WORKLOAD_NAMESPACE; Account derives it from the pod namespace" \ + "$TMP_DIR/collision.err"; then + echo "Account chart collision failure omitted its explicit reason" >&2 + cat "$TMP_DIR/collision.err" >&2 + exit 1 +fi + +echo "Account workload namespace Helm contract passed" diff --git a/dev-tools/tests/dev-certs-retention-contract.sh b/dev-tools/tests/dev-certs-retention-contract.sh new file mode 100644 index 0000000000..5192057b22 --- /dev/null +++ b/dev-tools/tests/dev-certs-retention-contract.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +GENERATOR="$REPO_ROOT/dev-tools/certs/generate-dev-certs.sh" +ENSURE="$REPO_ROOT/dev-tools/certs/ensure-dev-certs.sh" +CLEAN="$REPO_ROOT/dev-tools/certs/clean-dev-certs.sh" +TEST_ROOT="$(mktemp -d)" +trap 'rm -rf -- "$TEST_ROOT"' EXIT + +# Only inspect this test's own fixture; record links without following targets. +snapshot() { + python3 - "$1" <<'PY' +import hashlib +import os +import pathlib +import stat +import sys + +root = pathlib.Path(sys.argv[1]) +for directory, subdirs, files in os.walk(root, followlinks=False): + for path in [pathlib.Path(directory)] + sorted(pathlib.Path(directory) / name for name in subdirs + files): + info = path.lstat() + value = "" + if stat.S_ISLNK(info.st_mode): + value = os.readlink(path) + elif stat.S_ISREG(info.st_mode): + value = hashlib.sha256(path.read_bytes()).hexdigest() + print(path.relative_to(root), info.st_mode, info.st_nlink, value) +PY +} + +expect_unchanged_failure() { + local fixture="$1" before after + shift + before="$(snapshot "$fixture")" + if "$@" >"$TEST_ROOT/failure-output" 2>&1; then + echo "Expected certificate operation to refuse retained fixture: $*" >&2 + exit 1 + fi + after="$(snapshot "$fixture")" + [[ "$before" == "$after" ]] +} + +fresh="$TEST_ROOT/fresh" +mkdir "$fresh" +printf 'foreign material\n' >"$fresh/foreign.pem" +chmod 600 "$fresh/foreign.pem" +bash "$GENERATOR" "$fresh" >"$TEST_ROOT/generation-output" 2>&1 +[[ "$(stat -c %a "$fresh/foreign.pem")" == 600 ]] +[[ "$(cat "$fresh/foreign.pem")" == 'foreign material' ]] +for name in ca.crt ca.key server.crt server.key client.crt client.key dev-ca.pem dev-cert.pem dev-key.pem; do + [[ -s "$fresh/$name" ]] + chmod 640 "$fresh/$name" +done +chmod 750 "$fresh" +before="$(snapshot "$fresh")" +bash "$GENERATOR" "$fresh" >/dev/null +bash "$ENSURE" "$fresh" >/dev/null +[[ "$before" == "$(snapshot "$fresh")" ]] + +partial="$TEST_ROOT/partial" +mkdir "$partial" +printf 'retained CA\n' >"$partial/ca.crt" +expect_unchanged_failure "$partial" bash "$GENERATOR" "$partial" +expect_unchanged_failure "$partial" bash "$ENSURE" "$partial" + +other="$TEST_ROOT/other" +bash "$GENERATOR" "$other" >"$TEST_ROOT/other-output" 2>&1 +for corruption in malformed key ca ca-key; do + fixture="$TEST_ROOT/$corruption" + cp -a -- "$fresh" "$fixture" + case "$corruption" in + malformed) printf 'invalid certificate\n' >"$fixture/client.crt" ;; + key) cp -- "$other/client.key" "$fixture/dev-key.pem" ;; + ca) cp -- "$other/ca.crt" "$fixture/ca.crt"; cp -- "$other/ca.key" "$fixture/ca.key"; cp -- "$other/dev-ca.pem" "$fixture/dev-ca.pem" ;; + ca-key) cp -- "$other/ca.key" "$fixture/ca.key" ;; + esac + expect_unchanged_failure "$fixture" bash "$GENERATOR" "$fixture" + expect_unchanged_failure "$fixture" bash "$ENSURE" "$fixture" +done + +links="$TEST_ROOT/links" +mkdir "$links" "$links/outside" "$links/partial" "$links/hard" "$links/nonregular" +printf 'outside retained material\n' >"$links/outside/material" +ln -s "$links/outside/material" "$links/partial/dev-key.pem" +ln "$links/outside/material" "$links/hard/ca.key" +mkdir "$links/nonregular/ca.crt" +ln -s "$links/outside" "$links/directory" +for target in "$links/partial" "$links/hard" "$links/nonregular" "$links/directory/" "$links/directory/new"; do + expect_unchanged_failure "$links" bash "$GENERATOR" "$target" + expect_unchanged_failure "$links" bash "$ENSURE" "$target" +done +# A link in an otherwise complete bundle is also refused without a mode change. +linked_complete="$TEST_ROOT/linked-complete" +cp -a -- "$fresh" "$linked_complete" +rm -- "$linked_complete/ca.key" +ln -s "$fresh/ca.key" "$linked_complete/ca.key" +expect_unchanged_failure "$linked_complete" bash "$ENSURE" "$linked_complete" + +workloads="$TEST_ROOT/workloads" +mkdir "$workloads" +printf 'retained output\n' >"$workloads/existing.crt" +ln -s "$links/outside/material" "$workloads/linked.key" +ln "$links/outside/material" "$workloads/hard.key" +for key in linked.key hard.key; do + expect_unchanged_failure "$workloads" bash "$GENERATOR" --workload \ + "$fresh/ca.crt" "$fresh/ca.key" "$workloads/new/client.crt" "$workloads/$key" dev world-management-service +done +expect_unchanged_failure "$workloads" bash "$GENERATOR" --workload \ + "$fresh/ca.crt" "$fresh/ca.key" "$workloads/existing.crt" "$workloads/new/client.key" dev world-management-service + +cleanup="$TEST_ROOT/cleanup" +cp -a -- "$fresh" "$cleanup" +rm -- "$cleanup/client.key" "$cleanup/server.key" +ln -s "$links/outside/material" "$cleanup/client.key" +ln "$links/outside/material" "$cleanup/server.key" +printf 'foreign certificate\n' >"$cleanup/foreign.crt" +mkdir "$cleanup/foreign-directory" +outside_before="$(snapshot "$links/outside")" +bash "$CLEAN" "$cleanup" >"$TEST_ROOT/cleanup-output" +[[ ! -e "$cleanup/ca.crt" && ! -e "$cleanup/dev-key.pem" ]] +[[ -L "$cleanup/client.key" && -f "$cleanup/server.key" && -d "$cleanup/foreign-directory" ]] +[[ "$(cat "$cleanup/foreign.crt")" == 'foreign certificate' ]] +[[ "$(cat "$cleanup/foreign.pem")" == 'foreign material' ]] +[[ "$outside_before" == "$(snapshot "$links/outside")" ]] +for entry in client.key server.key foreign.crt foreign-directory; do + grep -Fq "Preserved certificate-directory entry: $cleanup/$entry" "$TEST_ROOT/cleanup-output" +done +for target in "$links/directory/" "$links/directory/new"; do + expect_unchanged_failure "$links" bash "$CLEAN" "$target" +done + +echo 'Development certificate retention contract passed.' diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 073c2b689e..7f94322a6a 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -64,6 +64,9 @@ services: SPRING_FLYWAY_TABLE: flyway_schema_history_account_service FIREMUD_DATABASE_ENABLED: "true" FIREMUD_SMOKE_SEED_DEMO_ACCOUNT_ENABLED: "true" + SPRING_PROFILES_ACTIVE: local-fixture + FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_ENABLED: "true" + FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_EMAIL: demo@example.com env_file: *service-env-file volumes: *service-vols restart: unless-stopped diff --git a/k8s/helm/account-service/templates/deployment.yaml b/k8s/helm/account-service/templates/deployment.yaml index bde01874a2..95f0d96d5b 100644 --- a/k8s/helm/account-service/templates/deployment.yaml +++ b/k8s/helm/account-service/templates/deployment.yaml @@ -23,10 +23,17 @@ spec: ports: - containerPort: 8080 env: + {{- if hasKey (default dict .Values.extraEnv) "FIREMUD_GRPC_WORKLOAD_NAMESPACE" }} + {{- fail "extraEnv must not set FIREMUD_GRPC_WORKLOAD_NAMESPACE; Account derives it from the pod namespace" }} + {{- end }} {{- range $key, $value := .Values.extraEnv }} - name: {{ $key }} value: "{{ $value }}" {{- end }} + - name: FIREMUD_GRPC_WORKLOAD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace readinessProbe: httpGet: path: {{ .Values.readinessProbe.path }} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java index acb2c576fb..cfa661c7e2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java @@ -10,6 +10,9 @@ import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationManager; @Repository @SuppressFBWarnings( @@ -67,6 +70,34 @@ public void deleteByAccountId(Long accountId) { .execute(); } + /** Claims only the exact original, still-valid token in the Account owner's transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public boolean consumeIfUnexpired(EmailVerificationToken token, LocalDateTime capturedNow) { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "Email verification requires an active writable owner transaction"); + } + if (token == null + || token.getId() == null + || token.getAccount() == null + || token.getAccount().getId() == null + || capturedNow == null) { + return false; + } + return dsl.deleteFrom(EMAIL_VERIFICATION_TOKEN) + .where( + EMAIL_VERIFICATION_TOKEN + .ID + .eq(token.getId()) + .and(EMAIL_VERIFICATION_TOKEN.TOKEN.eq(token.getToken())) + .and(EMAIL_VERIFICATION_TOKEN.ACCOUNT_ID.eq(token.getAccount().getId())) + .and(EMAIL_VERIFICATION_TOKEN.EXPIRES_AT.eq(token.getExpiresAt())) + .and(EMAIL_VERIFICATION_TOKEN.EXPIRES_AT.gt(capturedNow))) + .execute() + == 1; + } + /** Deletes at most {@code batchSize} expired rows in deterministic expiry/id order. */ public int deleteExpired(LocalDateTime capturedNow, int batchSize) { return JooqAccountRepositorySupport.deleteExpired( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 29d8c1bb0a..c1b3139473 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -61,6 +61,8 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.core.env.Profiles; import org.springframework.dao.DataAccessException; import org.springframework.grpc.server.service.GrpcService; import org.springframework.transaction.TransactionException; @@ -79,6 +81,8 @@ public class AccountGrpcService extends AccountServiceGrpc.AccountServiceImplBas private final AccountService accountService; private final MeterRegistry meterRegistry; private final String workloadNamespace; + private final boolean localDemoAuthenticationEnabled; + private final String localDemoEmail; public AccountGrpcService(PingService pingService, AccountService accountService) { this(pingService, accountService, null, null); @@ -89,6 +93,14 @@ public AccountGrpcService( this(pingService, accountService, meterRegistry, null); } + public AccountGrpcService( + PingService pingService, + AccountService accountService, + MeterRegistry meterRegistry, + String workloadNamespace) { + this(pingService, accountService, meterRegistry, workloadNamespace, null, false, ""); + } + @Autowired @SuppressFBWarnings( value = "EI_EXPOSE_REP2", @@ -97,11 +109,22 @@ public AccountGrpcService( PingService pingService, AccountService accountService, MeterRegistry meterRegistry, - @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace, + Environment environment, + @Value("${firemud.account.local-demo-authentication.enabled:false}") + boolean localDemoAuthenticationEnabled, + @Value("${firemud.account.local-demo-authentication.email:}") String localDemoEmail) { this.pingService = pingService; this.accountService = accountService; this.meterRegistry = meterRegistry; this.workloadNamespace = workloadNamespace; + this.localDemoAuthenticationEnabled = + localDemoAuthenticationEnabled + && environment != null + && environment.acceptsProfiles(Profiles.of("local-fixture")) + && !environment.acceptsProfiles(Profiles.of("prod")); + this.localDemoEmail = + this.localDemoAuthenticationEnabled ? EmailCanonicalization.normalize(localDemoEmail) : ""; } @Override @@ -217,6 +240,29 @@ private void requireGameSessionPeer() { "Verified Game Session workload identity is required", "game-session-service"); } + private void requireCredentialPeer(AuthenticateRequest request) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer != null + && peer.isService("game-session-service") + && peer.isInNamespace(workloadNamespace)) { + requireGameSessionPeer(); + return; + } + requireWorkloadPeer( + "Verified Game Session workload identity is required", "entity-management-service"); + if (!localDemoAuthenticationEnabled) { + throw new AdminAuthorizationException("Local demo authentication is unavailable"); + } + try { + if (localDemoEmail.equals(EmailCanonicalization.normalize(request.getEmail()))) { + return; + } + } catch (IllegalArgumentException ignored) { + // Invalid fixture identity does not authorize credential verification. + } + throw new AdminAuthorizationException("Configured local demo account identity is required"); + } + private void requireRuntimeEntitlementsPeer() { requireWorkloadPeer( "Verified Game Session or World Management workload identity is required", @@ -377,6 +423,7 @@ public void createAccount( public void authenticate( AuthenticateRequest request, StreamObserver responseObserver) { try { + requireCredentialPeer(request); net.firedevops.firemud.accountservice.dto.AuthenticationResult result = accountService.authenticateForGameplay(request.getEmail(), request.getPassword()); AuthenticateResponse response = @@ -386,6 +433,12 @@ public void authenticate( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + AuthenticateResponse.newBuilder() + .setError(appError("Authenticate", "PERMISSION_DENIED", ex.getMessage())) + .build()); + responseObserver.onCompleted(); } catch (InvalidRequestException ex) { AuthenticateResponse response = AuthenticateResponse.newBuilder() @@ -423,8 +476,14 @@ public void requestEmailLoginOtp( RequestEmailLoginOtpRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); accountService.requestEmailLoginOtp(requireEmail(request.getEmail())); responseObserver.onNext(RequestEmailLoginOtpResponse.newBuilder().setAccepted(true).build()); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + RequestEmailLoginOtpResponse.newBuilder() + .setError(appError("RequestEmailLoginOtp", "PERMISSION_DENIED", ex.getMessage())) + .build()); } catch (InvalidRequestException ex) { responseObserver.onNext( RequestEmailLoginOtpResponse.newBuilder() @@ -439,12 +498,18 @@ public void requestEmailLoginOtp( public void verifyEmailLoginOtp( VerifyEmailLoginOtpRequest request, StreamObserver responseObserver) { try { + requireGameSessionPeer(); var result = accountService.verifyEmailLoginOtp(request.getEmail(), request.getCode()); responseObserver.onNext( AuthenticateResponse.newBuilder() .setAuthToken(result.authToken()) .setAccountId(result.accountId()) .build()); + } catch (AdminAuthorizationException ex) { + responseObserver.onNext( + AuthenticateResponse.newBuilder() + .setError(appError("VerifyEmailLoginOtp", "PERMISSION_DENIED", ex.getMessage())) + .build()); } catch (InvalidRequestException ex) { responseObserver.onNext( AuthenticateResponse.newBuilder() @@ -936,97 +1001,30 @@ public void updateProfile( @Timed(value = "accountGrpc.exportAccount") public void exportAccount( ExportAccountRequest request, StreamObserver responseObserver) { - try { - var data = - accountService.exportAccountData( - resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setAccountJson(JsonMapper.builder().build().writeValueAsString(data.account())) - .setProfilesJson(JsonMapper.builder().build().writeValueAsString(data.profiles())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AccountUuidReadbackUnavailableException ex) { - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setError(accountUuidReadbackUnavailableError("ExportAccount")) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setError(appError("ExportAccount", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AuthenticationException ex) { - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setError(appError("ExportAccount", ex.getCode(), ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - ExportAccountResponse response = - ExportAccountResponse.newBuilder() - .setError(appError("ExportAccount", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + ExportAccountResponse.newBuilder() + .setError( + appError( + "ExportAccount", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @Timed(value = "accountGrpc.exportTenantData") public void exportTenantData( ExportTenantDataRequest request, StreamObserver responseObserver) { - try { - var data = - accountService.exportTenantData( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setTenantId(String.valueOf(data.tenantId())) - .setAccountJson(JsonMapper.builder().build().writeValueAsString(data.account())) - .setProfileJson( - data.profile() != null - ? JsonMapper.builder().build().writeValueAsString(data.profile()) - : "") - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AccountUuidReadbackUnavailableException ex) { - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setError(accountUuidReadbackUnavailableError("ExportTenantData")) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setError(appError("ExportTenantData", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AuthenticationException ex) { - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setError(appError("ExportTenantData", ex.getCode(), ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - ExportTenantDataResponse response = - ExportTenantDataResponse.newBuilder() - .setError(appError("ExportTenantData", "NOT_FOUND", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + ExportTenantDataResponse.newBuilder() + .setError( + appError( + "ExportTenantData", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @@ -1151,44 +1149,16 @@ public void linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest request, StreamObserver responseObserver) { - try { - accountService.linkExternalAccount( - new net.firedevops.firemud.accountservice.dto.LinkExternalAccountRequest( - requirePositiveRequestId(request.getTenantId(), "tenantId"), - resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId())), - request.getProvider(), - request.getExternalId())); - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AccountUuidReadbackUnavailableException ex) { - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(false) - .setError(accountUuidReadbackUnavailableError("LinkExternalAccount")) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(false) - .setError(appError("LinkExternalAccount", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(false) - .setError(appError("LinkExternalAccount", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "LinkExternalAccount", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override @@ -1197,40 +1167,16 @@ public void requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest request, StreamObserver responseObserver) { - try { - accountService.requestEmailVerification( - resolveAccountStorageIdForRpc(requireCanonicalAccountUuid(request.getAccountId()))); - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(true) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (AccountUuidReadbackUnavailableException ex) { - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(false) - .setError(accountUuidReadbackUnavailableError("RequestEmailVerification")) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (InvalidRequestException ex) { - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(false) - .setError(appError("RequestEmailVerification", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - var response = - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(false) - .setError(appError("RequestEmailVerification", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() + .setSuccess(false) + .setError( + appError( + "RequestEmailVerification", + "FAILED_PRECONDITION", + "No authorized internal caller is configured")) + .build()); + responseObserver.onCompleted(); } @Override diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index 4da20b561c..13fefe53f3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -3184,13 +3184,33 @@ public void verifyEmail(VerifyEmailRequest request) { emailVerificationTokenRepository .findByToken(request.token()) .orElseThrow(() -> new IllegalArgumentException("Invalid token")); - if (token.getExpiresAt().isBefore(java.time.LocalDateTime.now())) { + if (token.getId() == null + || token.getId() <= 0L + || token.getAccount() == null + || token.getAccount().getId() == null + || token.getAccount().getId() <= 0L + || token.getExpiresAt() == null + || !request.token().equals(token.getToken())) { + throw new IllegalArgumentException("Invalid token"); + } + // The token join supplies a locator, not the current full Account to mutate. + Long accountId = token.getAccount().getId(); + Account account = + accountRepository + .findByIdForUpdate(accountId) + .orElseThrow(() -> new IllegalArgumentException("Invalid token")); + if (!accountId.equals(account.getId())) { + throw new IllegalArgumentException("Invalid token"); + } + LocalDateTime capturedNow = LocalDateTime.now(); + if (!token.getExpiresAt().isAfter(capturedNow)) { throw new IllegalArgumentException("Token expired"); } - Account account = token.getAccount(); + if (!emailVerificationTokenRepository.consumeIfUnexpired(token, capturedNow)) { + throw new IllegalArgumentException("Invalid token"); + } account.setEmailVerified(true); accountRepository.save(account); - emailVerificationTokenRepository.delete(token); } @Override diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java index 1adc30f9a8..54c76c2bfb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java @@ -13,7 +13,7 @@ import net.firedevops.firemud.account.v1.VirtualCurrencyServiceGrpc; import net.firedevops.firemud.accountservice.service.VirtualCurrencyService; import net.firedevops.firemud.common.grpc.GrpcAppErrors; -import net.firedevops.firemud.common.security.RequestIdValidation; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -49,98 +49,33 @@ public VirtualCurrencyGrpcService( @Timed(value = "currencyGrpc.getBalance") public void getBalance( GetBalanceRequest request, StreamObserver responseObserver) { - try { - long balance = - currencyService.getBalance( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getCurrencyCode()); - GetBalanceResponse response = GetBalanceResponse.newBuilder().setBalance(balance).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - GetBalanceResponse response = - GetBalanceResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "GetBalance", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - GetBalanceResponse response = - GetBalanceResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "GetBalance", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + GetBalanceResponse.newBuilder().setError(unavailable("GetBalance")).build()); + responseObserver.onCompleted(); } @Override @Timed(value = "currencyGrpc.addCurrency") public void addCurrency( AddCurrencyRequest request, StreamObserver responseObserver) { - try { - long balance = - currencyService.addCurrency( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getCurrencyCode(), - request.getAmount()); - AddCurrencyResponse response = AddCurrencyResponse.newBuilder().setBalance(balance).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - AddCurrencyResponse response = - AddCurrencyResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "AddCurrency", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - AddCurrencyResponse response = - AddCurrencyResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "AddCurrency", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + AddCurrencyResponse.newBuilder().setError(unavailable("AddCurrency")).build()); + responseObserver.onCompleted(); } @Override @Timed(value = "currencyGrpc.spendCurrency") public void spendCurrency( SpendCurrencyRequest request, StreamObserver responseObserver) { - try { - long balance = - currencyService.spendCurrency( - RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), - RequestIdValidation.requirePositiveLong(request.getAccountId(), "accountId"), - request.getCurrencyCode(), - request.getAmount()); - SpendCurrencyResponse response = - SpendCurrencyResponse.newBuilder().setBalance(balance).build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (IllegalArgumentException ex) { - SpendCurrencyResponse response = - SpendCurrencyResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, logger, "SpendCurrency", "INVALID_ARGUMENT", ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } catch (Exception ex) { - SpendCurrencyResponse response = - SpendCurrencyResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "SpendCurrency", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } + responseObserver.onNext( + SpendCurrencyResponse.newBuilder().setError(unavailable("SpendCurrency")).build()); + responseObserver.onCompleted(); + } + + private ErrorDetail unavailable(String operation) { + String message = operation + " is unavailable"; + return meterRegistry == null + ? ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(message).build() + : GrpcAppErrors.error(meterRegistry, logger, operation, "FAILED_PRECONDITION", message); } } diff --git a/services/account-service/src/main/resources/application-prod.yml b/services/account-service/src/main/resources/application-prod.yml index 138a962cd0..07b28a5463 100644 --- a/services/account-service/src/main/resources/application-prod.yml +++ b/services/account-service/src/main/resources/application-prod.yml @@ -54,7 +54,7 @@ firemud: path-pattern: /auth/complete-password-reset - method: POST path-pattern: /auth/request-email-verification - - method: GET + - method: POST path-pattern: /auth/verify-email - method: POST path-pattern: /auth/recover-username diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 790568480b..99eadbdc10 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -42,6 +42,9 @@ firemud: ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} account: + local-demo-authentication: + enabled: ${FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_ENABLED:false} + email: ${FIREMUD_ACCOUNT_LOCAL_DEMO_AUTHENTICATION_EMAIL:} credentials: cleanup: batch-size: ${FIREMUD_ACCOUNT_CREDENTIAL_CLEANUP_BATCH_SIZE:100} @@ -86,7 +89,7 @@ firemud: path-pattern: /auth/complete-password-reset - method: POST path-pattern: /auth/request-email-verification - - method: GET + - method: POST path-pattern: /auth/verify-email - method: POST path-pattern: /auth/recover-username diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index 0cf8542d4b..e6ab3e3767 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -1,17 +1,35 @@ package net.firedevops.firemud.accountservice; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.LocalDateTime; import java.util.List; import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import net.firedevops.firemud.accountservice.client.EntityManagementClient; import net.firedevops.firemud.accountservice.client.GameSessionClient; import net.firedevops.firemud.accountservice.client.LoggingAdminClient; +import net.firedevops.firemud.accountservice.dto.CreateAccountRequest; +import net.firedevops.firemud.accountservice.dto.DirectTextCallerContext; +import net.firedevops.firemud.accountservice.dto.DirectTextJoinTarget; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest; +import net.firedevops.firemud.accountservice.dto.JoinPublicProductionResult; +import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; +import net.firedevops.firemud.accountservice.entity.AccountIdentityProvenance; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException; import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.exception.AuthenticationException; import net.firedevops.firemud.common.security.HttpAuthProperties; import net.firedevops.firemud.common.security.HttpAuthRoleRequirement; import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; @@ -32,6 +50,7 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -80,6 +99,14 @@ static void configure(DynamicPropertyRegistry registry) { @org.springframework.test.context.bean.override.mockito.MockitoSpyBean private net.firedevops.firemud.accountservice.repository.AccountRepository accountRepository; + @org.springframework.test.context.bean.override.mockito.MockitoSpyBean + private net.firedevops.firemud.accountservice.repository.EmailVerificationTokenRepository + emailVerificationTokenRepository; + + @org.springframework.test.context.bean.override.mockito.MockitoSpyBean + private net.firedevops.firemud.accountservice.repository.AccountJoinOperationRepository + joinOperationRepository; + @Autowired private org.springframework.transaction.PlatformTransactionManager transactionManager; @Autowired @@ -98,6 +125,592 @@ void pingEndpointReturnsPong() { assertThat(body).contains("pong"); } + @Test + void concurrentEmailVerificationClaimsTheExactTokenOnce() throws Exception { + var fixture = emailVerificationFixture(); + var ready = new CountDownLatch(2); + var start = new CountDownLatch(1); + var located = new CountDownLatch(2); + org.mockito.Mockito.doAnswer( + invocation -> { + var original = invocation.callRealMethod(); + located.countDown(); + if (!located.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Both verification attempts must read the token"); + } + return original; + }) + .when(emailVerificationTokenRepository) + .findByToken(fixture.token()); + var executor = Executors.newFixedThreadPool(2); + try { + Callable attempt = + () -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Email verification start was not released"); + } + try { + verifyEmail(fixture.token()); + return true; + } catch (IllegalArgumentException consumed) { + return false; + } + }; + var first = executor.submit(attempt); + var second = executor.submit(attempt); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + assertThat(first.get(30, TimeUnit.SECONDS)).isNotEqualTo(second.get(30, TimeUnit.SECONDS)); + } finally { + start.countDown(); + executor.shutdownNow(); + } + assertThat( + dsl.fetchValue("SELECT email_verified FROM accounts WHERE id = ?", fixture.accountId())) + .isEqualTo(true); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM email_verification_token WHERE token = ?", fixture.token())) + .isEqualTo(0L); + } + + @Test + void expiredAndExactlyExpiringEmailVerificationTokensCannotMutateAccount() { + for (boolean equality : List.of(false, true)) { + var fixture = emailVerificationFixture(); + var expiry = LocalDateTime.now().minusSeconds(1); + dsl.execute( + "UPDATE email_verification_token SET expires_at = ? WHERE token = ?", + expiry, + fixture.token()); + var before = emailVerificationState(fixture); + if (equality) { + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> { + accountRepository.findByIdForUpdate(fixture.accountId()).orElseThrow(); + var token = + emailVerificationTokenRepository.findByToken(fixture.token()).orElseThrow(); + assertThat( + emailVerificationTokenRepository.consumeIfUnexpired( + token, token.getExpiresAt())) + .isFalse(); + }); + } else { + assertThatThrownBy(() -> verifyEmail(fixture.token())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Token expired"); + } + assertThat(emailVerificationState(fixture)).isEqualTo(before); + } + } + + @Test + void changedOriginalEmailVerificationTokenCannotMutateAccount() { + for (String field : List.of("token", "expires_at", "account_id")) { + var fixture = emailVerificationFixture(); + var other = emailVerificationFixture(); + var before = emailVerificationState(fixture); + var changed = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> { + var original = invocation.callRealMethod(); + if (changed.compareAndSet(false, true)) { + switch (field) { + case "token" -> + dsl.execute( + "UPDATE email_verification_token SET token = ? WHERE token = ?", + fixture.token() + "-changed", + fixture.token()); + case "expires_at" -> + dsl.execute( + "UPDATE email_verification_token SET expires_at = expires_at + INTERVAL '1 second' WHERE token = ?", + fixture.token()); + case "account_id" -> + dsl.execute( + "UPDATE email_verification_token SET account_id = ? WHERE token = ?", + other.accountId(), + fixture.token()); + default -> throw new AssertionError(field); + } + } + return original; + }) + .when(emailVerificationTokenRepository) + .findByToken(fixture.token()); + + assertThatThrownBy(() -> verifyEmail(fixture.token())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid token"); + + // The injected change shares the owner transaction and rolls back with the rejected claim. + assertThat(emailVerificationState(fixture)).isEqualTo(before); + assertThat( + dsl.fetchValue("SELECT email_verified FROM accounts WHERE id = ?", other.accountId())) + .isEqualTo(false); + } + } + + @Test + void emailVerificationRollbackRestoresTokenAccountAndSourceEvidence() { + var fixture = emailVerificationFixture(); + var before = emailVerificationState(fixture); + var transaction = new TransactionTemplate(transactionManager); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> { + verifyEmail(fixture.token()); + throw new IllegalStateException("failure after verification source update"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("failure after verification source update"); + assertThat(emailVerificationState(fixture)).isEqualTo(before); + verifyEmail(fixture.token()); + assertThat( + dsl.fetchValue("SELECT email_verified FROM accounts WHERE id = ?", fixture.accountId())) + .isEqualTo(true); + } + + @Test + void emailVerificationWithoutOwnerBaselineRollsBackClaimWithoutEnrollingRetainedAccount() { + String suffix = UUID.randomUUID().toString(); + // A raw retained-style row deliberately lacks repository-owned V40 source initialization. + long accountId = + java.util.Objects.requireNonNull( + dsl.resultQuery( + "INSERT INTO accounts (username, email, password_hash) VALUES (?, ?, ?) RETURNING id", + "retained-" + suffix.substring(0, 8), + suffix + "@example.com", + "retained-password") + .fetchOne(0, Long.class)); + var fixture = insertEmailVerificationToken(accountId); + var before = emailVerificationState(fixture); + assertThatThrownBy(() -> verifyEmail(fixture.token())) + .isInstanceOf(SourceEvidenceUnavailableException.class); + assertThat(emailVerificationState(fixture)).isEqualTo(before); + } + + @Test + void emailVerificationUsesFreshOwnerAfterConcurrentAccountUpdate() throws Exception { + var fixture = emailVerificationFixture(); + var changed = new AtomicBoolean(); + var executor = Executors.newSingleThreadExecutor(); + try { + org.mockito.Mockito.doAnswer( + invocation -> { + var original = invocation.callRealMethod(); + if (changed.compareAndSet(false, true)) { + executor + .submit( + () -> + new TransactionTemplate(transactionManager) + .executeWithoutResult( + status -> { + var current = + accountRepository + .findByIdForUpdate(fixture.accountId()) + .orElseThrow(); + current.setUsername("current-" + fixture.accountId()); + current.setEmail( + "current-" + fixture.accountId() + "@example.com"); + current.setPasswordHash("current-password-hash"); + current.setRole("player"); + current.setLoginAuthModes("EMAIL_OTP"); + accountRepository.save(current); + })) + .get(30, TimeUnit.SECONDS); + } + return original; + }) + .when(emailVerificationTokenRepository) + .findByToken(fixture.token()); + UUID originalUuid = + dsl.resultQuery("SELECT account_uuid FROM accounts WHERE id = ?", fixture.accountId()) + .fetchOne(0, UUID.class); + + verifyEmail(fixture.token()); + + var current = accountRepository.findById(fixture.accountId()).orElseThrow(); + assertThat(current.isEmailVerified()).isTrue(); + assertThat(current.getUsername()).isEqualTo("current-" + fixture.accountId()); + assertThat(current.getEmail()).isEqualTo("current-" + fixture.accountId() + "@example.com"); + assertThat(current.getPasswordHash()).isEqualTo("current-password-hash"); + assertThat(current.getRole()).isEqualTo("player"); + assertThat(current.getAccountUuid()).isEqualTo(originalUuid); + assertThat(current.getAccountUuidSourceNumericId()).isEqualTo(fixture.accountId()); + assertThat(current.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(current.getLoginAuthModes()).isEqualTo("EMAIL_OTP"); + } finally { + executor.shutdownNow(); + } + } + + private EmailVerificationFixture emailVerificationFixture() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + var account = + accountService.createAccount( + new CreateAccountRequest( + "verify-" + suffix, "verify-" + suffix + "@example.com", "password123")); + long accountId = + java.util.Objects.requireNonNull( + dsl.resultQuery( + "SELECT id FROM accounts WHERE account_uuid = ?", UUID.fromString(account.id())) + .fetchOne(0, Long.class)); + return insertEmailVerificationToken(accountId); + } + + private EmailVerificationFixture insertEmailVerificationToken(long accountId) { + String token = UUID.randomUUID().toString(); + dsl.execute( + "INSERT INTO email_verification_token (account_id, token, expires_at) VALUES (?, ?, ?)", + accountId, + token, + LocalDateTime.now().plusHours(1)); + return new EmailVerificationFixture(accountId, token); + } + + private void verifyEmail(String token) { + accountService.verifyEmail(new VerifyEmailRequest(token)); + } + + private List emailVerificationState(EmailVerificationFixture fixture) { + return List.of( + dsl.resultQuery( + "SELECT row_to_json(a)::text FROM accounts a WHERE id = ?", fixture.accountId()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT row_to_json(t)::text FROM email_verification_token t WHERE token = ?", + fixture.token()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT COALESCE(json_agg(s ORDER BY outbox_stream_key)::text, '[]') " + + "FROM account_authority_source_records s WHERE account_uuid = " + + "(SELECT account_uuid FROM accounts WHERE id = ?)", + fixture.accountId()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT COUNT(*)::text FROM account_authority_outbox_events " + + "WHERE outbox_stream_key = 'account:auth-authority:v1:account/' || " + + "(SELECT account_uuid::text FROM accounts WHERE id = ?)", + fixture.accountId()) + .fetchOne(0, String.class)); + } + + private record EmailVerificationFixture(long accountId, String token) {} + + @Test + void publicJoinLostCommitAcknowledgementAndReadbackReplayTheSameOriginalOnce() { + var fixture = publicJoinFixture(); + var readbackDropped = losePublicJoinTerminalResponse(fixture); + + assertPublicJoinUnavailable(fixture); + + assertThat(readbackDropped).isTrue(); + assertPublicJoinCommittedOnce(fixture); + var committed = publicJoinState(fixture); + var replay = publicJoin(fixture); + + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.outcomeCode()).isEqualTo("JOINED"); + assertThat(replay.accountId()).isEqualTo(fixture.accountUuid()); + assertPublicJoinCommittedOnce(fixture); + assertThat(publicJoinState(fixture)).isEqualTo(committed); + } + + @Test + void publicJoinFailureBeforeCommitRollsBackEffectsAndContinuesTheOriginalIntent() { + var fixture = publicJoinFixture(); + var failOnce = new AtomicBoolean(true); + org.mockito.Mockito.doAnswer( + invocation -> { + invocation.callRealMethod(); + if (failOnce.compareAndSet(true, false)) { + // The real terminal UPDATE ran, but its owner transaction has not committed. + throw new IllegalStateException("Injected failure before public JOIN commit"); + } + return null; + }) + .when(joinOperationRepository) + .finish( + org.mockito.ArgumentMatchers.eq(fixture.caller().requestId()), + org.mockito.ArgumentMatchers.eq("COMMITTED"), + org.mockito.ArgumentMatchers.eq("JOINED"), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + + assertPublicJoinUnavailable(fixture); + + assertThat(failOnce).isFalse(); + var pending = + dsl.fetchOne( + "SELECT status, outcome, intent_digest, request_digest, membership_id " + + "FROM account_join_operations WHERE request_id = ?", + fixture.caller().requestId()); + assertThat(pending).isNotNull(); + assertThat(pending.get("status", String.class)).isEqualTo("PENDING"); + assertThat(pending.get("intent_digest", String.class)).startsWith("sha256:"); + assertThat(pending.get("outcome")).isNull(); + assertThat(pending.get("request_digest")).isNull(); + assertThat(pending.get("membership_id")).isNull(); + assertThat(publicJoinMembershipCount(fixture)).isZero(); + assertThat(publicJoinAuditCount(fixture)).isZero(); + + var continued = publicJoin(fixture); + + assertThat(continued.success()).isTrue(); + assertThat(continued.replayed()).isFalse(); + assertThat(continued.outcomeCode()).isEqualTo("JOINED"); + assertPublicJoinCommittedOnce(fixture); + assertThat(publicJoin(fixture).replayed()).isTrue(); + assertPublicJoinCommittedOnce(fixture); + } + + @Test + void publicJoinLostResponseThenExpiredScopePreservesTheCompleteCommittedOriginal() { + var fixture = publicJoinFixture(); + var readbackDropped = losePublicJoinTerminalResponse(fixture); + assertPublicJoinUnavailable(fixture); + assertThat(readbackDropped).isTrue(); + assertPublicJoinCommittedOnce(fixture); + var committed = publicJoinState(fixture); + String retainedExpiry = + dsl.resultQuery( + "SELECT s.connect_scope_expires_at FROM account_connect_scope_records s " + + "JOIN account_join_operations j ON j.scope_token_hash = s.scope_token_hash " + + "WHERE j.request_id = ?", + fixture.caller().requestId()) + .fetchOne(0, String.class); + assertThat(retainedExpiry).isNotBlank(); + Instant expiredNow = Instant.parse(retainedExpiry).plusSeconds(1); + + // Advance only the owner clock; never rewrite the original scope, intent or terminal row. + try (org.mockito.MockedStatic clock = + org.mockito.Mockito.mockStatic(Instant.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + clock.when(Instant::now).thenReturn(expiredNow); + var refused = publicJoin(fixture); + assertThat(refused.success()).isFalse(); + assertThat(refused.replayed()).isFalse(); + assertThat(refused.outcomeCode()).isEqualTo("CONNECT_SCOPE_INVALID"); + } + + assertThat(publicJoinState(fixture)).isEqualTo(committed); + assertPublicJoinCommittedOnce(fixture); + } + + private AtomicBoolean losePublicJoinTerminalResponse(PublicJoinFixture fixture) { + var committed = new AtomicBoolean(); + var readbackDropped = new AtomicBoolean(); + org.mockito.Mockito.doAnswer( + invocation -> { + invocation.callRealMethod(); + org.springframework.transaction.support.TransactionSynchronizationManager + .registerSynchronization( + new org.springframework.transaction.support.TransactionSynchronization() { + @Override + public void afterCommit() { + committed.set(true); + throw new IllegalStateException("Injected lost public JOIN commit ACK"); + } + }); + return null; + }) + .when(joinOperationRepository) + .finish( + org.mockito.ArgumentMatchers.eq(fixture.caller().requestId()), + org.mockito.ArgumentMatchers.eq("COMMITTED"), + org.mockito.ArgumentMatchers.eq("JOINED"), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.doAnswer( + invocation -> { + if (committed.get() && readbackDropped.compareAndSet(false, true)) { + throw new org.springframework.dao.DataAccessResourceFailureException( + "Injected unavailable first post-commit JOIN readback"); + } + return invocation.callRealMethod(); + }) + .when(joinOperationRepository) + .find(fixture.caller().requestId()); + return readbackDropped; + } + + private void assertPublicJoinUnavailable(PublicJoinFixture fixture) { + var unavailable = + org.junit.jupiter.api.Assertions.assertThrows( + AuthenticationException.class, () -> publicJoin(fixture)); + assertThat(unavailable.getCode()).isEqualTo("AUTH_UNAVAILABLE"); + } + + private JoinPublicProductionResult publicJoin(PublicJoinFixture fixture) { + return accountService.joinPublicProductionFromGameSession( + fixture.caller(), + new JoinPublicProductionRequest(fixture.connectScopeId(), fixture.caller().requestId())); + } + + private PublicJoinFixture publicJoinFixture() { + String suffix = UUID.randomUUID().toString().substring(0, 8); + String world = "join-" + suffix; + var account = + accountService.createAccount( + new CreateAccountRequest(world, world + "@example.com", "password123")); + long accountId = + java.util.Objects.requireNonNull( + dsl.resultQuery( + "SELECT id FROM accounts WHERE account_uuid = ?", UUID.fromString(account.id())) + .fetchOne(0, Long.class)); + long tenantId = 6000000000L + accountId; + dsl.execute( + "INSERT INTO subscription(account_id,plan_id,status,tenant_id,entitlement_version) " + + "VALUES(?,'join-proof','active',?,1)", + accountId, + tenantId); + UUID realmId = UUID.randomUUID(); + String namespace = UUID.randomUUID().toString(); + var realm = + net.firedevops.firemud.gamesession.v1.GameplayRealm.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(realmId.toString()) + .setWorldSlug(world) + .setRealmSlug("production") + .setPlayableStateNamespaceId(namespace) + .setStateScope("SHARED") + .setGameInstanceId("44") + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .build(); + var pointer = + net.firedevops.firemud.gamesession.v1.GameplayAdmissionPointer.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setRealmId(realmId.toString()) + .setWorldSlug(world) + .setRealmSlug("production") + .setPlayableStateNamespaceId(namespace) + .setStateScope("SHARED") + .setGameInstanceId("44") + .setCatalogRevision(23L) + .setPointerVersion(17L) + .setVisible(true) + .setPublicProductionRealm(true) + .build(); + org.mockito.Mockito.when(gameSessionClient.listGameplayRealms(world)) + .thenReturn(List.of(realm)); + org.mockito.Mockito.when(gameSessionClient.getAdmissionPointer(tenantId, world, "production")) + .thenReturn(pointer); + var caller = + new DirectTextCallerContext( + accountId, + tenantId, + realmId, + namespace, + "SHARED", + 44L, + "controlled-join-session-" + suffix, + "original-join-" + suffix); + var scope = + accountService.issueDirectTextConnectScope( + caller, + new DirectTextJoinTarget( + tenantId, realmId, world, "production", namespace, "SHARED", 44L, 23L, 17L)); + return new PublicJoinFixture(accountId, account.id(), tenantId, caller, scope.connectScopeId()); + } + + private long publicJoinMembershipCount(PublicJoinFixture fixture) { + return java.util.Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_tenant_membership WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, Long.class)); + } + + private UUID publicJoinAuditId(PublicJoinFixture fixture) { + return UUID.nameUUIDFromBytes( + ("account-join-audit/v1:" + fixture.caller().requestId()).getBytes(StandardCharsets.UTF_8)); + } + + private long publicJoinAuditCount(PublicJoinFixture fixture) { + return java.util.Objects.requireNonNull( + dsl.resultQuery( + "SELECT COUNT(*) FROM account_audit_outbox WHERE audit_event_id = ?", + publicJoinAuditId(fixture)) + .fetchOne(0, Long.class)); + } + + private void assertPublicJoinCommittedOnce(PublicJoinFixture fixture) { + assertThat(publicJoinMembershipCount(fixture)).isEqualTo(1L); + assertThat(publicJoinAuditCount(fixture)).isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_join_operations j " + + "JOIN account_tenant_membership m ON m.id = j.membership_id " + + "WHERE j.request_id = ? AND j.status = 'COMMITTED' AND j.outcome = 'JOINED' " + + "AND j.account_id = ? AND j.tenant_id = ? " + + "AND m.account_id = j.account_id AND m.tenant_id = j.tenant_id " + + "AND m.lifecycle_state = 'ACTIVE' AND m.authority_provenance = 'EXPLICIT_JOIN' " + + "AND m.membership_version = 1 AND m.membership_authority_generation = 1 " + + "AND j.outcome_membership_version = m.membership_version " + + "AND j.outcome_membership_authority_generation = m.membership_authority_generation", + fixture.caller().requestId(), + fixture.accountId(), + fixture.tenantId())) + .isEqualTo(1L); + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM account_audit_outbox " + + "WHERE audit_event_id = ? AND scope = 'tenant' AND tenant_id = ? " + + "AND producer_service = 'account-service' " + + "AND event_type = 'ACCOUNT_JOINED_PUBLIC_PRODUCTION' " + + "AND payload::jsonb ->> 'requestId' = ? " + + "AND payload::jsonb ->> 'accountId' = ? " + + "AND payload::jsonb ->> 'membershipVersion' = '1'", + publicJoinAuditId(fixture), + fixture.tenantId(), + fixture.caller().requestId(), + Long.toString(fixture.accountId()))) + .isEqualTo(1L); + } + + private List publicJoinState(PublicJoinFixture fixture) { + return List.of( + dsl.resultQuery( + "SELECT row_to_json(j)::text FROM account_join_operations j WHERE request_id = ?", + fixture.caller().requestId()) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT row_to_json(m)::text FROM account_tenant_membership m " + + "WHERE account_id = ? AND tenant_id = ?", + fixture.accountId(), + fixture.tenantId()) + .fetchOne(0, String.class), + dsl.resultQuery( + // Delivery retry diagnostics may advance independently of original JOIN evidence. + "SELECT (to_jsonb(a) - ARRAY['attempt_count','last_attempt_at','next_attempt_at'])::text " + + "FROM account_audit_outbox a WHERE audit_event_id = ?", + publicJoinAuditId(fixture)) + .fetchOne(0, String.class), + dsl.resultQuery( + "SELECT row_to_json(s)::text FROM account_connect_scope_records s " + + "JOIN account_join_operations j ON j.scope_token_hash = s.scope_token_hash " + + "WHERE j.request_id = ?", + fixture.caller().requestId()) + .fetchOne(0, String.class)); + } + + private record PublicJoinFixture( + long accountId, + String accountUuid, + long tenantId, + DirectTextCallerContext caller, + String connectScopeId) {} + @Test void publicRegistrationCreatesGlobalIdentityAndDurablePlatformAuditOnly() throws Exception { String suffix = UUID.randomUUID().toString().substring(0, 8); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java new file mode 100644 index 0000000000..a39851e3a7 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java @@ -0,0 +1,154 @@ +package unit.net.firedevops.firemud.accountservice.security; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.io.IOException; +import net.firedevops.firemud.accountservice.controller.AuthController; +import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.common.GlobalExceptionHandler; +import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; +import net.firedevops.firemud.common.config.CommonSecurityServletAutoConfiguration; +import net.firedevops.firemud.common.security.HttpAuthProperties; +import net.firedevops.firemud.common.security.HttpJwtAuthInterceptor; +import net.firedevops.firemud.common.security.JwtUtil; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration; +import org.springframework.boot.env.YamlPropertySourceLoader; +import org.springframework.boot.test.context.runner.WebApplicationContextRunner; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.MediaType; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +/** Actual Account YAML and servlet-auth composition with a mocked verification owner. */ +class EmailVerificationHttpAuthWiringTest { + private static final String PATH = "/auth/verify-email"; + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void publicPostReachesMappedVerificationOwnerWithoutBearer(boolean productionLayer) { + JwtUtil jwtUtil = mock(JwtUtil.class); + configuredRunner(productionLayer, jwtUtil) + .run( + context -> { + assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); + HttpAuthProperties properties = context.getBean(HttpAuthProperties.class); + assertThat(properties.isEnabled()).isTrue(); + assertThat(properties.getPublicRoutes()) + .filteredOn(route -> PATH.equals(route.getPathPattern())) + .extracting(HttpAuthProperties.HttpPublicRoute::getMethod) + .containsExactly("POST"); + AccountService owner = mock(AccountService.class); + var mvc = + MockMvcBuilders.standaloneSetup(new AuthController(owner)) + .addInterceptors(context.getBean(HttpJwtAuthInterceptor.class)) + .build(); + + mvc.perform( + post(PATH) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"token\":\"exact-verification-token\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.status").value("SUCCESS")); + + verify(owner).verifyEmail(new VerifyEmailRequest("exact-verification-token")); + verifyNoMoreInteractions(owner); + verifyNoInteractions(jwtUtil); + }); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void publicPostPreservesVerificationOwnersInvalidTokenOutcome(boolean productionLayer) { + JwtUtil jwtUtil = mock(JwtUtil.class); + configuredRunner(productionLayer, jwtUtil) + .run( + context -> { + assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); + AccountService owner = mock(AccountService.class); + VerifyEmailRequest invalid = new VerifyEmailRequest("invalid-token"); + doThrow(new IllegalArgumentException("Invalid token")) + .when(owner) + .verifyEmail(invalid); + var mvc = + MockMvcBuilders.standaloneSetup(new AuthController(owner)) + .setControllerAdvice(new GlobalExceptionHandler()) + .addInterceptors(context.getBean(HttpJwtAuthInterceptor.class)) + .build(); + + mvc.perform( + post(PATH) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"token\":\"invalid-token\"}")) + .andExpect(status().isBadRequest()); + + verify(owner).verifyEmail(invalid); + verifyNoMoreInteractions(owner); + verifyNoInteractions(jwtUtil); + }); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void getIsNotWhitelistedWithoutBearer(boolean productionLayer) { + JwtUtil jwtUtil = mock(JwtUtil.class); + configuredRunner(productionLayer, jwtUtil) + .run( + context -> { + assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); + HttpJwtAuthInterceptor interceptor = context.getBean(HttpJwtAuthInterceptor.class); + MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); + MockHttpServletResponse response = new MockHttpServletResponse(); + + assertThat(interceptor.preHandle(request, response, new Object())).isFalse(); + assertThat(response.getStatus()).isEqualTo(401); + verifyNoInteractions(jwtUtil); + }); + } + + private static WebApplicationContextRunner configuredRunner( + boolean productionLayer, JwtUtil jwtUtil) { + return new WebApplicationContextRunner() + .withConfiguration( + AutoConfigurations.of( + ConfigurationPropertiesAutoConfiguration.class, + CommonSecurityAutoConfiguration.class, + CommonSecurityServletAutoConfiguration.class)) + .withBean("jwtUtil", JwtUtil.class, () -> jwtUtil) + .withInitializer( + context -> { + try { + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + for (var source : + loader.load( + "account-application", + new FileSystemResource("src/main/resources/application.yml"))) { + context.getEnvironment().getPropertySources().addLast(source); + } + if (productionLayer) { + context.getEnvironment().setActiveProfiles("prod"); + for (var source : + loader.load( + "account-application-prod", + new FileSystemResource("src/main/resources/application-prod.yml"))) { + context.getEnvironment().getPropertySources().addFirst(source); + } + } + } catch (IOException exception) { + throw new IllegalStateException("Could not load Account HTTP auth YAML", exception); + } + }); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java new file mode 100644 index 0000000000..94d7c242c6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java @@ -0,0 +1,332 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +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.stub.MetadataUtils; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.account.v1.RequestEmailLoginOtpRequest; +import net.firedevops.firemud.account.v1.VerifyEmailLoginOtpRequest; +import net.firedevops.firemud.accountservice.dto.AuthenticationResult; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.PingService; +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.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.BeforeAll; +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.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.mock.env.MockEnvironment; + +/** + * Physical TLS caller-policy proof with a mocked Account credential owner, not credential proof. + */ +class AccountCredentialPeerGrpcMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_UUID = "4cae05e8-7a6b-4b14-9d44-665e3eec450b"; + private static final String DEMO_EMAIL = "demo@example.com"; + private static final String GAME_SESSION_URI = "spiffe://firemud/ns/test/sa/game-session-service"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + + @TempDir static Path temporaryDirectory; + + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + temporaryDirectory, + "FireMUD Account credential peer test CA", + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", true), + new IdentitySpec("game-session", GAME_SESSION_URI, false), + new IdentitySpec("entity", ENTITY_URI, false), + new IdentitySpec( + "world", "spiffe://firemud/ns/test/sa/world-management-service", false), + new IdentitySpec( + "other-game-session", "spiffe://firemud/ns/other/sa/game-session-service", false), + new IdentitySpec( + "other-entity", "spiffe://firemud/ns/other/sa/entity-management-service", false)); + } + + @Test + void gameSessionCertificateAuthorizesAllThreeCredentialMethodsWithoutFixtureSettings() + throws Exception { + AccountService owner = credentialOwner(GAME_SESSION_URI); + AccountGrpcService service = + new AccountGrpcService(mock(PingService.class), owner, null, NAMESPACE); + try (TransportServer server = startServer(service); + ClientTransport client = newClient(server.port(), "game-session")) { + var stub = client.stub(); + assertAuthenticated(stub.authenticate(authentication(DEMO_EMAIL))); + var challenge = stub.requestEmailLoginOtp(challenge()); + assertThat(challenge.hasError()).isFalse(); + assertThat(challenge.getAccepted()).isTrue(); + assertAuthenticated(stub.verifyEmailLoginOtp(verification())); + + verify(owner).authenticateForGameplay(DEMO_EMAIL, "password"); + verify(owner).requestEmailLoginOtp(DEMO_EMAIL); + verify(owner).verifyEmailLoginOtp(DEMO_EMAIL, "123456"); + verifyNoMoreInteractions(owner); + } + } + + @Test + void exactEntityCertificateAuthenticatesOnlyDemoFixtureAndNeverAuthorizesOtp() throws Exception { + AccountService owner = credentialOwner(ENTITY_URI); + try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture")); + ClientTransport client = newClient(server.port(), "entity")) { + var stub = client.stub(); + assertAuthenticated(stub.authenticate(authentication(DEMO_EMAIL))); + assertOtpDenied(stub); + + verify(owner).authenticateForGameplay(DEMO_EMAIL, "password"); + verifyNoMoreInteractions(owner); + } + } + + @ParameterizedTest + @MethodSource("unavailableFixtureSettings") + void entityCertificateCannotBypassReceivingFlagOrProfileGates(boolean enabled, String[] profiles) + throws Exception { + AccountService owner = mock(AccountService.class); + try (TransportServer server = startServer(fixtureService(owner, enabled, profiles)); + ClientTransport client = newClient(server.port(), "entity")) { + assertAllDenied(client.stub(), authentication(DEMO_EMAIL)); + verifyNoInteractions(owner); + } + } + + private static Stream unavailableFixtureSettings() { + return Stream.of( + Arguments.of(false, new String[] {"local-fixture"}), + Arguments.of(true, new String[] {}), + Arguments.of(true, new String[] {"prod"}), + Arguments.of(true, new String[] {"local-fixture", "prod"})); + } + + @Test + void defaultConstructorDoesNotAuthorizeEntityFixture() throws Exception { + AccountService owner = mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(mock(PingService.class), owner, null, NAMESPACE); + try (TransportServer server = startServer(service); + ClientTransport client = newClient(server.port(), "entity")) { + assertAllDenied(client.stub(), authentication(DEMO_EMAIL)); + verifyNoInteractions(owner); + } + } + + @Test + void trustedWrongWorkloadAndNamespaceCertificatesAreDeniedBeforeAccountInvocation() + throws Exception { + AccountService owner = mock(AccountService.class); + try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture"))) { + for (String alias : List.of("world", "other-game-session", "other-entity")) { + try (ClientTransport client = newClient(server.port(), alias)) { + assertAllDenied(client.stub(), AuthenticateRequest.getDefaultInstance()); + } + } + verifyNoInteractions(owner); + } + } + + @Test + void entityCertificateCannotAuthenticateAnotherEmail() throws Exception { + AccountService owner = mock(AccountService.class); + try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture")); + ClientTransport client = newClient(server.port(), "entity")) { + assertAuthenticationDenied(client.stub().authenticate(authentication("other@example.com"))); + verifyNoInteractions(owner); + } + } + + @Test + void callerSuppliedPeerHeadersCannotReplaceWrongWorkloadCertificate() throws Exception { + AccountService owner = mock(AccountService.class); + Metadata spoofed = new Metadata(); + for (String header : List.of("x-peer-identity", "x-spiffe-id", "x-workload-identity")) { + spoofed.put(Metadata.Key.of(header, Metadata.ASCII_STRING_MARSHALLER), GAME_SESSION_URI); + } + try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture")); + ClientTransport client = newClient(server.port(), "world")) { + var stub = client.stub().withInterceptors(MetadataUtils.newAttachHeadersInterceptor(spoofed)); + assertAllDenied(stub, authentication(DEMO_EMAIL)); + verifyNoInteractions(owner); + } + } + + @Test + void missingClientCertificateFailsHandshakeWithoutAccountInvocation() throws Exception { + AccountService owner = mock(AccountService.class); + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + // Reuse the fixture's CA projection without supplying its client certificate or key. + var issued = pki.clientProperties(temporaryDirectory, pki.identity("game-session")); + tls.setCaCert(issued.getCaCert()); + try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture")); + ClientTransport client = newClient(server.port(), tls)) { + assertThatThrownBy(() -> client.stub().authenticate(authentication(DEMO_EMAIL))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); + verifyNoInteractions(owner); + } + } + + private static AccountService credentialOwner(String expectedPeerUri) { + AccountService owner = mock(AccountService.class); + doAnswer( + invocation -> { + assertThat(GrpcPeerIdentity.current()).isNotNull(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(expectedPeerUri); + return new AuthenticationResult(ACCOUNT_UUID, "test-owner-token"); + }) + .when(owner) + .authenticateForGameplay(DEMO_EMAIL, "password"); + doAnswer( + invocation -> { + assertThat(GrpcPeerIdentity.current()).isNotNull(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(expectedPeerUri); + return new AuthenticationResult(ACCOUNT_UUID, "test-owner-token"); + }) + .when(owner) + .verifyEmailLoginOtp(DEMO_EMAIL, "123456"); + doAnswer( + invocation -> { + assertThat(GrpcPeerIdentity.current()).isNotNull(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(expectedPeerUri); + return null; + }) + .when(owner) + .requestEmailLoginOtp(DEMO_EMAIL); + return owner; + } + + private static AccountGrpcService fixtureService( + AccountService owner, boolean enabled, String... profiles) { + MockEnvironment environment = new MockEnvironment(); + environment.setActiveProfiles(profiles); + return new AccountGrpcService( + mock(PingService.class), owner, null, NAMESPACE, environment, enabled, DEMO_EMAIL); + } + + private static AuthenticateRequest authentication(String email) { + return AuthenticateRequest.newBuilder().setEmail(email).setPassword("password").build(); + } + + private static RequestEmailLoginOtpRequest challenge() { + return RequestEmailLoginOtpRequest.newBuilder().setEmail(DEMO_EMAIL).build(); + } + + private static VerifyEmailLoginOtpRequest verification() { + return VerifyEmailLoginOtpRequest.newBuilder().setEmail(DEMO_EMAIL).setCode("123456").build(); + } + + private static void assertAuthenticated(AuthenticateResponse response) { + assertThat(response.hasError()).isFalse(); + assertThat(response.getAccountId()).isEqualTo(ACCOUNT_UUID); + assertThat(response.getAuthToken()).isEqualTo("test-owner-token"); + } + + private static void assertAuthenticationDenied(AuthenticateResponse response) { + assertThat(response.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + assertThat(response.getAccountId()).isEmpty(); + assertThat(response.getAuthToken()).isEmpty(); + } + + private static void assertOtpDenied(AccountServiceGrpc.AccountServiceBlockingStub stub) { + var challenge = stub.requestEmailLoginOtp(RequestEmailLoginOtpRequest.getDefaultInstance()); + assertThat(challenge.getError().getCode()).isEqualTo("PERMISSION_DENIED"); + assertThat(challenge.getAccepted()).isFalse(); + assertAuthenticationDenied( + stub.verifyEmailLoginOtp(VerifyEmailLoginOtpRequest.getDefaultInstance())); + } + + private static void assertAllDenied( + AccountServiceGrpc.AccountServiceBlockingStub stub, AuthenticateRequest request) { + assertAuthenticationDenied(stub.authenticate(request)); + assertOtpDenied(stub); + } + + private static TransportServer startServer(AccountGrpcService service) throws Exception { + var identity = pki.identity("account"); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server); + } + + private static ClientTransport newClient(int port, String alias) throws Exception { + return newClient(port, pki.clientProperties(temporaryDirectory, pki.identity(alias))); + } + + private static ClientTransport newClient(int port, CommonGrpcClientProperties tls) + throws Exception { + return new ClientTransport( + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false)); + } + + private record TransportServer(Server server) implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account credential server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private AccountServiceGrpc.AccountServiceBlockingStub stub() { + return AccountServiceGrpc.newBlockingStub(channel).withDeadlineAfter(5, TimeUnit.SECONDS); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account credential client did not terminate"); + } + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 3d69ec90e0..9de596c0ad 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -3,6 +3,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import io.grpc.Context; @@ -67,10 +68,12 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mockito; import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.mock.env.MockEnvironment; import org.springframework.transaction.CannotCreateTransactionException; class AccountGrpcServiceTest { @@ -670,23 +673,30 @@ void authenticateFailureReturnsErrorDetail() { .thenThrow( new AuthenticationException( AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.authenticate( - AuthenticateRequest.newBuilder().setEmail("demo@example.com").setPassword("bad").build(), - new StreamObserver() { - @Override - public void onNext(AuthenticateResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("bad") + .build(), + new StreamObserver() { + @Override + public void onNext(AuthenticateResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals(AuthenticationErrorCodes.INVALID_CREDENTIALS, ref.get().getError().getCode()); @@ -700,15 +710,19 @@ void authenticateConvertsIllegalStateToBoundedAuthorityUnavailableError() { .thenThrow(new IllegalStateException("private provenance detail")); SimpleMeterRegistry registry = new SimpleMeterRegistry(); AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService, registry); + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, registry, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.authenticate( - AuthenticateRequest.newBuilder() - .setEmail("demo@example.com") - .setPassword("password") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer)); assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); assertEquals( @@ -726,15 +740,19 @@ void authenticatePreservesAccountOwnerUnavailableAsApplicationError() { .thenThrow( new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable")); AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService); + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.authenticate( - AuthenticateRequest.newBuilder() - .setEmail("demo@example.com") - .setPassword("password") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer)); assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); assertEquals("Account authority is unavailable", observer.response().getError().getMessage()); @@ -750,15 +768,19 @@ void verifyEmailLoginOtpPreservesAccountOwnerUnavailableAsApplicationError() { .thenThrow( new AuthenticationException("AUTH_UNAVAILABLE", "Account authority is unavailable")); AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService); + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.verifyEmailLoginOtp( - VerifyEmailLoginOtpRequest.newBuilder() - .setEmail("demo@example.com") - .setCode("123456") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + observer)); assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); assertEquals( @@ -772,23 +794,27 @@ void verifyEmailLoginOtpPreservesAccountOwnerUnavailableAsApplicationError() { void requestEmailLoginOtpDispatchesNeutralChallengeRequest() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.requestEmailLoginOtp( - RequestEmailLoginOtpRequest.newBuilder().setEmail("demo@example.com").build(), - new StreamObserver() { - @Override - public void onNext(RequestEmailLoginOtpResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.requestEmailLoginOtp( + RequestEmailLoginOtpRequest.newBuilder().setEmail("demo@example.com").build(), + new StreamObserver() { + @Override + public void onNext(RequestEmailLoginOtpResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertTrue(ref.get().getAccepted()); @@ -799,11 +825,15 @@ public void onCompleted() {} void requestEmailLoginOtpRejectsBlankEmailBeforeCallingAccountService() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.requestEmailLoginOtp( - RequestEmailLoginOtpRequest.newBuilder().setEmail(" ").build(), observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.requestEmailLoginOtp( + RequestEmailLoginOtpRequest.newBuilder().setEmail(" ").build(), observer)); assertNotNull(observer.response()); assertFalse(observer.response().getAccepted()); @@ -822,26 +852,30 @@ void verifyEmailLoginOtpReturnsAuthenticatedSession() { .thenReturn( new net.firedevops.firemud.accountservice.dto.AuthenticationResult( ACCOUNT_UUID, "jwt")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - service.verifyEmailLoginOtp( - VerifyEmailLoginOtpRequest.newBuilder() - .setEmail("demo@example.com") - .setCode("123456") - .build(), - new StreamObserver() { - @Override - public void onNext(AuthenticateResponse value) { - ref.set(value); - } + withPeer( + GAME_SESSION_PEER, + () -> + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + new StreamObserver() { + @Override + public void onNext(AuthenticateResponse value) { + ref.set(value); + } - @Override - public void onError(Throwable t) {} + @Override + public void onError(Throwable t) {} - @Override - public void onCompleted() {} - }); + @Override + public void onCompleted() {} + })); assertNotNull(ref.get()); assertEquals(ACCOUNT_UUID, ref.get().getAccountId()); @@ -856,15 +890,19 @@ void authenticateReturnsCanonicalUuid() { .thenReturn( new net.firedevops.firemud.accountservice.dto.AuthenticationResult( ACCOUNT_UUID, "jwt")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.authenticate( - AuthenticateRequest.newBuilder() - .setEmail("demo@example.com") - .setPassword("password") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + observer)); assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); assertEquals("jwt", observer.response().getAuthToken()); @@ -879,15 +917,19 @@ void verifyEmailLoginOtpReturnsInvalidCredentialsAsApplicationError() { .thenThrow( new AuthenticationException( AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); - AccountGrpcService service = new AccountGrpcService(pingService, accountService); + AccountGrpcService service = + new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.verifyEmailLoginOtp( - VerifyEmailLoginOtpRequest.newBuilder() - .setEmail("demo@example.com") - .setCode("123456") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + observer)); assertNotNull(observer.response()); assertEquals( @@ -903,15 +945,19 @@ void verifyEmailLoginOtpConvertsIllegalStateToBoundedAuthorityUnavailableError() .thenThrow(new IllegalStateException("private provenance detail")); SimpleMeterRegistry registry = new SimpleMeterRegistry(); AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService, registry); + new AccountGrpcService( + Mockito.mock(PingService.class), accountService, registry, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); - service.verifyEmailLoginOtp( - VerifyEmailLoginOtpRequest.newBuilder() - .setEmail("demo@example.com") - .setCode("123456") - .build(), - observer); + withPeer( + GAME_SESSION_PEER, + () -> + service.verifyEmailLoginOtp( + VerifyEmailLoginOtpRequest.newBuilder() + .setEmail("demo@example.com") + .setCode("123456") + .build(), + observer)); assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); assertEquals( @@ -922,6 +968,243 @@ void verifyEmailLoginOtpConvertsIllegalStateToBoundedAuthorityUnavailableError() 1.0, registry.get("grpc.app_error").tag("code", "AUTH_UNAVAILABLE").counter().count()); } + @Test + void credentialMethodsRejectMissingAndWrongPeersBeforePayloadAccess() { + for (GrpcPeerIdentity peer : + java.util.Arrays.asList( + null, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/unknown-service").orElse(null), + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/world-management-service") + .orElseThrow(), + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/spring-cloud-gateway") + .orElseThrow(), + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/other/sa/game-session-service") + .orElseThrow(), + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/other/sa/entity-management-service") + .orElseThrow())) { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = + localDemoService(owner, true, "demo@example.com", "local-fixture"); + withPeer(peer, () -> assertCredentialMethodsDeniedBeforePayload(service)); + Mockito.verifyNoInteractions(owner); + } + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void credentialMethodsRejectBlankReceivingNamespace(String namespace) { + AccountService owner = Mockito.mock(AccountService.class); + MockEnvironment environment = new MockEnvironment(); + environment.setActiveProfiles("local-fixture"); + AccountGrpcService service = + new AccountGrpcService( + Mockito.mock(PingService.class), + owner, + null, + namespace, + environment, + true, + "demo@example.com"); + withPeer(GAME_SESSION_PEER, () -> assertCredentialMethodsDeniedBeforePayload(service)); + withPeer(entityPeer(), () -> assertCredentialMethodsDeniedBeforePayload(service)); + Mockito.verifyNoInteractions(owner); + } + + @Test + void defaultConstructorDoesNotAuthorizeEntityDemoFixture() { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = + new AccountGrpcService(Mockito.mock(PingService.class), owner, null, WORKLOAD_NAMESPACE); + withPeer(entityPeer(), () -> assertCredentialMethodsDeniedBeforePayload(service)); + Mockito.verifyNoInteractions(owner); + } + + private static void assertCredentialMethodsDeniedBeforePayload(AccountGrpcService service) { + RecordingObserver authenticate = new RecordingObserver<>(); + RecordingObserver request = new RecordingObserver<>(); + RecordingObserver verify = new RecordingObserver<>(); + service.authenticate(null, authenticate); + service.requestEmailLoginOtp(null, request); + service.verifyEmailLoginOtp(null, verify); + assertEquals("PERMISSION_DENIED", authenticate.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", request.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", verify.response().getError().getCode()); + assertTrue(authenticate.response().getAuthToken().isEmpty()); + assertTrue(authenticate.response().getAccountId().isEmpty()); + assertFalse(request.response().getAccepted()); + assertTrue(verify.response().getAuthToken().isEmpty()); + assertTrue(verify.response().getAccountId().isEmpty()); + for (RecordingObserver observer : List.of(authenticate, request, verify)) { + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + } + } + + @ParameterizedTest + @MethodSource("deniedLocalDemoAuthenticationSettings") + void entityDemoAuthenticationRequiresEveryReceivingFixtureGate( + boolean enabled, String[] profiles, String email) { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = localDemoService(owner, enabled, "demo@example.com", profiles); + RecordingObserver observer = new RecordingObserver<>(); + withPeer( + entityPeer(), + () -> + service.authenticate( + AuthenticateRequest.newBuilder().setEmail(email).setPassword("password").build(), + observer)); + assertEquals("PERMISSION_DENIED", observer.response().getError().getCode()); + assertTrue(observer.response().getAuthToken().isEmpty()); + assertTrue(observer.response().getAccountId().isEmpty()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(owner); + } + + private static Stream deniedLocalDemoAuthenticationSettings() { + return Stream.of( + Arguments.of(false, new String[] {"local-fixture"}, "demo@example.com"), + Arguments.of(true, new String[] {}, "demo@example.com"), + Arguments.of(true, new String[] {"prod"}, "demo@example.com"), + Arguments.of(true, new String[] {"local-fixture", "prod"}, "demo@example.com"), + Arguments.of(true, new String[] {"local-fixture"}, "other@example.com"), + Arguments.of(true, new String[] {"local-fixture"}, " ")); + } + + @ParameterizedTest + @ValueSource(strings = {"", " "}) + void enabledLocalFixtureRequiresConfiguredDemoIdentity(String email) { + AccountService owner = Mockito.mock(AccountService.class); + assertThrows( + IllegalArgumentException.class, + () -> localDemoService(owner, true, email, "local-fixture")); + Mockito.verifyNoInteractions(owner); + } + + @Test + void gameSessionAuthenticationRemainsAvailableWithProductionFixtureExclusion() { + AccountService owner = Mockito.mock(AccountService.class); + Mockito.when(owner.authenticateForGameplay("player@example.com", "password")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.AuthenticationResult( + ACCOUNT_UUID, "jwt")); + AccountGrpcService service = + localDemoService(owner, true, "demo@example.com", "local-fixture", "prod"); + RecordingObserver observer = new RecordingObserver<>(); + withPeer( + GAME_SESSION_PEER, + () -> + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("player@example.com") + .setPassword("password") + .build(), + observer)); + assertEquals(ACCOUNT_UUID, observer.response().getAccountId()); + assertEquals("jwt", observer.response().getAuthToken()); + assertFalse(observer.response().hasError()); + assertTrue(observer.completed()); + assertFalse(observer.receivedTransportError()); + Mockito.verify(owner).authenticateForGameplay("player@example.com", "password"); + Mockito.verifyNoMoreInteractions(owner); + } + + @Test + void entityDemoFixturePreservesCredentialVerificationAndCanonicalUuid() { + AccountService owner = Mockito.mock(AccountService.class); + Mockito.when(owner.authenticateForGameplay("demo@example.com", "password")) + .thenReturn( + new net.firedevops.firemud.accountservice.dto.AuthenticationResult( + ACCOUNT_UUID, "jwt")); + Mockito.when(owner.authenticateForGameplay("demo@example.com", "bad")) + .thenThrow( + new AuthenticationException( + AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); + AccountGrpcService service = + localDemoService(owner, true, " DEMO@EXAMPLE.COM ", "local-fixture"); + RecordingObserver success = new RecordingObserver<>(); + RecordingObserver failure = new RecordingObserver<>(); + withPeer( + entityPeer(), + () -> { + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("password") + .build(), + success); + service.authenticate( + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("bad") + .build(), + failure); + }); + assertEquals(ACCOUNT_UUID, success.response().getAccountId()); + assertEquals("jwt", success.response().getAuthToken()); + assertFalse(success.response().hasError()); + assertEquals( + AuthenticationErrorCodes.INVALID_CREDENTIALS, failure.response().getError().getCode()); + assertTrue(failure.response().getAuthToken().isEmpty()); + assertTrue(failure.response().getAccountId().isEmpty()); + assertTrue(success.completed()); + assertTrue(failure.completed()); + assertFalse(success.receivedTransportError()); + assertFalse(failure.receivedTransportError()); + Mockito.verify(owner).authenticateForGameplay("demo@example.com", "password"); + Mockito.verify(owner).authenticateForGameplay("demo@example.com", "bad"); + Mockito.verifyNoMoreInteractions(owner); + } + + @Test + void enabledEntityDemoFixtureNeverAuthorizesOtpMethods() { + AccountService owner = Mockito.mock(AccountService.class); + AccountGrpcService service = localDemoService(owner, true, "demo@example.com", "local-fixture"); + RecordingObserver request = new RecordingObserver<>(); + RecordingObserver verify = new RecordingObserver<>(); + withPeer( + entityPeer(), + () -> { + service.requestEmailLoginOtp(null, request); + service.verifyEmailLoginOtp(null, verify); + }); + assertEquals("PERMISSION_DENIED", request.response().getError().getCode()); + assertEquals("PERMISSION_DENIED", verify.response().getError().getCode()); + assertFalse(request.response().getAccepted()); + assertTrue(verify.response().getAuthToken().isEmpty()); + assertTrue(verify.response().getAccountId().isEmpty()); + assertTrue(request.completed()); + assertTrue(verify.completed()); + assertFalse(request.receivedTransportError()); + assertFalse(verify.receivedTransportError()); + assertEquals(1, request.nextCalls); + assertEquals(1, request.completedCalls); + assertEquals(1, verify.nextCalls); + assertEquals(1, verify.completedCalls); + Mockito.verifyNoInteractions(owner); + } + + private static GrpcPeerIdentity entityPeer() { + return GrpcPeerIdentity.parseUri("spiffe://firemud/ns/test/sa/entity-management-service") + .orElseThrow(); + } + + private static AccountGrpcService localDemoService( + AccountService owner, boolean enabled, String email, String... profiles) { + MockEnvironment environment = new MockEnvironment(); + environment.setActiveProfiles(profiles); + return new AccountGrpcService( + Mockito.mock(PingService.class), + owner, + null, + WORKLOAD_NAMESPACE, + environment, + enabled, + email); + } + @Test void createAccountValidationErrorReturnsErrorDetail() { PingService pingService = Mockito.mock(PingService.class); @@ -2471,67 +2754,50 @@ public void onCompleted() {} } @Test - void exportAccountErrorReturnsDetail() { + void exportAccountDeniesCanonicalSelectorBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.exportAccountData(2L)) - .thenThrow(new IllegalArgumentException("missing")); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = new RecordingObserver<>(); - AtomicReference ref = new AtomicReference<>(); service.exportAccount( - ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), - new StreamObserver() { - @Override - public void onNext(ExportAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), observer); - assertNotNull(ref.get()); - assertEquals("NOT_FOUND", ref.get().getError().getCode()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertTrue(observer.response().getAccountJson().isEmpty()); + assertTrue(observer.response().getProfilesJson().isEmpty()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void exportAccountPreservesUnavailableOwnerProjectionResponse() { + void exportAccountDeniesAbsentSelectorBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - String message = "Account owner projection is unavailable"; - Mockito.when(accountService.exportAccountData(2L)) - .thenThrow(new AuthenticationException("AUTH_UNAVAILABLE", message)); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); - AccountGrpcService service = - new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); RecordingObserver observer = new RecordingObserver<>(); - service.exportAccount( - ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), observer); + service.exportAccount(ExportAccountRequest.getDefaultInstance(), observer); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertTrue(observer.response().getAccountJson().isEmpty()); + assertTrue(observer.response().getProfilesJson().isEmpty()); assertEquals(1, observer.nextCalls); - assertEquals(0, observer.receivedTransportError() ? 1 : 0); assertEquals(1, observer.completedCalls); - assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); - assertEquals(message, observer.response().getError().getMessage()); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void exportTenantDataPreservesUnavailableOwnerProjectionResponse() { + void exportTenantDataDeniesCanonicalRequestBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - String message = "Account owner projection is unavailable"; - Mockito.when(accountService.exportTenantData(1L, 2L)) - .thenThrow(new AuthenticationException("AUTH_UNAVAILABLE", message)); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); RecordingObserver observer = new RecordingObserver<>(); @@ -2543,64 +2809,55 @@ void exportTenantDataPreservesUnavailableOwnerProjectionResponse() { assertEquals(1, observer.nextCalls); assertEquals(0, observer.receivedTransportError() ? 1 : 0); assertEquals(1, observer.completedCalls); - assertEquals("AUTH_UNAVAILABLE", observer.response().getError().getCode()); - assertEquals(message, observer.response().getError().getMessage()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertTrue(observer.response().getTenantId().isEmpty()); + assertTrue(observer.response().getAccountJson().isEmpty()); + assertTrue(observer.response().getProfileJson().isEmpty()); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void exportAccountRejectsZeroAccountIdBeforeLookup() { + void exportAccountDeniesMalformedSelectorBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = new RecordingObserver<>(); - AtomicReference ref = new AtomicReference<>(); - service.exportAccount( - ExportAccountRequest.newBuilder().setAccountId("0").build(), - new StreamObserver() { - @Override - public void onNext(ExportAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + service.exportAccount(ExportAccountRequest.newBuilder().setAccountId("0").build(), observer); - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertTrue(observer.response().getAccountJson().isEmpty()); + assertTrue(observer.response().getProfilesJson().isEmpty()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void exportTenantDataRejectsZeroTenantIdBeforeLookup() { + void exportTenantDataDeniesMalformedRequestBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - AtomicReference ref = new AtomicReference<>(); + RecordingObserver observer = new RecordingObserver<>(); service.exportTenantData( - ExportTenantDataRequest.newBuilder().setTenantId("0").setAccountId("2").build(), - new StreamObserver() { - @Override - public void onNext(ExportTenantDataResponse value) { - ref.set(value); - } + ExportTenantDataRequest.newBuilder().setTenantId("0").setAccountId("2").build(), observer); - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertTrue(observer.response().getTenantId().isEmpty()); + assertTrue(observer.response().getAccountJson().isEmpty()); + assertTrue(observer.response().getProfileJson().isEmpty()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); } @Test @@ -2663,15 +2920,13 @@ public void onCompleted() {} } @Test - void linkExternalAccountSuccess() { + void linkExternalAccountDeniesCanonicalSelectorsBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); - Mockito.when(accountService.resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID))) - .thenReturn(2L); AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = + new RecordingObserver<>(); - AtomicReference ref = - new AtomicReference<>(); service.linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() .setTenantId("1") @@ -2679,31 +2934,26 @@ void linkExternalAccountSuccess() { .setProvider("google") .setExternalId("abc") .build(), - new StreamObserver() { - @Override - public void onNext(net.firedevops.firemud.account.v1.LinkExternalAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + observer); - assertNotNull(ref.get()); - assertTrue(ref.get().getSuccess()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertFalse(observer.response().getSuccess()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void linkExternalAccountRejectsZeroTenantIdBeforeLink() { + void linkExternalAccountDeniesMalformedSelectorsBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = + new RecordingObserver<>(); - AtomicReference ref = - new AtomicReference<>(); service.linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() .setTenantId("0") @@ -2711,91 +2961,81 @@ void linkExternalAccountRejectsZeroTenantIdBeforeLink() { .setProvider("google") .setExternalId("abc") .build(), - new StreamObserver() { - @Override - public void onNext(net.firedevops.firemud.account.v1.LinkExternalAccountResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + observer); - assertNotNull(ref.get()); - assertFalse(ref.get().getSuccess()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertFalse(observer.response().getSuccess()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); } @Test - void requestEmailVerificationRejectsZeroAccountIdBeforeDispatch() { + void requestEmailVerificationDeniesMalformedSelectorBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = + new RecordingObserver<>(); - AtomicReference ref = - new AtomicReference<>(); service.requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.newBuilder() .setAccountId("0") .build(), - new StreamObserver() { - @Override - public void onNext( - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); + observer); - assertNotNull(ref.get()); - assertFalse(ref.get().getSuccess()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be a canonical non-nil UUID", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(accountService); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertFalse(observer.response().getSuccess()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); } - @ParameterizedTest - @MethodSource("accountUuidReadbackFailures") - void exportAccountSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { - AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); - AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService); + @Test + void exportAccountDeniesAbsentRequestBeforeOwnerLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); RecordingObserver observer = new RecordingObserver<>(); - service.exportAccount( - ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), observer); + service.exportAccount(null, observer); - assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); - Mockito.verify(accountService, Mockito.never()).exportAccountData(Mockito.anyLong()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertTrue(observer.response().getAccountJson().isEmpty()); + assertTrue(observer.response().getProfilesJson().isEmpty()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); } - @ParameterizedTest - @MethodSource("accountUuidReadbackFailures") - void exportTenantDataSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { - AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); + @Test + void exportTenantDataDeniesAbsentSelectorsBeforeOwnerLookup() { + AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(Mockito.mock(PingService.class), accountService); RecordingObserver observer = new RecordingObserver<>(); - service.exportTenantData( - ExportTenantDataRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), - observer); + service.exportTenantData(ExportTenantDataRequest.getDefaultInstance(), observer); - assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); - Mockito.verify(accountService, Mockito.never()) - .exportTenantData(Mockito.anyLong(), Mockito.anyLong()); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertTrue(observer.response().getTenantId().isEmpty()); + assertTrue(observer.response().getAccountJson().isEmpty()); + assertTrue(observer.response().getProfileJson().isEmpty()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService); } @ParameterizedTest @@ -2816,36 +3056,33 @@ void deleteAccountSanitizesUnavailableAccountUuidReadback(RuntimeException failu Mockito.verify(accountService, Mockito.never()).deleteAccount(Mockito.anyLong()); } - @ParameterizedTest - @MethodSource("accountUuidReadbackFailures") - void linkExternalAccountSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { - AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); - AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService); + @Test + void linkExternalAccountDeniesAbsentSelectorsBeforeOwnerLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); RecordingObserver observer = new RecordingObserver<>(); service.linkExternalAccount( - net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() - .setTenantId("1") - .setAccountId(ACCOUNT_UUID) - .setProvider("google") - .setExternalId("external-1") - .build(), + net.firedevops.firemud.account.v1.LinkExternalAccountRequest.getDefaultInstance(), observer); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); assertFalse(observer.response().getSuccess()); - assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); - Mockito.verify(accountService, Mockito.never()).linkExternalAccount(Mockito.any()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); } - @ParameterizedTest - @MethodSource("accountUuidReadbackFailures") - void requestEmailVerificationSanitizesUnavailableAccountUuidReadback(RuntimeException failure) { - AccountService accountService = accountServiceWithUnavailableAccountUuidReadback(failure); - AccountGrpcService service = - new AccountGrpcService(Mockito.mock(PingService.class), accountService); + @Test + void requestEmailVerificationDeniesCanonicalSelectorBeforeOwnerLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); RecordingObserver observer = new RecordingObserver<>(); @@ -2855,10 +3092,36 @@ void requestEmailVerificationSanitizesUnavailableAccountUuidReadback(RuntimeExce .build(), observer); + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); assertFalse(observer.response().getSuccess()); - assertAccountUuidReadbackUnavailable(observer, observer.response().getError()); - Mockito.verify(accountService).resolveAccountStorageId(UUID.fromString(ACCOUNT_UUID)); - Mockito.verify(accountService, Mockito.never()).requestEmailVerification(Mockito.anyLong()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); + } + + @Test + void requestEmailVerificationDeniesAbsentSelectorBeforeOwnerLookup() { + PingService pingService = Mockito.mock(PingService.class); + AccountService accountService = Mockito.mock(AccountService.class); + AccountGrpcService service = new AccountGrpcService(pingService, accountService); + RecordingObserver observer = + new RecordingObserver<>(); + + service.requestEmailVerification( + net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.getDefaultInstance(), + observer); + + assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); + assertEquals( + "No authorized internal caller is configured", observer.response().getError().getMessage()); + assertFalse(observer.response().getSuccess()); + assertEquals(1, observer.nextCalls); + assertEquals(1, observer.completedCalls); + assertFalse(observer.receivedTransportError()); + Mockito.verifyNoInteractions(accountService, pingService); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 8993441a4f..030cdb497a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -6316,17 +6316,118 @@ void requestEmailVerificationByEmailContainsDeliveryFailureAfterSavingToken() { } @Test - void verifyEmailSetsFlag() { + void verifyEmailClaimsTokenBeforeSavingOnlyTheFreshLockedAccount() { + EmailVerificationToken token = emailVerificationToken(); Account account = new Account(); - EmailVerificationToken token = new EmailVerificationToken(); - token.setAccount(account); - token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); - when(emailVerificationTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + account.setId(1L); + account.setAccountUuid(UUID.randomUUID()); + account.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + account.setAccountUuidSourceNumericId(1L); + account.setUsername("current-name"); + account.setEmail("current@example.com"); + account.setPasswordHash("current-password"); + account.setRole("player"); + account.setLoginAuthModes("PASSWORD"); + Account expected = new Account(); + org.springframework.beans.BeanUtils.copyProperties(account, expected); + expected.setEmailVerified(true); + when(accountRepository.findByIdForUpdate(1L)).thenReturn(Optional.of(account)); + when(emailVerificationTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), org.mockito.ArgumentMatchers.any())) + .thenReturn(true); service.verifyEmail(new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok")); - assertTrue(account.isEmailVerified()); - org.mockito.Mockito.verify(emailVerificationTokenRepository).delete(token); + assertEquals(expected, account); + assertFalse(token.getAccount().isEmailVerified()); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(emailVerificationTokenRepository, accountRepository); + order.verify(emailVerificationTokenRepository).findByToken("tok"); + order.verify(accountRepository).findByIdForUpdate(1L); + order + .verify(emailVerificationTokenRepository) + .consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), org.mockito.ArgumentMatchers.any()); + order.verify(accountRepository).save(account); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .delete(org.mockito.ArgumentMatchers.any()); + } + + @Test + void verifyEmailRejectsLostOrChangedTokenClaimBeforeAccountMutation() { + EmailVerificationToken token = emailVerificationToken(); + Account current = new Account(); + current.setId(1L); + when(accountRepository.findByIdForUpdate(1L)).thenReturn(Optional.of(current)); + when(emailVerificationTokenRepository.consumeIfUnexpired( + org.mockito.ArgumentMatchers.eq(token), org.mockito.ArgumentMatchers.any())) + .thenReturn(false); + + assertThrows( + IllegalArgumentException.class, + () -> + service.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok"))); + + assertFalse(current.isEmailVerified()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void verifyEmailRejectsExpiredAndExactlyExpiringTokenAfterAccountLock(boolean equality) { + EmailVerificationToken token = emailVerificationToken(); + java.time.LocalDateTime now = java.time.LocalDateTime.of(2026, 11, 1, 12, 0); + token.setExpiresAt(equality ? now : now.minusNanos(1)); + Account current = new Account(); + current.setId(1L); + when(accountRepository.findByIdForUpdate(1L)).thenReturn(Optional.of(current)); + + try (org.mockito.MockedStatic clock = + org.mockito.Mockito.mockStatic( + java.time.LocalDateTime.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { + clock.when(java.time.LocalDateTime::now).thenReturn(now); + assertThrows( + IllegalArgumentException.class, + () -> + service.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok"))); + } + + assertFalse(current.isEmailVerified()); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) + .save(org.mockito.ArgumentMatchers.any()); + } + + @Test + void verifyEmailRejectsMalformedTokenOwnerBeforeLockOrMutation() { + EmailVerificationToken token = emailVerificationToken(); + token.getAccount().setId(null); + + assertThrows( + IllegalArgumentException.class, + () -> + service.verifyEmail( + new net.firedevops.firemud.accountservice.dto.VerifyEmailRequest("tok"))); + + verifyNoInteractions(accountRepository); + org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) + .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); + } + + private EmailVerificationToken emailVerificationToken() { + Account locator = new Account(); + locator.setId(1L); + EmailVerificationToken token = new EmailVerificationToken(); + token.setId(9L); + token.setToken("tok"); + token.setAccount(locator); + token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); + when(emailVerificationTokenRepository.findByToken("tok")).thenReturn(Optional.of(token)); + return token; } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java index 93c652916c..98c097822a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java @@ -5,7 +5,8 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; -import java.util.concurrent.atomic.AtomicReference; +import java.util.ArrayList; +import java.util.List; import net.firedevops.firemud.account.v1.AddCurrencyRequest; import net.firedevops.firemud.account.v1.AddCurrencyResponse; import net.firedevops.firemud.account.v1.GetBalanceRequest; @@ -18,162 +19,103 @@ class VirtualCurrencyGrpcServiceTest { @Test - void getBalanceReturnsResponse() { + void getBalanceFailsClosedForRepeatedValidRequestsWithoutReadingBalance() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - Mockito.when(currencyService.getBalance(1L, 2L, "GOLD")).thenReturn(123L); VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + List responses = new ArrayList<>(); - AtomicReference ref = new AtomicReference<>(); - service.getBalance( + StreamObserver observer = collecting(responses); + GetBalanceRequest request = GetBalanceRequest.newBuilder() .setTenantId("1") - .setAccountId("2") + .setAccountId("11111111-1111-4111-8111-111111111111") .setCurrencyCode("GOLD") - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetBalanceResponse value) { - ref.set(value); - } + .build(); + service.getBalance(request, observer); + service.getBalance(request, observer); - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertEquals(123L, ref.get().getBalance()); - } - - @Test - void getBalanceRuntimeFailureReturnsInternalErrorDetail() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - Mockito.when(currencyService.getBalance(1L, 2L, "GOLD")) - .thenThrow(new IllegalStateException("boom")); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.getBalance( - GetBalanceRequest.newBuilder() - .setTenantId("1") - .setAccountId("2") - .setCurrencyCode("GOLD") - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetBalanceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INTERNAL", ref.get().getError().getCode()); - } - - @Test - void getBalanceRejectsZeroTenantIdBeforeLookup() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.getBalance( - GetBalanceRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") - .setCurrencyCode("GOLD") - .build(), - new StreamObserver<>() { - @Override - public void onNext(GetBalanceResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); + assertUnavailable(responses, "GetBalance is unavailable"); Mockito.verifyNoInteractions(currencyService); } @Test - void addCurrencyRejectsZeroAccountIdBeforeMutation() { + void addCurrencyFailsClosedForRepeatedValidRequestsWithoutAddingCurrency() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + List responses = new ArrayList<>(); - AtomicReference ref = new AtomicReference<>(); - service.addCurrency( + StreamObserver observer = collecting(responses); + AddCurrencyRequest request = AddCurrencyRequest.newBuilder() .setTenantId("1") - .setAccountId("0") + .setAccountId("11111111-1111-4111-8111-111111111111") .setCurrencyCode("GOLD") .setAmount(10) - .build(), - new StreamObserver<>() { - @Override - public void onNext(AddCurrencyResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} + .build(); + service.addCurrency(request, observer); + service.addCurrency(request, observer); - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("accountId must be positive", ref.get().getError().getMessage()); + assertUnavailable(responses, "AddCurrency is unavailable"); Mockito.verifyNoInteractions(currencyService); } @Test - void spendCurrencyRejectsZeroTenantIdBeforeSpend() { + void spendCurrencyFailsClosedForRepeatedValidRequestsWithoutSpendingCurrency() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + List responses = new ArrayList<>(); - AtomicReference ref = new AtomicReference<>(); - service.spendCurrency( + StreamObserver observer = collecting(responses); + SpendCurrencyRequest request = SpendCurrencyRequest.newBuilder() - .setTenantId("0") - .setAccountId("2") + .setTenantId("1") + .setAccountId("11111111-1111-4111-8111-111111111111") .setCurrencyCode("GOLD") .setAmount(5) - .build(), - new StreamObserver<>() { - @Override - public void onNext(SpendCurrencyResponse value) { - ref.set(value); - } + .build(); + service.spendCurrency(request, observer); + service.spendCurrency(request, observer); - @Override - public void onError(Throwable t) {} + assertUnavailable(responses, "SpendCurrency is unavailable"); + Mockito.verifyNoInteractions(currencyService); + } - @Override - public void onCompleted() {} - }); + private static StreamObserver collecting(List responses) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + responses.add(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError("Expected an application-level fail-closed response", error); + } + + @Override + public void onCompleted() {} + }; + } - assertNotNull(ref.get()); - assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); - assertEquals("tenantId must be positive", ref.get().getError().getMessage()); - Mockito.verifyNoInteractions(currencyService); + private static void assertUnavailable(List responses, String message) { + assertEquals(2, responses.size()); + for (Object response : responses) { + assertNotNull(response); + if (response instanceof GetBalanceResponse getBalanceResponse) { + assertEquals("FAILED_PRECONDITION", getBalanceResponse.getError().getCode()); + assertEquals(message, getBalanceResponse.getError().getMessage()); + } else if (response instanceof AddCurrencyResponse addCurrencyResponse) { + assertEquals("FAILED_PRECONDITION", addCurrencyResponse.getError().getCode()); + assertEquals(message, addCurrencyResponse.getError().getMessage()); + } else if (response instanceof SpendCurrencyResponse spendCurrencyResponse) { + assertEquals("FAILED_PRECONDITION", spendCurrencyResponse.getError().getCode()); + assertEquals(message, spendCurrencyResponse.getError().getMessage()); + } else { + throw new AssertionError("Unexpected response type: " + response.getClass()); + } + } } } From 0d47422f71b1ea4a405f1b58838b60cf3952557e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 06:18:27 +1300 Subject: [PATCH 04/16] Record current Account containment held-smoke qualification --- .../implementation-tracking/player-access-and-session.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index a28bf79088..d7d95f8f41 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -646,12 +646,14 @@ Shared coordination state carries reconnect/connect-context tracking, disconnect ### Account email verification and deferred currency containment -Local receiving work for #2848 prepares the [Account-owned email confirmation boundary](../../architecture/microservices/account-service/runtime-and-data.md#email-and-notification-design): an exact still-valid token claim and a fresh locked Account/source update share one transaction. It preserves current UUID and source-baseline guards and the stronger password-reset owner. The deferred `GetBalance`, `AddCurrency` and `SpendCurrency` RPCs now refuse before balance/service access, in line with the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis). R1416 passes eight focused unit cases and six actual PostgreSQL/Spring cases, with zero failures, errors or skips, plus selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Account packaging. The database cases cover single-use races, strict expiry, exact-token changes, owner/source rollback and preservation of a separately committed current Account update. Its missing-baseline fixture is a synthetic retained-style row, not historical migration proof. Fresh source-built runtime qualification remains pending. The remaining #2848 JOIN reconciliation, receipt and caller-proof obligations are separate and incomplete. This correction changes no JOIN expiry policy, activates no unsupported commerce and makes no complete Account recovery claim. +Local receiving work for #2848 prepares the [Account-owned email confirmation boundary](../../architecture/microservices/account-service/runtime-and-data.md#email-and-notification-design): an exact still-valid token claim and a fresh locked Account/source update share one transaction. It preserves current UUID and source-baseline guards and the stronger password-reset owner. The deferred `GetBalance`, `AddCurrency` and `SpendCurrency` RPCs now refuse before balance/service access, in line with the [Account API contract](../../architecture/microservices/account-service/api-contracts.md#grpc-apis). R1416 passes eight focused unit cases and six actual PostgreSQL/Spring cases, with zero failures, errors or skips, plus selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Account packaging. The database cases cover single-use races, strict expiry, exact-token changes, owner/source rollback and preservation of a separately committed current Account update. Its missing-baseline fixture is a synthetic retained-style row, not historical migration proof. The later R1418 held-smoke result below supplies fresh local runtime qualification. The remaining #2848 JOIN reconciliation, receipt and caller-proof obligations are separate and incomplete. This correction changes no JOIN expiry policy, activates no unsupported commerce and makes no complete Account recovery claim. -R1418 additionally contains the legacy account-targeted `ExportTenantData` gRPC before selector parsing or owner reads; five focused gRPC/REST cases pass, with the separate REST/service authorization retained. The local Helm namespace render and development-certificate retention contracts pass, together with scoped ShellCheck and documentation checks. New credential receivers use exact Game Session certificate identity for OTP and the separately gated [Account-local Entity demo fixture](../../architecture/microservices/account-service/api-contracts.md#legacy-credential-rpc-and-local-demo-fixture) for Authenticate only. The first credential aggregate fails a missing test assertion import before test execution. Its corrected source passes 162 fresh Account cases, including eleven physical loopback-mTLS cases with a mocked credential owner; six unchanged Entity demo cases are up to date, not fresh executions. Subsequent main/test analysis recoveries pass after removing an unnecessary constructor suppression and retaining the channel shutdown return value; the eleven physical cases pass again without failures, errors or skips. These are separate scoped results across retained failed aggregates, not one complete Account suite or genuine credential verification. Fresh source-built held smoke remains pending. +R1418 additionally contains the legacy account-targeted `ExportTenantData` gRPC before selector parsing or owner reads; five focused gRPC/REST cases pass, with the separate REST/service authorization retained. The local Helm namespace render and development-certificate retention contracts pass, together with scoped ShellCheck and documentation checks. New credential receivers use exact Game Session certificate identity for OTP and the separately gated [Account-local Entity demo fixture](../../architecture/microservices/account-service/api-contracts.md#legacy-credential-rpc-and-local-demo-fixture) for Authenticate only. The first credential aggregate fails a missing test assertion import before test execution. Its corrected source passes 162 fresh Account cases, including eleven physical loopback-mTLS cases with a mocked credential owner; six unchanged Entity demo cases are up to date, not fresh executions. Subsequent main/test analysis recoveries pass after removing an unnecessary constructor suppression and retaining the channel shutdown return value; the eleven physical cases pass again without failures, errors or skips. These are separate scoped results across retained failed aggregates, not one complete Account suite or genuine credential verification. The later R1418 held-smoke result below supplies the current local runtime result. The same local containment suspends the unused `ExportAccount`, caller-asserted `LinkExternalAccount` and Account-ID `RequestEmailVerification` gRPC adapters before request parsing or owner access. Target export/link capabilities and an authorized internal verification-initiation caller remain incomplete. Separately authorized REST/service exports, neutral email-based initiation and the stronger token-based reset/verification owners remain. The combined current gate passes all 172 selected cases (163 Account unit/loopback cases, including eleven physical mTLS and six actual-profile HTTP wiring cases, plus nine actual PostgreSQL/Spring cases) with zero failures, errors or skips, selected main/test/integration static analysis, full formatting, fresh packaging and documentation checks. The three public-v1 JOIN cases prove actual commit followed by lost acknowledgement/readback, rollback followed by same-original continuation, and unchanged retained committed evidence after scope expiry. Controlled routing/caller inputs and injected failures establish no deployed RPC recovery or production authority. Public POST verification is selected by actual base/prod YAML; GET supplies no verification route or bypass. The email-link/browser handoff remains outside this local API proof. +R1418 subsequently carries published #3365 parent `1d2b862ea5a176f9c7e08dd3a0d76ee2056b9503` into local receiving source `863797ec59361deee0225a40804dcdaf08fd0d86` and freshly rebuilds jars and images for the canonical held-admission smoke. The direct backend LOGIN → PLAY → LOOK proof and Gateway/Telnet denial qualification pass; authenticated teardown succeeds, and independent exact-project checks find no containers, networks or volumes. This qualifies the bounded local Entity credential fixture and current contained startup, not successful public Gateway/Telnet admission, production credential authority, audit delivery, unknown-outcome observation or lawful release. The 172-case aggregate above retains its earlier code-source attribution; the inherited direct-text carry does not change those Account implementation or test bytes. + Current writer inspection also narrows the retained JOIN recovery gap: the public owner commits membership, transition audit and its terminal together after a separate durable intent. Unknown acknowledgement can leave either that intent without membership effects or a complete terminal; it does not establish the donor's manufactured positive-PENDING state. A lost committed result may remain unobservable after scope expiry, changed replay policy or lost caller binding. Same-original retry and this later outcome-observation limitation require distinct proof; the existing unknown-recovery and lawful-release holds remain. The proposed audit projection-version marker likewise has no implemented Logging receipt/projection producer here and must not be inferred from receiver IDs, payload replay or stamped test rows. No historical producer provenance, new receiver, recovery RPC or release authority is supplied. ### Fail-Closed Boundary Convergence From 6c63d7454688e8544783fb3e57fbf1a5d31c1459 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:36:21 +1300 Subject: [PATCH 05/16] Retry transient local demo owner authentication before Entity seeding --- .../runtime-and-data.md | 2 + design/project-management/ai-observations.md | 3 + .../player-access-and-session.md | 2 + .../DemoAccountAuthenticationClient.java | 53 +++++- .../DemoAccountAuthenticationClientTest.java | 146 +++++++++++++++ ...emoAccountAuthenticationTransportTest.java | 173 ++++++++++++++++++ 6 files changed, 370 insertions(+), 9 deletions(-) create mode 100644 services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationTransportTest.java diff --git a/design/architecture/microservices/entity-management-service/runtime-and-data.md b/design/architecture/microservices/entity-management-service/runtime-and-data.md index 3811ee1653..09ea58ca5c 100644 --- a/design/architecture/microservices/entity-management-service/runtime-and-data.md +++ b/design/architecture/microservices/entity-management-service/runtime-and-data.md @@ -7,6 +7,8 @@ This document defines Entity Management’s runtime model, persistence ownership - Ordinary Account ownership uses the existing `characters.account_uuid` carrier; V1024 permits fresh ordinary rows without fabricated numeric source evidence and adds an ordinary UUID roster index. It leaves retained numeric/unresolved rows unchanged and does not promote canonical actor provenance. Representation and admission consequences belong to [API Contracts](./api-contracts.md#ordinary-account-ownership); implementation/proof status belongs to the [Entity tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#ordinary-account-uuid-ownership). - Explicit local demo seeding authenticates the actual demo credentials through the normal Account mTLS `Authenticate` API and takes its canonical UUID response. Account separately enables its narrowly gated [local credential fixture](../account-service/api-contracts.md#legacy-credential-rpc-and-local-demo-fixture); Entity seed enablement alone grants no receiving authority, OTP access or general credential permission. It fails on unavailable identity or a retained demo character with missing/different UUID ownership, without repairing ownership by name or numeric row. The mTLS Compose profile starts Entity after Account health. This fixture operation grants no production registration, creation or admission authority. +The explicitly enabled local demo owner-authentication client makes at most three Account calls, each with the existing five-second deadline and a 250 ms delay between attempts. Only transport `UNAVAILABLE` and `DEADLINE_EXCEEDED` may retry; domain credential failures, authorization refusal and invalid returned ownership still fail before Entity seeding. Interruption and exhausted retries abort startup without substituting an identity. This is bounded fixture startup resilience, not production authentication or permission to rewrite retained owners. + - The current crafting REST adapter is runtime-reachable legacy implementation drift, not a supported or advertised boundary: the crafting paths and schemas are omitted from the ping-only authoritative OpenAPI, whose root `security: []` applies only to the health contract, so the adapter remains unsupported/nonconformant. The deployed interceptor requires any `AUTHENTICATED` bearer because this non-public path is not in the public-route list, but neither layer provides tenant binding; there is no controller `SessionContext` tenant guard. `CraftingServiceImpl` trusts the DTO's `tenantId`, `resultItemId`, and ingredient item IDs; `CraftingRecipeRepository.findWithIngredientsById` and the update branch use recipe ID alone, while ingredient loading also uses recipe ID alone. The tenant-qualified list methods first select IDs but then re-enter that unqualified lookup, so they are not evidence of an end-to-end tenant predicate. Existing crafting tests do not establish caller-tenant authorization, cross-tenant recipe isolation, or same-tenant result/ingredient ownership. - World owns guarded, manually composed initial `character_location` storage and its unregistered placement/read boundary. General movement, occupancy and NPC location remain unqualified; `room_instance` is topology, and a Game Session room binding is not World location authority. Entity Management must not add competing location persistence or treat a cache/projection as authoritative. - **Target crafting boundary:** require authenticated caller context and exact tenant authorization before any recipe operation, derive the target tenant rather than treating request `tenantId` as authority, and make recipe read/update and ingredient load/update predicates tenant-qualified. Validate that the result item and every ingredient item belong to the target tenant and the same applicable version/Draft scope before writing. A missing context, tenant mismatch, recipe mismatch, or cross-tenant item reference fails closed before any recipe or ingredient mutation; the target negative proof must exercise each case. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 420a4e383f..20a1a4dec7 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -13,3 +13,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): API helper inputs and reply-file shape required local recovery. - A read-only helper correctly refused its supplied external proof directory. Root copied and hash-verified the authorized inputs inside the worktree, without changing permissions, then resumed it. The reply command help omitted the required JSON array-of-string-arrays shape, so Root read its validator to construct the response. Next: add a concise help example in the owning API wrapper; this was reported to Overseer and is not a repository runtime blocker. + +- `2026-11-01` (Pacific/Auckland): A transient demo-owner authentication deadline terminated Entity startup. + - #3367 runtime-images run `41227037637` failed after Entity’s single five-second Account call expired; Entity exited and held smoke observed missing health, while matching local source-built smoke had passed. Complete job logs identify the startup deadline, not an authorization rejection or image-profile mismatch. Thirteen focused cases now qualify bounded transient-only fixture retries, including a real loopback deadline/cancellation regression; fresh image-lane proof remains pending. The underlying cold-start latency remains unknown; recurrence evidence and the exact run were reported to Overseer for tracking. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7ff5ae6d87..401809bb07 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -770,3 +770,5 @@ No competing target state is currently recorded. Future design discussion is req | Social Groups and Automation | Authenticated gameplay-adjacent communication/presence and runtime script/event admission using the same identity/routing guardrails | Positive-ID/current-account readers; gameplay routing bundles; canonical REST/gRPC error envelopes | | Logging & Admin | Authenticated operator/control-plane reads, mutation/remediation actor identity, audit and response projection; StartSession compares and persists the Account-returned owner tuple for handoff | Control-plane client readers; `ApiResponse` REST boundary; owner-tuple consequence in [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | | Game Logic | Current-state command aggregation after recovery; currently stateless `LOOK`, movement-derived room context, and communication fan-out inputs | Post-restart gameplay command paths backed by shared world/session state | + +The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled demo owner-authentication call reaches its single five-second Account deadline, after which the startup runner exits. The image and source profiles retain the configured Account receiving fixture; no credential or authorization rejection is established for that call. The local correction bounds transient transport retries while preserving the existing exact mTLS, credential, token and canonical Account UUID checks and fail-closed seeding. R1421 passes thirteen focused cases, including a real loopback mTLS deadline/cancellation followed by successful retry, permanent-error and interruption refusal, and fail-closed seeding. Enabled affected static analysis, full formatting, Entity packaging and documentation checks pass. The physical Account owner is a controlled stub; fresh image-lane runtime requalification remains pending, and the underlying cold-start latency is not explained by this resilience correction. diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java index 1545213011..e5cad77f30 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClient.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.entitymanagement.client; import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import jakarta.annotation.PostConstruct; import jakarta.annotation.PreDestroy; import java.io.IOException; @@ -15,6 +17,8 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.security.JwtClaims; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Lazy; @@ -29,6 +33,10 @@ @Lazy public final class DemoAccountAuthenticationClient extends AbstractReloadingBlockingGrpcClient { + private static final Logger logger = + LoggerFactory.getLogger(DemoAccountAuthenticationClient.class); + private static final int MAX_AUTHENTICATION_ATTEMPTS = 3; + private static final long RETRY_DELAY_MILLIS = 250; private final String namespace; private final String email; private final String password; @@ -79,16 +87,43 @@ protected AccountServiceGrpc.AccountServiceBlockingStub buildStub(ManagedChannel } public UUID authenticateDemoOwner() { - var response = - requireInitializedStub("Demo Account client is not initialized") - .withDeadlineAfter(5, TimeUnit.SECONDS) - .authenticate( - AuthenticateRequest.newBuilder().setEmail(email).setPassword(password).build()); - if (response.hasError() || response.getAuthToken().isBlank()) { - throw new IllegalStateException("Account demo authentication is unavailable"); + var request = AuthenticateRequest.newBuilder().setEmail(email).setPassword(password).build(); + for (int attempt = 1; ; attempt++) { + if (Thread.currentThread().isInterrupted()) { + throw new IllegalStateException("Account demo authentication interrupted"); + } + try { + var response = + requireInitializedStub("Demo Account client is not initialized") + .withDeadlineAfter(5, TimeUnit.SECONDS) + .authenticate(request); + if (response.hasError() || response.getAuthToken().isBlank()) { + throw new IllegalStateException("Account demo authentication is unavailable"); + } + return UUID.fromString( + JwtClaims.requireCanonicalAccountUuid(response.getAccountId(), "accountId")); + } catch (StatusRuntimeException ex) { + Status.Code code = ex.getStatus().getCode(); + if (attempt >= MAX_AUTHENTICATION_ATTEMPTS + || (code != Status.Code.UNAVAILABLE && code != Status.Code.DEADLINE_EXCEEDED)) { + throw ex; + } + if (Thread.currentThread().isInterrupted()) { + throw new IllegalStateException("Account demo authentication interrupted", ex); + } + logger.warn( + "Local demo Account authentication transport retry after attempt {}/{} status={}", + attempt, + MAX_AUTHENTICATION_ATTEMPTS, + code); + try { + Thread.sleep(RETRY_DELAY_MILLIS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Account demo authentication interrupted", interrupted); + } + } } - return UUID.fromString( - JwtClaims.requireCanonicalAccountUuid(response.getAccountId(), "accountId")); } @Override diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java index c03754c23f..167ce139ea 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java @@ -4,10 +4,13 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.*; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; import java.lang.reflect.Field; import java.util.UUID; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; @@ -15,6 +18,7 @@ import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.entitymanagement.client.DemoAccountAuthenticationClient; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; @@ -49,6 +53,148 @@ void usesCredentialAuthenticationAndExactReturnedUuidWithoutNumericIdentity() th && request.getPassword().equals("swordfish"))); } + @Test + void retriesOnlyTransientTransportFailuresWithTheSameCredentialRequest() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + UUID owner = UUID.randomUUID(); + when(stub.authenticate(any())) + .thenThrow(Status.UNAVAILABLE.asRuntimeException()) + .thenThrow(Status.DEADLINE_EXCEEDED.asRuntimeException()) + .thenReturn( + AuthenticateResponse.newBuilder() + .setAccountId(owner.toString()) + .setAuthToken("ordinary-fixture-token") + .build()); + + assertThat(client(stub).authenticateDemoOwner()).isEqualTo(owner); + + var requests = ArgumentCaptor.forClass(AuthenticateRequest.class); + verify(stub, times(3)).authenticate(requests.capture()); + verify(stub, times(3)).withDeadlineAfter(5, TimeUnit.SECONDS); + assertThat(requests.getAllValues()) + .allSatisfy( + request -> { + assertThat(request).isSameAs(requests.getValue()); + assertThat(request.getEmail()).isEqualTo("demo@example.com"); + assertThat(request.getPassword()).isEqualTo("swordfish"); + }); + } + + @Test + void propagatesFinalTransientFailureAfterThreeCalls() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + var failure = Status.DEADLINE_EXCEEDED.asRuntimeException(); + when(stub.authenticate(any())).thenThrow(failure); + var client = client(stub); + + assertThatThrownBy(client::authenticateDemoOwner).isSameAs(failure); + + verify(stub, times(3)).authenticate(any()); + } + + @Test + void refusesPermanentAuthorizationStatusesWithoutRetry() throws Exception { + for (Status status : new Status[] {Status.PERMISSION_DENIED, Status.UNAUTHENTICATED}) { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + var failure = status.asRuntimeException(); + when(stub.authenticate(any())).thenThrow(failure); + var client = client(stub); + + assertThatThrownBy(client::authenticateDemoOwner) + .isInstanceOf(StatusRuntimeException.class) + .isSameAs(failure); + + verify(stub).authenticate(any()); + } + } + + @Test + void refusesCredentialErrorsAndMissingTokensWithoutRetry() throws Exception { + for (AuthenticateResponse response : + new AuthenticateResponse[] { + AuthenticateResponse.newBuilder() + .setError( + net.firedevops.firemud.shared.v1.ErrorDetail.newBuilder() + .setCode("AUTH_INVALID_CREDENTIALS")) + .build(), + AuthenticateResponse.newBuilder().setAccountId(UUID.randomUUID().toString()).build() + }) { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.authenticate(any())).thenReturn(response); + var client = client(stub); + + assertThatThrownBy(client::authenticateDemoOwner).isInstanceOf(IllegalStateException.class); + + verify(stub).authenticate(any()); + } + } + + @Test + void interruptionStopsRetryAndPreservesInterruptWithoutReturningAnOwner() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.authenticate(any())) + .thenAnswer( + invocation -> { + Thread.currentThread().interrupt(); + throw Status.UNAVAILABLE.asRuntimeException(); + }); + var client = client(stub); + try { + assertThatThrownBy(client::authenticateDemoOwner) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account demo authentication interrupted"); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + verify(stub).authenticate(any()); + verify(stub).withDeadlineAfter(5, TimeUnit.SECONDS); + assertThatThrownBy(client::authenticateDemoOwner) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account demo authentication interrupted"); + verifyNoMoreInteractions(stub); + } finally { + Thread.interrupted(); + } + } + + @Test + void interruptedFixtureAuthenticationCannotReachOwnerMutation() throws Exception { + var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); + var characters = + mock(net.firedevops.firemud.entitymanagement.repository.CharacterRepository.class); + var items = mock(net.firedevops.firemud.entitymanagement.repository.ItemRepository.class); + var itemInstances = + mock(net.firedevops.firemud.entitymanagement.repository.ItemInstanceRepository.class); + var containers = + mock(net.firedevops.firemud.entitymanagement.repository.ContainerInstanceRepository.class); + var equipmentSlots = + mock( + net.firedevops.firemud.entitymanagement.repository.EquipmentSlotDefinitionRepository + .class); + var bodySlots = + mock( + net.firedevops.firemud.entitymanagement.repository.BodyLayoutSlotDefinitionRepository + .class); + var seeder = + new net.firedevops.firemud.entitymanagement.data.TestDataSeeder( + client(stub), characters, items, itemInstances, containers, equipmentSlots, bodySlots); + Thread.currentThread().interrupt(); + try { + assertThatThrownBy( + () -> seeder.run(new org.springframework.boot.DefaultApplicationArguments())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account demo authentication interrupted"); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + verifyNoInteractions( + stub, characters, items, itemInstances, containers, equipmentSlots, bodySlots); + } finally { + Thread.interrupted(); + } + } + @Test void refusesUnavailableMalformedNilAndNoncanonicalOwners() throws Exception { var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationTransportTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationTransportTest.java new file mode 100644 index 0000000000..56bc1f1df5 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationTransportTest.java @@ -0,0 +1,173 @@ +package unit.net.firedevops.firemud.entitymanagement.client; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptors; +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.stub.ServerCallStreamObserver; +import io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AuthenticateRequest; +import net.firedevops.firemud.account.v1.AuthenticateResponse; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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.grpc.ResolvedGrpcTlsMaterial; +import net.firedevops.firemud.entitymanagement.client.DemoAccountAuthenticationClient; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.LoopbackMtlsTestPki.IdentitySpec; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** + * Physical deadline/retry proof with a controlled Account stub, not real credential-owner proof. + */ +class DemoAccountAuthenticationTransportTest { + private static final String NAMESPACE = "test"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final UUID OWNER = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); + private static final AuthenticateRequest REQUEST = + AuthenticateRequest.newBuilder() + .setEmail("demo@example.com") + .setPassword("controlled-fixture-password") + .build(); + + @TempDir static Path directory; + private static LoopbackMtlsTestPki.Pki pki; + + @BeforeAll + static void createLoopbackCertificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + directory, + "FireMUD demo authentication transport test CA", + new IdentitySpec("account", "spiffe://firemud/ns/test/sa/account-service", true), + new IdentitySpec("entity", ENTITY_URI, false)); + } + + @Test + @Timeout(20) + void realDeadlineCancelsFirstCallAndRetryReturnsOnlyTheExactAccountOwner() throws Exception { + var requests = new CopyOnWriteArrayList(); + var peers = new CopyOnWriteArrayList(); + var firstCancelled = new CountDownLatch(1); + var service = + new AccountServiceGrpc.AccountServiceImplBase() { + @Override + public void authenticate( + AuthenticateRequest request, StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + peers.add(peer == null ? "missing" : peer.uri()); + requests.add(request); + if (!ENTITY_URI.equals(peers.getLast()) || !REQUEST.equals(request)) { + observer.onError(io.grpc.Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (requests.size() == 1) { + // Leave the RPC open without blocking a server thread. The real client deadline + // must cancel it before the client can retry with a fresh five-second deadline. + ((ServerCallStreamObserver) observer) + .setOnCancelHandler(firstCancelled::countDown); + return; + } + observer.onNext( + AuthenticateResponse.newBuilder() + .setAccountId(OWNER.toString()) + .setAuthToken("controlled-fixture-token") + .build()); + observer.onCompleted(); + } + }; + var identity = pki.identity("account"); + try (var server = + new TransportServer( + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start()); + var channels = new CapturingChannelFactory()) { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + server.server().getPort()); + try (var client = + new DemoAccountAuthenticationClient( + endpoints, + pki.clientProperties(directory, pki.identity("entity")), + channels, + NAMESPACE, + REQUEST.getEmail(), + REQUEST.getPassword())) { + client.init(); + + assertThat(client.authenticateDemoOwner()).isEqualTo(OWNER); + + assertThat(firstCancelled.await(2, TimeUnit.SECONDS)).isTrue(); + assertThat(requests).hasSize(2); + assertThat(peers).containsExactly(ENTITY_URI, ENTITY_URI); + assertThat(requests) + .allSatisfy( + request -> assertThat(request.toByteArray()).isEqualTo(REQUEST.toByteArray())); + } + } + } + + private record TransportServer(Server server) implements AutoCloseable { + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + + /** Records channels produced by the real factory so teardown also checks physical termination. */ + private static final class CapturingChannelFactory extends GrpcChannelFactory + implements AutoCloseable { + private final List channels = new CopyOnWriteArrayList<>(); + + @Override + public ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive, + ResolvedGrpcTlsMaterial tlsMaterial) + throws SSLException { + ManagedChannel channel = + super.buildChannel(target, defaultPort, properties, keepAlive, tlsMaterial); + channels.add(channel); + return channel; + } + + @Override + public void close() throws InterruptedException { + channels.forEach(ManagedChannel::shutdownNow); + for (ManagedChannel channel : channels) { + assertThat(channel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + } + } + } +} From 4859ed01e0d4c0971fceaf7ad1feb3dac7d226d3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 07:46:26 +1300 Subject: [PATCH 06/16] Record fresh image smoke proof for Entity startup retry --- design/project-management/ai-observations.md | 2 +- .../implementation-tracking/player-access-and-session.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 20a1a4dec7..fd94d81979 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -15,4 +15,4 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - A read-only helper correctly refused its supplied external proof directory. Root copied and hash-verified the authorized inputs inside the worktree, without changing permissions, then resumed it. The reply command help omitted the required JSON array-of-string-arrays shape, so Root read its validator to construct the response. Next: add a concise help example in the owning API wrapper; this was reported to Overseer and is not a repository runtime blocker. - `2026-11-01` (Pacific/Auckland): A transient demo-owner authentication deadline terminated Entity startup. - - #3367 runtime-images run `41227037637` failed after Entity’s single five-second Account call expired; Entity exited and held smoke observed missing health, while matching local source-built smoke had passed. Complete job logs identify the startup deadline, not an authorization rejection or image-profile mismatch. Thirteen focused cases now qualify bounded transient-only fixture retries, including a real loopback deadline/cancellation regression; fresh image-lane proof remains pending. The underlying cold-start latency remains unknown; recurrence evidence and the exact run were reported to Overseer for tracking. + - #3367 runtime-images run `41227037637` failed after Entity’s single five-second Account call expired; Entity exited and held smoke observed missing health, while matching local source-built smoke had passed. Complete job logs identify the startup deadline, not an authorization rejection or image-profile mismatch. Thirteen focused cases now qualify bounded transient-only fixture retries, including a real loopback deadline/cancellation regression; fresh canonical image-lane held smoke at `6c63d74546` also passes, with independent empty-project cleanup. Remote replacement CI remains required. The underlying cold-start latency remains unknown; recurrence evidence and the exact run were reported to Overseer for tracking. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 401809bb07..de9a5fa937 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -771,4 +771,4 @@ No competing target state is currently recorded. Future design discussion is req | Logging & Admin | Authenticated operator/control-plane reads, mutation/remediation actor identity, audit and response projection; StartSession compares and persists the Account-returned owner tuple for handoff | Control-plane client readers; `ApiResponse` REST boundary; owner-tuple consequence in [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | | Game Logic | Current-state command aggregation after recovery; currently stateless `LOOK`, movement-derived room context, and communication fan-out inputs | Post-restart gameplay command paths backed by shared world/session state | -The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled demo owner-authentication call reaches its single five-second Account deadline, after which the startup runner exits. The image and source profiles retain the configured Account receiving fixture; no credential or authorization rejection is established for that call. The local correction bounds transient transport retries while preserving the existing exact mTLS, credential, token and canonical Account UUID checks and fail-closed seeding. R1421 passes thirteen focused cases, including a real loopback mTLS deadline/cancellation followed by successful retry, permanent-error and interruption refusal, and fail-closed seeding. Enabled affected static analysis, full formatting, Entity packaging and documentation checks pass. The physical Account owner is a controlled stub; fresh image-lane runtime requalification remains pending, and the underlying cold-start latency is not explained by this resilience correction. +The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled demo owner-authentication call reaches its single five-second Account deadline, after which the startup runner exits. The image and source profiles retain the configured Account receiving fixture; no credential or authorization rejection is established for that call. The local correction bounds transient transport retries while preserving the existing exact mTLS, credential, token and canonical Account UUID checks and fail-closed seeding. R1421 passes thirteen focused cases, including a real loopback mTLS deadline/cancellation followed by successful retry, permanent-error and interruption refusal, and fail-closed seeding. Enabled affected static analysis, full formatting, Entity packaging and documentation checks pass. The physical Account owner in that focused test is a controlled stub. Fresh canonical image-lane held smoke built all eleven applications from `6c63d7454688e8544783fb3e57fbf1a5d31c1459` and passed backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial; run-owned cleanup and independent exact-project checks found no remaining containers, networks or volumes. This runtime result does not establish successful public admission, production authority, or an explanation for the underlying cold-start latency. From a2cf2e4fb2f5abd08e703c4051e28dee64caec1e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:05:05 +1300 Subject: [PATCH 07/16] Address initial Account containment reviews and qualify certificate defaults --- .../account-service/api-contracts.md | 6 +- .../account-service/runtime-and-data.md | 4 +- design/project-management/ai-observations.md | 3 + .../player-access-and-session.md | 14 ++- dev-tools/certs/clean-dev-certs.sh | 2 +- dev-tools/certs/ensure-dev-certs.sh | 2 +- dev-tools/certs/generate-dev-certs.sh | 2 +- .../tests/dev-certs-retention-contract.sh | 78 +++++++++++++--- .../impl/VirtualCurrencyGrpcServiceTest.java | 93 ++++++++++++++++--- 9 files changed, 164 insertions(+), 40 deletions(-) diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index d92a42a6f2..20a1dce448 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -275,7 +275,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco | `POST` | `/auth/request-password-reset` | Request account-scoped password reset by normalized email with a neutral known/unknown response | | `POST` | `/auth/complete-password-reset` | Complete account-scoped password reset | | `POST` | `/auth/request-email-verification` | Send an account-scoped verification email selected by normalized email with a neutral known/unknown response; the public route accepts no numeric account selector | -| `POST` | `/auth/verify-email` | **Target public route; current bearer exception.** Verify an account-scoped email token. The current HTTP configurations allowlist only `GET /auth/verify-email` (which has no controller mapping), so the implemented `POST` route inherits bearer authentication until the public-route configuration is deliberately converged and proved. | +| `POST` | `/auth/verify-email` | **Current public route.** Verify an account-scoped email token without a bearer JWT. The configured verification email still links to `GET /auth/verify-email`, which has no controller mapping; browser handoff to the public POST remains unavailable. See the separate link-routing gap in [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | `POST` | `/auth/recover-username` | Send an account-scoped username reminder by normalized email with a neutral known/unknown response | | `POST` | `/accounts` | Create a global Account identity and platform-scoped audit outbox row; tenant membership and profile creation are separate operations. Legacy tenant input is not registration authority. | | `GET` | `/accounts/{accountId}/login-auth-modes` | Read primary login modes for the selected global Account; the current account selector is a canonical lowercase non-nil Account UUID. | @@ -317,7 +317,7 @@ Implemented Account-valued REST selectors and response fields use canonical Acco The listed Account UUID representation is implemented through the qualified ordinary receiving boundary, including Account-issued credentials, shared forwarding, caller-bound REST/profile use, and UUID-valued downstream Account references. Private numeric Account rows and the separate legacy numeric GameInstance owner/StartSession boundary remain distinct. Full token-profile/registry qualification, production custody and gameplay admission/activation remain held; proof status is in the [player-access implementation tracker](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving). -Current verification routing/auth status: `POST /auth/verify-email` inherits bearer authentication because both HTTP configurations allowlist only `GET /auth/verify-email`, while that allowlisted GET has no controller mapping; see the existing [verification-routing gap in Runtime and Data](./runtime-and-data.md#email-and-notification-design). +Current verification routing/auth status: base and production HTTP configurations allowlist public `POST /auth/verify-email`, which has no bearer requirement. The configured verification email remains a `GET /auth/verify-email` link with no controller mapping, and browser handoff to the public POST is not implemented; see the separate [verification-link routing gap in Runtime and Data](./runtime-and-data.md#email-and-notification-design). The legacy `GET /profiles/{accountId}?tenantId=...` and `PUT /profiles/{accountId}` handlers follow [Account UUID response and REST selector identity](#account-uuid-response-and-rest-selector-identity), including PUT path/body equality. They enforce exact UUID `SessionContext` self-binding before private owner resolution, retaining current tenant-membership checks (`gameplayAdmissionAllowed` is not required), public policy vocabulary checks, and post-commit update notification. Legacy PUT rejects `HIDDEN_STAFF` before persistence; a successful update stores the supplied selectable policy. Normalizing retained legacy policy to `PRIVATE` applies to read/export projection without rewriting that row, not acceptance of the retired policy on update. These selectors do not authorize another Account's profile or activate the canonical tenant-qualified route, scoped tenant roles, or membership-authority-generation checks. The legacy route and its route/policy shape remain implementation drift. @@ -355,7 +355,7 @@ Every tenant-targeted request identifies its tenant in the route or request cont | Surface | Examples | Required auth path | Notes | | --- | --- | --- | --- | -| Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. `POST /auth/verify-email` is target-public but is excluded from the current public allowlist and therefore requires a bearer under the current configuration; the allowlisted `GET` has no controller mapping. | +| Public auth/bootstrap | `/auth/login`, `/auth/request-password-reset`, `/auth/complete-password-reset`, `/auth/request-email-verification`, `/auth/verify-email`, `/auth/recover-username`, `/.well-known/jwks.json` | No pre-existing user JWT; endpoint-specific validation and abuse controls | Intended for initial auth/bootstrap flows. The public `POST /auth/verify-email` is configured, but the verification email's `GET /auth/verify-email` link has no controller mapping and no browser handoff to POST. See [Runtime and Data](./runtime-and-data.md#email-and-notification-design). | | Player bootstrap issuance | `/auth/player-bootstrap` | First-party player account authentication bootstrap | **Target state:** issues the `player-bootstrap` token profile only after atomically creating its one active `session:auth:token:` registry record; registry failure fails issuance before exposure. It must not return a `control-ui` JWT or perform tenant-scoped admission checks. It may share Account's credential verification, abuse controls, and account-state checks with `/auth/login`, but the endpoint, audience, claims, lifetime, and allowed surfaces remain distinct. **Current implementation:** uses the legacy `session:auth:account::` Account session key rather than the ADR 0035 registry shape. | | Player bootstrap | `/auth/bootstrap/worlds`, `/auth/bootstrap/worlds/{world}/realms`, `/auth/bootstrap/join`, `/auth/bootstrap/worlds/{world}/realms/{realm}/characters`, `/auth/connect-token` | Target first-party flow: short-lived, memory-only `player-bootstrap` token in `Authorization: Bearer ...` | The implemented bootstrap derives caller identity before tenant selection, then resolves tenant scope through realm discovery. World and realm discovery may show a public production target before membership exists; character discovery now requires the caller's current membership to exist and permit gameplay admission, and `/auth/bootstrap/join` has a local Account controller/operation for the explicit first-party open-enrollment writer. Character discovery consumes the opaque server-issued `connectScopeId`, verifies the route matches it, and revalidates its tenant/runtime target. Current `POST /auth/connect-token` validates bootstrap identity and scope binding, then returns `AUTH_UNAVAILABLE` before membership, entitlement, admission-pointer, or cached-result reads and token minting. The target character-creation route is not currently routable or implemented: it requires that exact `connectScopeId`, derives `playableStateScope` from the realm catalog/pointer snapshot, and delegates the scoped write to Entity Management `CreateCharacter`; it does not persist character state or accept a caller-selected scope. Later character and connect-token surfaces must require live membership plus applicable grant, entitlement, and pointer checks. `POST /auth/connect-token` must obtain the exact current caller-bound runtime membership snapshot at its issuance commit gate, including lifecycle state, independent membership version, and opaque authority generation; cached or bootstrap evidence cannot substitute even when its generation appears current. Target success delivery uses only the protected `Firemud-Connect-Token` `Set-Cookie` field; the HTTP response body and custom response-header fields are metadata-only. First-party browser/mobile-browser and first-party native-mobile or other first-party non-browser cookie-jar clients remain cookie-only. A separately registered route for explicitly classified public/non-first-party native-mobile and other non-browser clients returns the token once for protected secure storage and permits only the dedicated handshake header; it is not a browser endpoint or a cookie fallback. PostgreSQL exact-final-head, recovery/reconciliation, direct text end-to-end, and membership-generation proof remain open. | diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index c2436f53a7..0586f05eaa 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -348,11 +348,11 @@ Account owns the sole supported v1 Stripe integration for FireMUD hosting-plan b ### Email and Notification Design -This service sends verification and password reset emails using a configured SMTP provider. Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when a known-account post-commit SMTP send throws; those exceptions are caught and logged, while unknown requests create no token and schedule no email. **Current gap:** these sends still run synchronously after commit, so SMTP latency remains a timing oracle; durable asynchronous delivery is absent. Focused service tests prove exception containment, not timing resistance, HTTP-level timing parity, or durable delivery, so this is not full account-enumeration resistance. Public email-verification initiation no longer accepts a numeric account selector, while the internal gRPC method remains account-ID based. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). +This service sends verification and password reset emails using a configured SMTP provider. Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when a known-account post-commit SMTP send throws; those exceptions are caught and logged, while unknown requests create no token and schedule no email. **Current gap:** these sends still run synchronously after commit, so SMTP latency remains a timing oracle; durable asynchronous delivery is absent. Focused service tests prove exception containment, not timing resistance, HTTP-level timing parity, or durable delivery, so this is not full account-enumeration resistance. Public email-verification initiation no longer accepts a numeric account selector. The internal Account-ID gRPC initiation method currently returns `FAILED_PRECONDITION` before account lookup or mail dispatch because no authorized internal caller is configured; its retained request shape does not grant caller permission. Notifications for suspicious logins or account events are queued for asynchronous delivery via a gRPC `NotificationService`. Sample templates live under `resources/templates/` and environment variables configure `spring.mail.*` along with `firemud.mail.from`, `firemud.mail.verification-url`, and `firemud.mail.reset-url`. The Account-owned trusted-source context, distributed candidate/source throttles, and limiter-outage behavior from [ADR 0034](../../decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md) remain unimplemented, so neutral responses do not by themselves complete the abuse-control boundary. The gRPC API is defined in [`notification_service.proto`](../../../../protos/account/v1/notification_service.proto). Email verification uses the token association only to locate the Account, then locks the current complete Account row before claiming the exact original token. The conditional SQL consumption matches token row ID, opaque token, Account owner and original expiry, requiring expiry strictly after the captured process-local time. The claim and Account/source update share the writable owner transaction; losing, changed or expired claims cannot mutate Account state, and a failed source update rolls the claim back. Current password, role, email, login modes and UUID provenance come from that locked owner rather than the earlier partial token join. This preserves the existing local timestamp basis described above; it adds no cross-node timezone or retained-row migration claim. Focused implementation and proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-email-verification-and-deferred-currency-containment). -The configured default verification URL is a `GET /auth/verify-email` link while Account exposes verification as `POST /auth/verify-email`; the default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). The shipped defaults therefore do not route users to the canonical POST APIs ([Account API Contracts](./api-contracts.md#rest-apis)); deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live. +The configured default verification URL is a `GET /auth/verify-email` link, but Account exposes only `POST /auth/verify-email`; the GET has no controller mapping. Although the base and production HTTP configurations allow the POST as public, the configured mail link still requires an explicit browser handoff or matching GET handler to reach it. The default reset URL points to `/reset-password`, for which no Account route exists. The canonical Gateway forwards Account auth under `/api/account/auth/**` ([Gateway client behavior](../spring-cloud-gateway/client-behavior.md)). Deployment must provide an explicit web-client/edge handoff or matching handler, with link reachability proof, before recovery and verification are treated as end-to-end live; see the canonical route/auth contract in [Account API Contracts](./api-contracts.md#rest-apis). ## Original StartSession Source-Protection Storage diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index fd94d81979..acc9130285 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -16,3 +16,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): A transient demo-owner authentication deadline terminated Entity startup. - #3367 runtime-images run `41227037637` failed after Entity’s single five-second Account call expired; Entity exited and held smoke observed missing health, while matching local source-built smoke had passed. Complete job logs identify the startup deadline, not an authorization rejection or image-profile mismatch. Thirteen focused cases now qualify bounded transient-only fixture retries, including a real loopback deadline/cancellation regression; fresh canonical image-lane held smoke at `6c63d74546` also passes, with independent empty-project cleanup. Remote replacement CI remains required. The underlying cold-start latency remains unknown; recurrence evidence and the exact run were reported to Overseer for tracking. + +- `2026-11-01` (Pacific/Auckland): Recovery from a pending patch call needs a fresh file read. + - Root saw a patch call remain pending and later used an alternate edit without rereading after that call ended. The original patch had landed, so the local certificate test briefly contained duplicate fixture setup. Diff inspection caught and removed it before publication, and the corrected contract was rerun successfully. Next: inspect current scoped bytes after an uncertain mutation before constructing recovery; a pending result does not establish that no edit occurred. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index de9a5fa937..188b9a6870 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -380,7 +380,7 @@ R1407/R1408 prepare the direct-text observation and menu-retention boundary. The The public WORLDS menu store and one-key script are manually composed, unregistered preparation. The [Redis menu owner](../../architecture/system-architecture-redis.md#direct-text-worlds-ui-menu) owns storage, recovery, correlation and sharding; [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status) records the local runtime consequence. Its historical receiving gate passes 133 focused cases, including eight physical Redis/script/ACL cases, with zero failures, errors or skips, selected main/test/integration static analysis and full formatting. Earlier failed binary-array analysis aggregates remain retained. Production protected-connection binding, authenticated receiving custody, hidden rebind and deployed ACL changes remain incomplete; no genuine transport or admission authority is established. -The consolidated preparation also implements the unregistered [authenticated lobby SQL companion](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion) and its Account client composition. R1414 passes 29 unit and 16 actual PostgreSQL cases, covering populated-journal migration, original/attempt retention, lock-order races, ambiguous outcomes, delayed historical success and direct SQL violations, with zero failures, errors or skips. Selected static, formatting and fresh packaging checks pass across retained recoveries; earlier broad-catch, generated-message and synchronization failures remain recorded. Fresh source-built held smoke on `85d4568536` passes backend WORLDS → LOGIN → PLAY → LOOK → LOGOUT and Gateway/Telnet denial checks, with canonical cleanup and independently empty exact-project resources. This is controlled component/startup proof. Genuine protected receiving custody, live REALMS/JOIN registration, complete negative/unknown-result recovery, lawful release and successful public admission remain incomplete or held at their existing owners. +The consolidated authenticated-lobby SQL companion and Account-client proof, including the #3366 caller-bound Account scope, frozen JOIN original, current-selection and retention limits, is recorded in the [detailed #3366/R1414 qualification](#3366-direct-text-proof). R1417 qualifies the first combined menu-loss, SQL ordering and held-JOIN visibility corrections with 427 fresh selected cases (390 unit and 37 physical Redis/PostgreSQL cases), zero failures, errors or skips, selected static/formatting/documentation checks and fresh packaging. The twelve physical menu cases cover loss, expiry, source and preimage changes, and unknown writes; the SQL fixture verifies stable cross-tenant ordering and unchanged rows. The consolidated head's first full remote validation failed a retained-region test that unintentionally included V1052 in its two-migration expectation; both focused upgrade cases pass after pinning their intended V1051/V1051.1 boundary, with affected integration static analysis and formatting. Fresh held smoke on `045755e8cc` passes the same backend and denial flows with complete verified cleanup. These are separately attributed focused results, not a replacement full-service CI pass. @@ -388,6 +388,8 @@ The later scope-time correction passes all 39 focused scope/lobby cases, includi Latest review corrections clarify malformed-menu recovery at its owner and reset/descriptor consequences, preserve public descriptor/Lua read failure causes, and test the two transport correlation fields independently. Their focused gate passes all 67 selected cases, including twelve physical Redis cases, with zero failures, errors or skips, plus selected main/test/integration static analysis, full formatting and documentation checks. Replacement full CI and the final configured provider rounds remain pending. No production owner or cleanup authority is added. +#### #3366 direct-text proof + The #3366 direct-text preparation adds the separately owned [authenticated lobby SQL companion](../../architecture/microservices/game-session-service/runtime-and-data.md#direct-text-authenticated-lobby-companion), retaining the exact caller-bound Account scope and a durable frozen JOIN original before dispatch. Its current-selection pointer cannot replace earlier unknown attempts, and the existing original LOGIN journal/codec and retention hold remain. R1414 passes 29 focused unit cases and 16 real-PostgreSQL cases with zero failures, errors or skips. Physical proof migrates a populated pre-companion LOGIN journal, preserves its complete original row, exercises both abandonment/claim lock orders and concurrent dispatch claims, retains uncertain outcomes across owner replacement, rejects direct identity/transition/retention violations, and bounds positive membership identifiers to Account’s canonical positive BIGINT domain. Selected main/test/integration Checkstyle and SpotBugs, full Java formatting and fresh Game Session packaging pass across the combined recovery and final main-analysis gate; the first two aggregates retain broad-catch, generated-immutable-message analysis and test-fixture synchronization failures. The manually composed owner can issue scope and dispatch the frozen original through the existing Account client under a required protected-custody port, but no genuine producer for that port or text-command registration is supplied. Fresh source-built held-admission smoke on `85d4568536` passes the actual backend WORLDS → LOGIN → PLAY → LOOK → LOGOUT flow and Gateway/Telnet denial checks. Canonical cleanup completes, and independent exact-project checks find no containers, networks or volumes. This proves startup and the isolated held flow, not successful public admission or a production custody producer. This does not wire live REALMS/JOIN text dispatch, prove genuine receiving custody, register a production owner, settle negative/unknown results, release retained rows or establish admission. ### Account operation and signer source preparation @@ -484,7 +486,7 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The historical initial unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped when Docker was unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Previously merged bootstrap credential and connect-scope artifacts use the Account UUID. Ordinary password/OTP results, JWT subjects and profile/export identity fields also use that UUID in this receiving source; tenant IDs remain numeric and full portable export is not implemented. The [ordinary UUID receiving record](#ordinary-uuid-issuer-and-receiving) owns the current implementation and proof limits. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and alone do not qualify the later UUID receiving source or production gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | | `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | -| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | +| `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | | `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | @@ -654,6 +656,8 @@ The same local containment suspends the unused `ExportAccount`, caller-asserted R1418 subsequently carries published #3365 parent `1d2b862ea5a176f9c7e08dd3a0d76ee2056b9503` into local receiving source `863797ec59361deee0225a40804dcdaf08fd0d86` and freshly rebuilds jars and images for the canonical held-admission smoke. The direct backend LOGIN → PLAY → LOOK proof and Gateway/Telnet denial qualification pass; authenticated teardown succeeds, and independent exact-project checks find no containers, networks or volumes. This qualifies the bounded local Entity credential fixture and current contained startup, not successful public Gateway/Telnet admission, production credential authority, audit delivery, unknown-outcome observation or lawful release. The 172-case aggregate above retains its earlier code-source attribution; the inherited direct-text carry does not change those Account implementation or test bytes. +The initial review corrections qualify script-local certificate defaults beneath a symlinked checkout ancestor while continuing to refuse explicit caller paths through links and preserving retained certificate bytes, modes and foreign entries. The certificate contract now requires each intended repository refusal marker on stderr as well as unchanged state, so unrelated command failures cannot satisfy it. Four freshly executed currency adapter cases require one response and completion per call, exact fail-closed metrics when a registry exists, no-registry constructor behavior and no owner interaction. Affected test static analysis, full Java formatting, ShellCheck, capability tracking and documentation checks pass. These direct corrections add no currency capability, public browser handoff, production identity or JOIN recovery authority. + Current writer inspection also narrows the retained JOIN recovery gap: the public owner commits membership, transition audit and its terminal together after a separate durable intent. Unknown acknowledgement can leave either that intent without membership effects or a complete terminal; it does not establish the donor's manufactured positive-PENDING state. A lost committed result may remain unobservable after scope expiry, changed replay policy or lost caller binding. Same-original retry and this later outcome-observation limitation require distinct proof; the existing unknown-recovery and lawful-release holds remain. The proposed audit projection-version marker likewise has no implemented Logging receipt/projection producer here and must not be inferred from receiver IDs, payload replay or stamped test rows. No historical producer provenance, new receiver, recovery RPC or release authority is supplied. ### Fail-Closed Boundary Convergence @@ -676,6 +680,10 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The ## Validation and Proof +### Entity fixture startup qualification + +The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled demo owner-authentication call reaches its single five-second Account deadline, after which the startup runner exits. The image and source profiles retain the configured Account receiving fixture; no credential or authorization rejection is established for that call. The local correction bounds transient transport retries while preserving the existing exact mTLS, credential, token and canonical Account UUID checks and fail-closed seeding. R1421 passes thirteen focused cases, including a real loopback mTLS deadline/cancellation followed by successful retry, permanent-error and interruption refusal, and fail-closed seeding. Enabled affected static analysis, full formatting, Entity packaging and documentation checks pass. The physical Account owner in that focused test is a controlled stub. Fresh canonical image-lane held smoke built all eleven applications from `6c63d7454688e8544783fb3e57fbf1a5d31c1459` and passed backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial; run-owned cleanup and independent exact-project checks found no remaining containers, networks or volumes. This runtime result does not establish successful public admission, production authority, or an explanation for the underlying cold-start latency. + The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. The operator recovery boundary is recorded by [Game Session operations](../../architecture/microservices/game-session-service/operations.md#initial-region-timeline-recovery-boundary). Source-added focused regression `CanonicalGameplayRegionLeaseOwnerIntegrationTest.initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry` uses actual PostgreSQL preparation/begin APIs, an actual Redis absence probe and repeated actual owner retries at that precise pre-Redis cut. It asserts the retained SQL row image and absent lease/metadata before and after refusals, and no reacquired creation permit or installed runtime owner. World, provisional binding and stable-incarnation inputs are controlled fixtures; the cut is modeled by discarding the original permit before calling Redis, not by killing a process or fabricating SQL. R890 freshly passed all five native region-owner cases, including this cut, and the inherited protected-admission concurrency case; its aggregate still failed Entity test SpotBugs. The extracted Entity producer's R890/R891/R893 history is recorded separately below. This is bounded refusal proof and does not establish recovery or production activation. @@ -770,5 +778,3 @@ No competing target state is currently recorded. Future design discussion is req | Social Groups and Automation | Authenticated gameplay-adjacent communication/presence and runtime script/event admission using the same identity/routing guardrails | Positive-ID/current-account readers; gameplay routing bundles; canonical REST/gRPC error envelopes | | Logging & Admin | Authenticated operator/control-plane reads, mutation/remediation actor identity, audit and response projection; StartSession compares and persists the Account-returned owner tuple for handoff | Control-plane client readers; `ApiResponse` REST boundary; owner-tuple consequence in [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md) under [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); implementation/proof status in [AA-1.3](#capability-status) | | Game Logic | Current-state command aggregation after recovery; currently stateless `LOOK`, movement-derived room context, and communication fan-out inputs | Post-restart gameplay command paths backed by shared world/session state | - -The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled demo owner-authentication call reaches its single five-second Account deadline, after which the startup runner exits. The image and source profiles retain the configured Account receiving fixture; no credential or authorization rejection is established for that call. The local correction bounds transient transport retries while preserving the existing exact mTLS, credential, token and canonical Account UUID checks and fail-closed seeding. R1421 passes thirteen focused cases, including a real loopback mTLS deadline/cancellation followed by successful retry, permanent-error and interruption refusal, and fail-closed seeding. Enabled affected static analysis, full formatting, Entity packaging and documentation checks pass. The physical Account owner in that focused test is a controlled stub. Fresh canonical image-lane held smoke built all eleven applications from `6c63d7454688e8544783fb3e57fbf1a5d31c1459` and passed backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial; run-owned cleanup and independent exact-project checks found no remaining containers, networks or volumes. This runtime result does not establish successful public admission, production authority, or an explanation for the underlying cold-start latency. diff --git a/dev-tools/certs/clean-dev-certs.sh b/dev-tools/certs/clean-dev-certs.sh index 66833c4679..71b8f67ce4 100644 --- a/dev-tools/certs/clean-dev-certs.sh +++ b/dev-tools/certs/clean-dev-certs.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" # Remove generated certificates so tooling can start from scratch without # deleting the tracked helper scripts in dev-tools/certs/. diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index dd5d1a4223..f7220f129c 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" CERT_DIR="${1:-${CERT_DIR:-$SCRIPT_DIR}}" GENERATOR="$SCRIPT_DIR/generate-dev-certs.sh" COMPOSE_MTLS_STAGE_ROOT="" diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index 8020e2f1f1..1a9bedd128 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)" # Check lexical ancestors before mkdir/OpenSSL can follow a retained link. require_safe_directory_path() { diff --git a/dev-tools/tests/dev-certs-retention-contract.sh b/dev-tools/tests/dev-certs-retention-contract.sh index 5192057b22..b38018e888 100644 --- a/dev-tools/tests/dev-certs-retention-contract.sh +++ b/dev-tools/tests/dev-certs-retention-contract.sh @@ -31,15 +31,22 @@ PY } expect_unchanged_failure() { - local fixture="$1" before after - shift + local fixture="$1" marker="$2" before after + shift 2 before="$(snapshot "$fixture")" - if "$@" >"$TEST_ROOT/failure-output" 2>&1; then + if "$@" >"$TEST_ROOT/failure-stdout" 2>"$TEST_ROOT/failure-stderr"; then echo "Expected certificate operation to refuse retained fixture: $*" >&2 exit 1 fi + if ! grep -Fq -- "$marker" "$TEST_ROOT/failure-stderr"; then + echo "Missing refusal marker '$marker' for: $*" >&2 + exit 1 + fi after="$(snapshot "$fixture")" - [[ "$before" == "$after" ]] + if [[ "$before" != "$after" ]]; then + echo "Fixture changed during refused operation: $fixture" >&2 + exit 1 + fi } fresh="$TEST_ROOT/fresh" @@ -62,8 +69,8 @@ bash "$ENSURE" "$fresh" >/dev/null partial="$TEST_ROOT/partial" mkdir "$partial" printf 'retained CA\n' >"$partial/ca.crt" -expect_unchanged_failure "$partial" bash "$GENERATOR" "$partial" -expect_unchanged_failure "$partial" bash "$ENSURE" "$partial" +expect_unchanged_failure "$partial" "Incomplete retained development certificate bundle" bash "$GENERATOR" "$partial" +expect_unchanged_failure "$partial" "Incomplete retained development certificate bundle" bash "$ENSURE" "$partial" other="$TEST_ROOT/other" bash "$GENERATOR" "$other" >"$TEST_ROOT/other-output" 2>&1 @@ -76,8 +83,8 @@ for corruption in malformed key ca ca-key; do ca) cp -- "$other/ca.crt" "$fixture/ca.crt"; cp -- "$other/ca.key" "$fixture/ca.key"; cp -- "$other/dev-ca.pem" "$fixture/dev-ca.pem" ;; ca-key) cp -- "$other/ca.key" "$fixture/ca.key" ;; esac - expect_unchanged_failure "$fixture" bash "$GENERATOR" "$fixture" - expect_unchanged_failure "$fixture" bash "$ENSURE" "$fixture" + expect_unchanged_failure "$fixture" "Invalid retained development certificate bundle" bash "$GENERATOR" "$fixture" + expect_unchanged_failure "$fixture" "Invalid retained development certificate bundle" bash "$ENSURE" "$fixture" done links="$TEST_ROOT/links" @@ -88,15 +95,19 @@ ln "$links/outside/material" "$links/hard/ca.key" mkdir "$links/nonregular/ca.crt" ln -s "$links/outside" "$links/directory" for target in "$links/partial" "$links/hard" "$links/nonregular" "$links/directory/" "$links/directory/new"; do - expect_unchanged_failure "$links" bash "$GENERATOR" "$target" - expect_unchanged_failure "$links" bash "$ENSURE" "$target" + marker="Certificate paths must be regular files without symlinks or hardlinks" + case "$target" in + "$links/directory/"|"$links/directory/new") marker="Certificate directory and ancestors must be real directories" ;; + esac + expect_unchanged_failure "$links" "$marker" bash "$GENERATOR" "$target" + expect_unchanged_failure "$links" "$marker" bash "$ENSURE" "$target" done # A link in an otherwise complete bundle is also refused without a mode change. linked_complete="$TEST_ROOT/linked-complete" cp -a -- "$fresh" "$linked_complete" rm -- "$linked_complete/ca.key" ln -s "$fresh/ca.key" "$linked_complete/ca.key" -expect_unchanged_failure "$linked_complete" bash "$ENSURE" "$linked_complete" +expect_unchanged_failure "$linked_complete" "Certificate paths must be regular files without symlinks or hardlinks" bash "$ENSURE" "$linked_complete" workloads="$TEST_ROOT/workloads" mkdir "$workloads" @@ -104,10 +115,10 @@ printf 'retained output\n' >"$workloads/existing.crt" ln -s "$links/outside/material" "$workloads/linked.key" ln "$links/outside/material" "$workloads/hard.key" for key in linked.key hard.key; do - expect_unchanged_failure "$workloads" bash "$GENERATOR" --workload \ + expect_unchanged_failure "$workloads" "Certificate paths must be regular files without symlinks or hardlinks" bash "$GENERATOR" --workload \ "$fresh/ca.crt" "$fresh/ca.key" "$workloads/new/client.crt" "$workloads/$key" dev world-management-service done -expect_unchanged_failure "$workloads" bash "$GENERATOR" --workload \ +expect_unchanged_failure "$workloads" "Refusing to overwrite retained workload output" bash "$GENERATOR" --workload \ "$fresh/ca.crt" "$fresh/ca.key" "$workloads/existing.crt" "$workloads/new/client.key" dev world-management-service cleanup="$TEST_ROOT/cleanup" @@ -128,7 +139,44 @@ for entry in client.key server.key foreign.crt foreign-directory; do grep -Fq "Preserved certificate-directory entry: $cleanup/$entry" "$TEST_ROOT/cleanup-output" done for target in "$links/directory/" "$links/directory/new"; do - expect_unchanged_failure "$links" bash "$CLEAN" "$target" + expect_unchanged_failure "$links" "Certificate cleanup refuses linked or non-directory paths" bash "$CLEAN" "$target" +done + +# Resolve the implicit script root physically while refusing explicit linked paths. +physical_root="$TEST_ROOT/physical-root" +mkdir -p "$physical_root/certs" +cp -p -- "$GENERATOR" "$ENSURE" "$CLEAN" "$physical_root/certs/" +ln -s "$physical_root" "$TEST_ROOT/workspace-link" +printf 'retained checkout material\n' >"$physical_root/certs/foreign.pem" +( + unset CERT_DIR + cd "$TEST_ROOT/workspace-link" + bash certs/generate-dev-certs.sh >"$TEST_ROOT/default-generation-output" 2>&1 +) +[[ -s "$physical_root/certs/ca.crt" && -s "$physical_root/certs/server.key" ]] +before="$(snapshot "$physical_root")" +( + unset CERT_DIR + cd "$TEST_ROOT/workspace-link" + bash certs/ensure-dev-certs.sh >"$TEST_ROOT/default-ensure-output" 2>&1 +) +[[ "$before" == "$(snapshot "$physical_root")" ]] +for operation in "$GENERATOR" "$ENSURE" "$CLEAN"; do + marker="Certificate directory and ancestors must be real directories" + if [[ "$operation" == "$CLEAN" ]]; then + marker="Certificate cleanup refuses linked or non-directory paths" + fi + expect_unchanged_failure "$physical_root" "$marker" bash "$operation" "$TEST_ROOT/workspace-link/certs" +done +( + unset CERT_DIR + cd "$TEST_ROOT/workspace-link" + bash certs/clean-dev-certs.sh >"$TEST_ROOT/default-cleanup-output" 2>&1 +) +[[ ! -e "$physical_root/certs/ca.crt" && ! -e "$physical_root/certs/server.key" ]] +[[ "$(cat "$physical_root/certs/foreign.pem")" == 'retained checkout material' ]] +for script in generate-dev-certs.sh ensure-dev-certs.sh clean-dev-certs.sh; do + cmp -s "$physical_root/certs/$script" "$REPO_ROOT/dev-tools/certs/$script" done -echo 'Development certificate retention contract passed.' +echo 'Development certificate retention and physical-default contracts passed.' diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java index 98c097822a..139dddb6fe 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.ArrayList; import java.util.List; @@ -21,11 +22,13 @@ class VirtualCurrencyGrpcServiceTest { @Test void getBalanceFailsClosedForRepeatedValidRequestsWithoutReadingBalance() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + new VirtualCurrencyGrpcService(currencyService, meterRegistry); List responses = new ArrayList<>(); + CompletionCounter completions = new CompletionCounter(); - StreamObserver observer = collecting(responses); + StreamObserver observer = collecting(responses, completions); GetBalanceRequest request = GetBalanceRequest.newBuilder() .setTenantId("1") @@ -35,18 +38,21 @@ void getBalanceFailsClosedForRepeatedValidRequestsWithoutReadingBalance() { service.getBalance(request, observer); service.getBalance(request, observer); - assertUnavailable(responses, "GetBalance is unavailable"); + assertUnavailable(responses, completions, 2, "GetBalance is unavailable"); + assertAppErrorCount(meterRegistry, 2); Mockito.verifyNoInteractions(currencyService); } @Test void addCurrencyFailsClosedForRepeatedValidRequestsWithoutAddingCurrency() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + new VirtualCurrencyGrpcService(currencyService, meterRegistry); List responses = new ArrayList<>(); + CompletionCounter completions = new CompletionCounter(); - StreamObserver observer = collecting(responses); + StreamObserver observer = collecting(responses, completions); AddCurrencyRequest request = AddCurrencyRequest.newBuilder() .setTenantId("1") @@ -57,18 +63,21 @@ void addCurrencyFailsClosedForRepeatedValidRequestsWithoutAddingCurrency() { service.addCurrency(request, observer); service.addCurrency(request, observer); - assertUnavailable(responses, "AddCurrency is unavailable"); + assertUnavailable(responses, completions, 2, "AddCurrency is unavailable"); + assertAppErrorCount(meterRegistry, 2); Mockito.verifyNoInteractions(currencyService); } @Test void spendCurrencyFailsClosedForRepeatedValidRequestsWithoutSpendingCurrency() { VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, new SimpleMeterRegistry()); + new VirtualCurrencyGrpcService(currencyService, meterRegistry); List responses = new ArrayList<>(); + CompletionCounter completions = new CompletionCounter(); - StreamObserver observer = collecting(responses); + StreamObserver observer = collecting(responses, completions); SpendCurrencyRequest request = SpendCurrencyRequest.newBuilder() .setTenantId("1") @@ -79,11 +88,54 @@ void spendCurrencyFailsClosedForRepeatedValidRequestsWithoutSpendingCurrency() { service.spendCurrency(request, observer); service.spendCurrency(request, observer); - assertUnavailable(responses, "SpendCurrency is unavailable"); + assertUnavailable(responses, completions, 2, "SpendCurrency is unavailable"); + assertAppErrorCount(meterRegistry, 2); Mockito.verifyNoInteractions(currencyService); } - private static StreamObserver collecting(List responses) { + @Test + void singleArgumentConstructorFailsClosedWithoutOwnerAccess() { + VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); + VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService); + List balanceResponses = new ArrayList<>(); + List addResponses = new ArrayList<>(); + List spendResponses = new ArrayList<>(); + CompletionCounter balanceCompletions = new CompletionCounter(); + CompletionCounter addCompletions = new CompletionCounter(); + CompletionCounter spendCompletions = new CompletionCounter(); + + service.getBalance( + GetBalanceRequest.newBuilder() + .setTenantId("1") + .setAccountId("11111111-1111-4111-8111-111111111111") + .setCurrencyCode("GOLD") + .build(), + collecting(balanceResponses, balanceCompletions)); + service.addCurrency( + AddCurrencyRequest.newBuilder() + .setTenantId("1") + .setAccountId("11111111-1111-4111-8111-111111111111") + .setCurrencyCode("GOLD") + .setAmount(10) + .build(), + collecting(addResponses, addCompletions)); + service.spendCurrency( + SpendCurrencyRequest.newBuilder() + .setTenantId("1") + .setAccountId("11111111-1111-4111-8111-111111111111") + .setCurrencyCode("GOLD") + .setAmount(5) + .build(), + collecting(spendResponses, spendCompletions)); + + assertUnavailable(balanceResponses, balanceCompletions, 1, "GetBalance is unavailable"); + assertUnavailable(addResponses, addCompletions, 1, "AddCurrency is unavailable"); + assertUnavailable(spendResponses, spendCompletions, 1, "SpendCurrency is unavailable"); + Mockito.verifyNoInteractions(currencyService); + } + + private static StreamObserver collecting( + List responses, CompletionCounter completions) { return new StreamObserver<>() { @Override public void onNext(T value) { @@ -96,12 +148,16 @@ public void onError(Throwable error) { } @Override - public void onCompleted() {} + public void onCompleted() { + completions.count++; + } }; } - private static void assertUnavailable(List responses, String message) { - assertEquals(2, responses.size()); + private static void assertUnavailable( + List responses, CompletionCounter completions, int expectedCalls, String message) { + assertEquals(expectedCalls, responses.size()); + assertEquals(expectedCalls, completions.count); for (Object response : responses) { assertNotNull(response); if (response instanceof GetBalanceResponse getBalanceResponse) { @@ -118,4 +174,15 @@ private static void assertUnavailable(List responses, String message) { } } } + + private static void assertAppErrorCount(MeterRegistry meterRegistry, int expectedCount) { + assertEquals( + (double) expectedCount, + meterRegistry.get("grpc.app_error").tag("code", "FAILED_PRECONDITION").counter().count()); + assertEquals(1, meterRegistry.getMeters().size()); + } + + private static final class CompletionCounter { + private int count; + } } From 04eda910b3408871c4e8dc615110a4e2127eacf3 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 08:19:34 +1300 Subject: [PATCH 08/16] Clarify fixture peer denial and certificate workload scope --- .../implementation-tracking/player-access-and-session.md | 8 ++++---- dev-tools/certs/README.md | 4 ++-- .../accountservice/service/impl/AccountGrpcService.java | 3 ++- .../service/impl/AccountCredentialPeerGrpcMtlsTest.java | 7 ++++++- 4 files changed, 14 insertions(+), 8 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 188b9a6870..f739aded89 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -680,10 +680,6 @@ Equivalent HTTP, WebSocket, and gRPC failures use stable boundary semantics. The ## Validation and Proof -### Entity fixture startup qualification - -The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled demo owner-authentication call reaches its single five-second Account deadline, after which the startup runner exits. The image and source profiles retain the configured Account receiving fixture; no credential or authorization rejection is established for that call. The local correction bounds transient transport retries while preserving the existing exact mTLS, credential, token and canonical Account UUID checks and fail-closed seeding. R1421 passes thirteen focused cases, including a real loopback mTLS deadline/cancellation followed by successful retry, permanent-error and interruption refusal, and fail-closed seeding. Enabled affected static analysis, full formatting, Entity packaging and documentation checks pass. The physical Account owner in that focused test is a controlled stub. Fresh canonical image-lane held smoke built all eleven applications from `6c63d7454688e8544783fb3e57fbf1a5d31c1459` and passed backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial; run-owned cleanup and independent exact-project checks found no remaining containers, networks or volumes. This runtime result does not establish successful public admission, production authority, or an explanation for the underlying cold-start latency. - The prepared region owner has a scope-local liveness limit when `beginInitialTimeline` commits `INITIALIZING` but the Redis initialization call never executes. The retained phase, initialization operation and source do not grant a second creation permission; absent keys cannot distinguish that cut from metadata loss, so repeated owner retries refuse without a lease or runtime owner installation. No shipped in-place automatic recovery, dedicated alert or operator repair is claimed. The operator recovery boundary is recorded by [Game Session operations](../../architecture/microservices/game-session-service/operations.md#initial-region-timeline-recovery-boundary). Source-added focused regression `CanonicalGameplayRegionLeaseOwnerIntegrationTest.initializingBeforeRedisExecutionRetainsEvidenceAndRefusesRepeatedOwnerRetry` uses actual PostgreSQL preparation/begin APIs, an actual Redis absence probe and repeated actual owner retries at that precise pre-Redis cut. It asserts the retained SQL row image and absent lease/metadata before and after refusals, and no reacquired creation permit or installed runtime owner. World, provisional binding and stable-incarnation inputs are controlled fixtures; the cut is modeled by discarding the original permit before calling Redis, not by killing a process or fabricating SQL. R890 freshly passed all five native region-owner cases, including this cut, and the inherited protected-admission concurrency case; its aggregate still failed Entity test SpotBugs. The extracted Entity producer's R890/R891/R893 history is recorded separately below. This is bounded refusal proof and does not establish recovery or production activation. @@ -742,6 +738,10 @@ Restricted original-claim evidence continuation remains inactive and preparation At local source `0a685173e0982ba3c0006acb3e378d228daeadbb`, normally reconciled to published parent `7b2ce6340309198ed4fabd0e58629102ba717706`, the focused gate passed in 2m36s: 150 fresh unit cases and 35 physical Redis-context/PostgreSQL-journal cases, all with zero failures, errors or skips, plus Game Session Checkstyle, SpotBugs, formatting and documentation checks. The subsequent two composed-owner test additions on that local baseline passed all 28 physical Redis-context/PostgreSQL cases in the 57-second affected gate, with zero failures, errors or skips and affected static/format checks. The initial test-package compilation failures remain failed history; production constructor visibility was preserved. The unregistered [InitialGameplayLoginOwner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java) reserves and independently reads back distinct server UUIDv4 request/context coordinates at fence 1 before create-only `PENDING`, then calls the [canonical Account client](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java) with its bounded same-deadline retry guarded by current original credential custody. It records and reads back the verified nonsecret witness before exact-result installation and transfers the still-live private result to its caller; uncertain results and actual original pre-admission custody loss retain exact-original cleanup. This original-attempt lifecycle remains separate from already-admitted retained-edge rebind. The [owner proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java), [Redis integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java), and [journal integration proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java) exercise controlled composition and physical storage fixtures only. The composed physical cases check independently committed original coordinates before the first Redis mutation, actual PENDING creation and non-admitting installation, and same-invocation credential closure after a controlled Account response followed by exact-original Redis closure, frozen witness-bearing retirement, a PENDING disposal receipt and owned-result erasure. Account signing/disposal responses and external Redis qualification remain controlled inputs. The later 28-case evidence belongs to the local changed test postimage, not an authenticated production receiving chain. Caller registration, trusted Gateway/Proxy identity and protected custody, production Redis qualification, real Account mTLS/signing, qualified retained binding-history recovery, runtime activation, gameplay admission, and LOGIN wire success remain unproved; `AA-2.1` remains partial. See the canonical [session and identity model](../../architecture/system-architecture-session-behavior.md#session-types-and-lifetimes), [plain-text LOGIN mapping](../../architecture/system-architecture-authentication.md#plain-text-login-logon-command-mapping), [original-attempt coordination](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination), [bounded non-edge recovery](../../architecture/system-architecture-reconnection.md#bounded-non-edge-restart-recovery), [initial-context aggregate](../../architecture/system-architecture-redis.md#initial-login-context-aggregate), and [Redis operation](../../architecture/system-architecture-redis-ops-access.md) owners. +### Entity fixture startup qualification + +The #3367 image smoke at `e139ee01` fails when Entity’s explicitly enabled demo owner-authentication call reaches its single five-second Account deadline, after which the startup runner exits. The image and source profiles retain the configured Account receiving fixture; no credential or authorization rejection is established for that call. The local correction bounds transient transport retries while preserving the existing exact mTLS, credential, token and canonical Account UUID checks and fail-closed seeding. R1421 passes thirteen focused cases, including a real loopback mTLS deadline/cancellation followed by successful retry, permanent-error and interruption refusal, and fail-closed seeding. Enabled affected static analysis, full formatting, Entity packaging and documentation checks pass. The physical Account owner in that focused test is a controlled stub. Fresh canonical image-lane held smoke built all eleven applications from `6c63d7454688e8544783fb3e57fbf1a5d31c1459` and passed backend LOGIN → PLAY → LOOK plus Gateway/Telnet denial; run-owned cleanup and independent exact-project checks found no remaining containers, networks or volumes. This runtime result does not establish successful public admission, production authority, or an explanation for the underlying cold-start latency. + ## Active Gaps - Account authentication has no stable attempt identity or replayable result contract. Game Session now avoids automatically retrying an ambiguous credential-consuming transport failure, but Account still needs durable request identity and idempotent result lookup before authentication itself is safely retryable. diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index e473f1046a..bd24032c7f 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -6,8 +6,8 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map -- `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target or `CERT_DIR` is provided. A complete retained bundle is validated for certificate/key/CA agreement and reused without changing bytes or permissions. Incomplete or invalid retained material fails closed; preserve it and select a fresh dedicated directory for replacement material. All managed paths and their directory ancestors are checked before writes; symlinks, nonregular files, and hardlinked files are refused. Generation changes only its named outputs, leaving unrelated entries untouched. -- `dev-tools/certs/generate-dev-certs.sh --workload` signs local development or test-only gRPC workload leaves for the five publication services, Account, Game Session, and Social Groups with the exact SPIFFE URI and service DNS SANs. This mode supports all eleven Java application workload identities and requires fresh output paths; callers stage replacement leaves before installing them. Ordinary local development uses the dedicated per-workload helper described below; run-owned smoke uses the qualified fixture described below. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. +- `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target or `CERT_DIR` is provided. A complete retained bundle is validated for certificate/key/CA agreement and reused without changing bytes or permissions. Incomplete or invalid retained material fails closed; preserve it and select a fresh dedicated directory for replacement material. The implicit script-local default resolves its directory physically. Explicit caller paths and all managed certificate entries and their directory ancestors are checked before writes; symlinks, nonregular files, and hardlinked files are refused. Generation changes only its named outputs, leaving unrelated entries untouched. +- `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only gRPC workload leaf for any of the eleven Java application workload identities, with the exact SPIFFE URI and service DNS SANs. This mode requires fresh output paths; callers stage replacement leaves before installing them. Ordinary local development uses the dedicated per-workload helper described below; run-owned smoke uses the qualified fixture described below. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. - Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume eight cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. - `dev-tools/certs/ensure-local-compose-mtls.sh` owns ordinary local development certificates for all eleven application workloads. See [ordinary local Compose setup and retained-certificate recovery](../../docker/README.md#local-compose-mtls-certificate-recovery); this authority remains separate from run-owned smoke fixtures. - `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index c1b3139473..271520da85 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -249,7 +249,8 @@ private void requireCredentialPeer(AuthenticateRequest request) { return; } requireWorkloadPeer( - "Verified Game Session workload identity is required", "entity-management-service"); + "Verified Game Session or local-fixture Entity Management workload identity is required", + "entity-management-service"); if (!localDemoAuthenticationEnabled) { throw new AdminAuthorizationException("Local demo authentication is unavailable"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java index 94d7c242c6..716f4eef16 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java @@ -152,7 +152,12 @@ void trustedWrongWorkloadAndNamespaceCertificatesAreDeniedBeforeAccountInvocatio try (TransportServer server = startServer(fixtureService(owner, true, "local-fixture"))) { for (String alias : List.of("world", "other-game-session", "other-entity")) { try (ClientTransport client = newClient(server.port(), alias)) { - assertAllDenied(client.stub(), AuthenticateRequest.getDefaultInstance()); + var response = client.stub().authenticate(AuthenticateRequest.getDefaultInstance()); + assertAuthenticationDenied(response); + assertThat(response.getError().getMessage()) + .isEqualTo( + "Verified Game Session or local-fixture Entity Management workload identity is required"); + assertOtpDenied(client.stub()); } } verifyNoInteractions(owner); From 13953d4c18f452dc84f748d3f625e1eeb9220ca0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:24:09 +1300 Subject: [PATCH 09/16] Return canonical transport failures for deferred Account RPCs --- .../account-service/api-contracts.md | 2 + .../player-access-and-session.md | 2 + protos/account/v1/account_service.proto | 4 + .../account/v1/virtual_currency_service.proto | 2 + .../service/impl/AccountGrpcService.java | 56 ++-- .../impl/VirtualCurrencyGrpcService.java | 48 ++-- .../src/main/resources/openapi.yaml | 12 +- .../EmailVerificationHttpAuthWiringTest.java | 20 ++ .../service/impl/AccountGrpcServiceTest.java | 197 +++++-------- .../DeferredAccountGrpcTransportTest.java | 210 ++++++++++++++ .../impl/VirtualCurrencyGrpcServiceTest.java | 266 ++++++++---------- 11 files changed, 477 insertions(+), 342 deletions(-) create mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/DeferredAccountGrpcTransportTest.java diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 20a1dce448..7862c77103 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -262,6 +262,8 @@ The registered legacy `Authenticate`, `RequestEmailLoginOtp` and `VerifyEmailLog `Authenticate` alone has a separate local demo fixture branch for the exact same-namespace Entity Management certificate identity. Account must explicitly enable `firemud.account.local-demo-authentication.enabled`, configure the demo email identity, and run with the `local-fixture` profile without `prod`. The flag defaults to false and the configured identity defaults empty; an enabled local fixture with no valid configured identity fails startup. The request must match that configured identity before ordinary Account password verification runs. A caller-side seed flag, bearer or claimed peer header cannot enable the receiving branch, and enabling it never permits Entity OTP requests or general Entity credential access. This is the bounded local/run-fixture used by [Entity demo seeding](../entity-management-service/runtime-and-data.md#implementation-status); it does not activate the separate canonical private LOGIN receiver, production registration or gameplay admission. +The disabled `ExportAccount`, `ExportTenantData`, `LinkExternalAccount`, `RequestEmailVerification`, `GetBalance`, `AddCurrency`, and `SpendCurrency` adapters fail before domain execution with non-OK gRPC `FAILED_PRECONDITION` and one bounded `ErrorDetail` in status trailers. They emit no response body or successful completion. This follows the shared [outcome and transport classification](../../system-architecture-grpc.md#outcome-and-transport-classification); the retained response schemas do not make these operations available. + ## REST APIs Implemented Account-valued REST selectors and response fields use canonical Account UUID text. `AuthenticationResult.accountId`, `PlayerBootstrapResult.accountId`, and `ProfileDto.accountId` serialize as JSON strings; Account-issued login and bootstrap tokens carry the same UUID in `sub` and `accountId`. Current `/accounts/{accountId}` and profile handlers resolve those identities through Account's persisted UUID/provenance boundary before using private local rows. Tenant identifiers retain their existing representation. The Account identity contract is owned here with [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md); this paragraph records the local wire and storage boundary. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index f739aded89..1269a5284c 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -654,6 +654,8 @@ R1418 additionally contains the legacy account-targeted `ExportTenantData` gRPC The same local containment suspends the unused `ExportAccount`, caller-asserted `LinkExternalAccount` and Account-ID `RequestEmailVerification` gRPC adapters before request parsing or owner access. Target export/link capabilities and an authorized internal verification-initiation caller remain incomplete. Separately authorized REST/service exports, neutral email-based initiation and the stronger token-based reset/verification owners remain. The combined current gate passes all 172 selected cases (163 Account unit/loopback cases, including eleven physical mTLS and six actual-profile HTTP wiring cases, plus nine actual PostgreSQL/Spring cases) with zero failures, errors or skips, selected main/test/integration static analysis, full formatting, fresh packaging and documentation checks. The three public-v1 JOIN cases prove actual commit followed by lost acknowledgement/readback, rollback followed by same-original continuation, and unchanged retained committed evidence after scope expiry. Controlled routing/caller inputs and injected failures establish no deployed RPC recovery or production authority. Public POST verification is selected by actual base/prod YAML; GET supplies no verification route or bypass. The email-link/browser handoff remains outside this local API proof. +R1425 corrects the seven disabled Account/currency adapters to non-OK `FAILED_PRECONDITION` with bounded structured status details, retaining error metrics and no owner access. The Account RPC unit cases and a repeated-call loopback transport fixture cover this boundary; OpenAPI now declares the existing bearerless verification POST, with its base/prod HTTP wiring proof retained. All 154 selected cases pass with zero failures, errors or skips: 143 Account RPC, four currency adapter, one repeated-call real loopback gRPC, and six base/prod HTTP composition cases. The loopback fixture checks all seven adapters twice, precise status/details, zero injected owner calls and bounded error-counter labels/counts, with checked transport cleanup. After correcting the fixture compilation and replacing retained mutable-Throwable capture with immutable status capture, the fresh consolidated gate passes all 154 cases, enabled Account main/test Checkstyle and SpotBugs, full formatting, boot-jar packaging and documentation checks. Fresh packaged-runtime proof remains pending. These fixtures do not establish workload TLS, supported export/link/currency operations or browser email-link handoff. + R1418 subsequently carries published #3365 parent `1d2b862ea5a176f9c7e08dd3a0d76ee2056b9503` into local receiving source `863797ec59361deee0225a40804dcdaf08fd0d86` and freshly rebuilds jars and images for the canonical held-admission smoke. The direct backend LOGIN → PLAY → LOOK proof and Gateway/Telnet denial qualification pass; authenticated teardown succeeds, and independent exact-project checks find no containers, networks or volumes. This qualifies the bounded local Entity credential fixture and current contained startup, not successful public Gateway/Telnet admission, production credential authority, audit delivery, unknown-outcome observation or lawful release. The 172-case aggregate above retains its earlier code-source attribution; the inherited direct-text carry does not change those Account implementation or test bytes. The initial review corrections qualify script-local certificate defaults beneath a symlinked checkout ancestor while continuing to refuse explicit caller paths through links and preserving retained certificate bytes, modes and foreign entries. The certificate contract now requires each intended repository refusal marker on stderr as well as unchanged state, so unrelated command failures cannot satisfy it. Four freshly executed currency adapter cases require one response and completion per call, exact fail-closed metrics when a registry exists, no-registry constructor behavior and no owner interaction. Affected test static analysis, full Java formatting, ShellCheck, capability tracking and documentation checks pass. These direct corrections add no currency capability, public browser handoff, production identity or JOIN recovery authority. diff --git a/protos/account/v1/account_service.proto b/protos/account/v1/account_service.proto index 2149e6f927..922f3b881c 100644 --- a/protos/account/v1/account_service.proto +++ b/protos/account/v1/account_service.proto @@ -25,12 +25,16 @@ service AccountService { rpc ListPresenceVisibilityPolicies(ListPresenceVisibilityPoliciesRequest) returns (ListPresenceVisibilityPoliciesResponse); rpc UpdateProfile(UpdateProfileRequest) returns (UpdateProfileResponse); + // Deferred: non-OK FAILED_PRECONDITION with ErrorDetail status trailers; no response. rpc ExportAccount(ExportAccountRequest) returns (ExportAccountResponse); + // Deferred: non-OK FAILED_PRECONDITION with ErrorDetail status trailers; no response. rpc ExportTenantData(ExportTenantDataRequest) returns (ExportTenantDataResponse); rpc DeleteAccount(DeleteAccountRequest) returns (DeleteAccountResponse); rpc RequestPasswordReset(RequestPasswordResetRequest) returns (RequestPasswordResetResponse); rpc CompletePasswordReset(CompletePasswordResetRequest) returns (CompletePasswordResetResponse); + // Deferred: non-OK FAILED_PRECONDITION with ErrorDetail status trailers; no response. rpc LinkExternalAccount(LinkExternalAccountRequest) returns (LinkExternalAccountResponse); + // Deferred: non-OK FAILED_PRECONDITION with ErrorDetail status trailers; no response. rpc RequestEmailVerification(RequestEmailVerificationRequest) returns (RequestEmailVerificationResponse); rpc VerifyEmail(VerifyEmailRequest) returns (VerifyEmailResponse); } diff --git a/protos/account/v1/virtual_currency_service.proto b/protos/account/v1/virtual_currency_service.proto index e459eb93a9..6e43d87c5f 100644 --- a/protos/account/v1/virtual_currency_service.proto +++ b/protos/account/v1/virtual_currency_service.proto @@ -7,6 +7,8 @@ import "shared/v1/errors.proto"; option java_package = "net.firedevops.firemud.account.v1"; option java_multiple_files = true; +// These deferred methods currently fail before domain execution with non-OK +// FAILED_PRECONDITION and bounded ErrorDetail status trailers, without a response. service VirtualCurrencyService { rpc GetBalance(GetBalanceRequest) returns (GetBalanceResponse); rpc AddCurrency(AddCurrencyRequest) returns (AddCurrencyResponse); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index 271520da85..cd964043bb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -1,7 +1,9 @@ package net.firedevops.firemud.accountservice.service.impl; +import com.google.protobuf.Any; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.grpc.Status; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; @@ -1002,30 +1004,14 @@ public void updateProfile( @Timed(value = "accountGrpc.exportAccount") public void exportAccount( ExportAccountRequest request, StreamObserver responseObserver) { - responseObserver.onNext( - ExportAccountResponse.newBuilder() - .setError( - appError( - "ExportAccount", - "FAILED_PRECONDITION", - "No authorized internal caller is configured")) - .build()); - responseObserver.onCompleted(); + refuseUnconfiguredInternalCaller("ExportAccount", responseObserver); } @Override @Timed(value = "accountGrpc.exportTenantData") public void exportTenantData( ExportTenantDataRequest request, StreamObserver responseObserver) { - responseObserver.onNext( - ExportTenantDataResponse.newBuilder() - .setError( - appError( - "ExportTenantData", - "FAILED_PRECONDITION", - "No authorized internal caller is configured")) - .build()); - responseObserver.onCompleted(); + refuseUnconfiguredInternalCaller("ExportTenantData", responseObserver); } @Override @@ -1150,16 +1136,7 @@ public void linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest request, StreamObserver responseObserver) { - responseObserver.onNext( - net.firedevops.firemud.account.v1.LinkExternalAccountResponse.newBuilder() - .setSuccess(false) - .setError( - appError( - "LinkExternalAccount", - "FAILED_PRECONDITION", - "No authorized internal caller is configured")) - .build()); - responseObserver.onCompleted(); + refuseUnconfiguredInternalCaller("LinkExternalAccount", responseObserver); } @Override @@ -1168,16 +1145,7 @@ public void requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest request, StreamObserver responseObserver) { - responseObserver.onNext( - net.firedevops.firemud.account.v1.RequestEmailVerificationResponse.newBuilder() - .setSuccess(false) - .setError( - appError( - "RequestEmailVerification", - "FAILED_PRECONDITION", - "No authorized internal caller is configured")) - .build()); - responseObserver.onCompleted(); + refuseUnconfiguredInternalCaller("RequestEmailVerification", responseObserver); } @Override @@ -1244,6 +1212,18 @@ private AccountUuidReadbackUnavailableException(Throwable cause) { } } + private void refuseUnconfiguredInternalCaller(String operation, StreamObserver observer) { + String message = "No authorized internal caller is configured"; + var detail = appError(operation, "FAILED_PRECONDITION", message); + observer.onError( + StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(Status.Code.FAILED_PRECONDITION.value()) + .setMessage(message) + .addDetails(Any.pack(detail)) + .build())); + } + private net.firedevops.firemud.shared.v1.ErrorDetail appError( String operation, String code, String message) { return meterRegistry == null diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java index 54c76c2bfb..03af9c2861 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcService.java @@ -1,6 +1,9 @@ package net.firedevops.firemud.accountservice.service.impl; +import com.google.protobuf.Any; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; @@ -11,12 +14,10 @@ import net.firedevops.firemud.account.v1.SpendCurrencyRequest; import net.firedevops.firemud.account.v1.SpendCurrencyResponse; import net.firedevops.firemud.account.v1.VirtualCurrencyServiceGrpc; -import net.firedevops.firemud.accountservice.service.VirtualCurrencyService; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.shared.v1.ErrorDetail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.grpc.server.service.GrpcService; @GrpcService @@ -24,24 +25,12 @@ public class VirtualCurrencyGrpcService extends VirtualCurrencyServiceGrpc.VirtualCurrencyServiceImplBase { private static final Logger logger = LoggerFactory.getLogger(VirtualCurrencyGrpcService.class); - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "CurrencyService is injected and not exposed") - private final VirtualCurrencyService currencyService; - private final MeterRegistry meterRegistry; - public VirtualCurrencyGrpcService(VirtualCurrencyService currencyService) { - this(currencyService, null); - } - - @Autowired @SuppressFBWarnings( value = "EI_EXPOSE_REP2", - justification = "Injected service and registry remain internal collaborators.") - public VirtualCurrencyGrpcService( - VirtualCurrencyService currencyService, MeterRegistry meterRegistry) { - this.currencyService = currencyService; + justification = "Injected registry remains an internal collaborator.") + public VirtualCurrencyGrpcService(MeterRegistry meterRegistry) { this.meterRegistry = meterRegistry; } @@ -49,33 +38,34 @@ public VirtualCurrencyGrpcService( @Timed(value = "currencyGrpc.getBalance") public void getBalance( GetBalanceRequest request, StreamObserver responseObserver) { - responseObserver.onNext( - GetBalanceResponse.newBuilder().setError(unavailable("GetBalance")).build()); - responseObserver.onCompleted(); + responseObserver.onError(unavailable("GetBalance")); } @Override @Timed(value = "currencyGrpc.addCurrency") public void addCurrency( AddCurrencyRequest request, StreamObserver responseObserver) { - responseObserver.onNext( - AddCurrencyResponse.newBuilder().setError(unavailable("AddCurrency")).build()); - responseObserver.onCompleted(); + responseObserver.onError(unavailable("AddCurrency")); } @Override @Timed(value = "currencyGrpc.spendCurrency") public void spendCurrency( SpendCurrencyRequest request, StreamObserver responseObserver) { - responseObserver.onNext( - SpendCurrencyResponse.newBuilder().setError(unavailable("SpendCurrency")).build()); - responseObserver.onCompleted(); + responseObserver.onError(unavailable("SpendCurrency")); } - private ErrorDetail unavailable(String operation) { + private RuntimeException unavailable(String operation) { String message = operation + " is unavailable"; - return meterRegistry == null - ? ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(message).build() - : GrpcAppErrors.error(meterRegistry, logger, operation, "FAILED_PRECONDITION", message); + ErrorDetail detail = + meterRegistry == null + ? ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(message).build() + : GrpcAppErrors.error(meterRegistry, logger, operation, "FAILED_PRECONDITION", message); + return StatusProto.toStatusRuntimeException( + com.google.rpc.Status.newBuilder() + .setCode(Status.Code.FAILED_PRECONDITION.value()) + .setMessage(message) + .addDetails(Any.pack(detail)) + .build()); } } diff --git a/services/account-service/src/main/resources/openapi.yaml b/services/account-service/src/main/resources/openapi.yaml index d0b963a010..4745356dd3 100644 --- a/services/account-service/src/main/resources/openapi.yaml +++ b/services/account-service/src/main/resources/openapi.yaml @@ -586,13 +586,11 @@ paths: summary: Verify email token operationId: verifyEmail description: >- - Target state is a public token-verification endpoint. In the current - deployment the POST route is not in the public-route allowlist and - therefore requires bearer authentication; the allowlisted GET route - has no controller mapping. Do not treat this operation as publicly - reachable until the HTTP configuration and link handoff converge. - security: - - bearerAuth: [] + The public POST verifies an account-scoped email token without bearer + authentication. The configured verification email still links to + GET /auth/verify-email, which has no controller mapping; browser + handoff to the public POST remains unavailable. + security: [] requestBody: required: true content: diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java index a39851e3a7..da8d99a809 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java @@ -11,6 +11,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.io.IOException; +import java.util.List; +import java.util.Map; import net.firedevops.firemud.accountservice.controller.AuthController; import net.firedevops.firemud.accountservice.dto.VerifyEmailRequest; import net.firedevops.firemud.accountservice.service.AccountService; @@ -31,6 +33,7 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.yaml.snakeyaml.Yaml; /** Actual Account YAML and servlet-auth composition with a mocked verification owner. */ class EmailVerificationHttpAuthWiringTest { @@ -39,6 +42,7 @@ class EmailVerificationHttpAuthWiringTest { @ParameterizedTest @ValueSource(booleans = {false, true}) void publicPostReachesMappedVerificationOwnerWithoutBearer(boolean productionLayer) { + assertOpenApiDeclaresPublicPost(); JwtUtil jwtUtil = mock(JwtUtil.class); configuredRunner(productionLayer, jwtUtil) .run( @@ -151,4 +155,20 @@ private static WebApplicationContextRunner configuredRunner( } }); } + + private static void assertOpenApiDeclaresPublicPost() { + try (var input = + EmailVerificationHttpAuthWiringTest.class.getResourceAsStream("/openapi.yaml")) { + Map document = new Yaml().load(input); + Map paths = (Map) document.get("paths"); + Map verifyEmailPath = (Map) paths.get(PATH); + Map operation = (Map) verifyEmailPath.get("post"); + + assertThat(operation.get("operationId")).isEqualTo("verifyEmail"); + assertThat(operation.containsKey("security")).isTrue(); + assertThat(operation.get("security")).isEqualTo(List.of()); + } catch (IOException exception) { + throw new IllegalStateException("Could not load Account OpenAPI YAML", exception); + } + } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 9de596c0ad..10d8482cf3 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -8,6 +8,7 @@ import io.grpc.Context; import io.grpc.Status; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; @@ -2758,19 +2759,12 @@ void exportAccountDeniesCanonicalSelectorBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = new RecordingObserver<>(); + FailureObserver observer = new FailureObserver<>(); service.exportAccount( ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_UUID).build(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertTrue(observer.response().getAccountJson().isEmpty()); - assertTrue(observer.response().getProfilesJson().isEmpty()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -2779,18 +2773,11 @@ void exportAccountDeniesAbsentSelectorBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = new RecordingObserver<>(); + FailureObserver observer = new FailureObserver<>(); service.exportAccount(ExportAccountRequest.getDefaultInstance(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertTrue(observer.response().getAccountJson().isEmpty()); - assertTrue(observer.response().getProfilesJson().isEmpty()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -2800,21 +2787,13 @@ void exportTenantDataDeniesCanonicalRequestBeforeOwnerLookup() { AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService, null, WORKLOAD_NAMESPACE); - RecordingObserver observer = new RecordingObserver<>(); + FailureObserver observer = new FailureObserver<>(); service.exportTenantData( ExportTenantDataRequest.newBuilder().setTenantId("1").setAccountId(ACCOUNT_UUID).build(), observer); - assertEquals(1, observer.nextCalls); - assertEquals(0, observer.receivedTransportError() ? 1 : 0); - assertEquals(1, observer.completedCalls); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertTrue(observer.response().getTenantId().isEmpty()); - assertTrue(observer.response().getAccountJson().isEmpty()); - assertTrue(observer.response().getProfileJson().isEmpty()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -2823,18 +2802,11 @@ void exportAccountDeniesMalformedSelectorBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = new RecordingObserver<>(); + FailureObserver observer = new FailureObserver<>(); service.exportAccount(ExportAccountRequest.newBuilder().setAccountId("0").build(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertTrue(observer.response().getAccountJson().isEmpty()); - assertTrue(observer.response().getProfilesJson().isEmpty()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -2844,19 +2816,11 @@ void exportTenantDataDeniesMalformedRequestBeforeParsing() { AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = new RecordingObserver<>(); + FailureObserver observer = new FailureObserver<>(); service.exportTenantData( ExportTenantDataRequest.newBuilder().setTenantId("0").setAccountId("2").build(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertTrue(observer.response().getTenantId().isEmpty()); - assertTrue(observer.response().getAccountJson().isEmpty()); - assertTrue(observer.response().getProfileJson().isEmpty()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -2924,8 +2888,8 @@ void linkExternalAccountDeniesCanonicalSelectorsBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = - new RecordingObserver<>(); + FailureObserver observer = + new FailureObserver<>(); service.linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() @@ -2936,13 +2900,7 @@ void linkExternalAccountDeniesCanonicalSelectorsBeforeOwnerLookup() { .build(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertFalse(observer.response().getSuccess()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -2951,8 +2909,8 @@ void linkExternalAccountDeniesMalformedSelectorsBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = - new RecordingObserver<>(); + FailureObserver observer = + new FailureObserver<>(); service.linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest.newBuilder() @@ -2963,13 +2921,7 @@ void linkExternalAccountDeniesMalformedSelectorsBeforeParsing() { .build(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertFalse(observer.response().getSuccess()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -2978,8 +2930,8 @@ void requestEmailVerificationDeniesMalformedSelectorBeforeParsing() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = - new RecordingObserver<>(); + FailureObserver observer = + new FailureObserver<>(); service.requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.newBuilder() @@ -2987,13 +2939,7 @@ void requestEmailVerificationDeniesMalformedSelectorBeforeParsing() { .build(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertFalse(observer.response().getSuccess()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -3002,18 +2948,11 @@ void exportAccountDeniesAbsentRequestBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = new RecordingObserver<>(); + FailureObserver observer = new FailureObserver<>(); service.exportAccount(null, observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertTrue(observer.response().getAccountJson().isEmpty()); - assertTrue(observer.response().getProfilesJson().isEmpty()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -3022,19 +2961,11 @@ void exportTenantDataDeniesAbsentSelectorsBeforeOwnerLookup() { AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(Mockito.mock(PingService.class), accountService); - RecordingObserver observer = new RecordingObserver<>(); + FailureObserver observer = new FailureObserver<>(); service.exportTenantData(ExportTenantDataRequest.getDefaultInstance(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertTrue(observer.response().getTenantId().isEmpty()); - assertTrue(observer.response().getAccountJson().isEmpty()); - assertTrue(observer.response().getProfileJson().isEmpty()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService); } @@ -3061,20 +2992,14 @@ void linkExternalAccountDeniesAbsentSelectorsBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = - new RecordingObserver<>(); + FailureObserver observer = + new FailureObserver<>(); service.linkExternalAccount( net.firedevops.firemud.account.v1.LinkExternalAccountRequest.getDefaultInstance(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertFalse(observer.response().getSuccess()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -3083,8 +3008,8 @@ void requestEmailVerificationDeniesCanonicalSelectorBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = - new RecordingObserver<>(); + FailureObserver observer = + new FailureObserver<>(); service.requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.newBuilder() @@ -3092,13 +3017,7 @@ void requestEmailVerificationDeniesCanonicalSelectorBeforeOwnerLookup() { .build(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertFalse(observer.response().getSuccess()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -3107,20 +3026,14 @@ void requestEmailVerificationDeniesAbsentSelectorBeforeOwnerLookup() { PingService pingService = Mockito.mock(PingService.class); AccountService accountService = Mockito.mock(AccountService.class); AccountGrpcService service = new AccountGrpcService(pingService, accountService); - RecordingObserver observer = - new RecordingObserver<>(); + FailureObserver observer = + new FailureObserver<>(); service.requestEmailVerification( net.firedevops.firemud.account.v1.RequestEmailVerificationRequest.getDefaultInstance(), observer); - assertEquals("FAILED_PRECONDITION", observer.response().getError().getCode()); - assertEquals( - "No authorized internal caller is configured", observer.response().getError().getMessage()); - assertFalse(observer.response().getSuccess()); - assertEquals(1, observer.nextCalls); - assertEquals(1, observer.completedCalls); - assertFalse(observer.receivedTransportError()); + observer.assertUnconfiguredCallerRefusal(); Mockito.verifyNoInteractions(accountService, pingService); } @@ -3152,6 +3065,50 @@ public void onCompleted() {} assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); } + private static final class FailureObserver implements StreamObserver { + private Status transportStatus; + private com.google.rpc.Status rpcStatus; + private int nextCalls; + private int errorCalls; + private int completedCalls; + + @Override + public void onNext(T value) { + nextCalls++; + } + + @Override + public void onError(Throwable throwable) { + transportStatus = Status.fromThrowable(throwable); + rpcStatus = StatusProto.fromThrowable(throwable); + errorCalls++; + } + + @Override + public void onCompleted() { + completedCalls++; + } + + private void assertUnconfiguredCallerRefusal() { + assertEquals(0, nextCalls); + assertEquals(0, completedCalls); + assertEquals(1, errorCalls); + assertNotNull(transportStatus); + assertEquals(Status.Code.FAILED_PRECONDITION, transportStatus.getCode()); + assertNotNull(rpcStatus); + assertEquals(Status.Code.FAILED_PRECONDITION.value(), rpcStatus.getCode()); + assertEquals("No authorized internal caller is configured", rpcStatus.getMessage()); + assertEquals(1, rpcStatus.getDetailsCount()); + assertEquals( + com.google.protobuf.Any.pack( + ErrorDetail.newBuilder() + .setCode("FAILED_PRECONDITION") + .setMessage("No authorized internal caller is configured") + .build()), + rpcStatus.getDetails(0)); + } + } + private static final class RecordingObserver implements StreamObserver { private T response; private boolean receivedTransportError; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/DeferredAccountGrpcTransportTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/DeferredAccountGrpcTransportTest.java new file mode 100644 index 0000000000..a450ac7b7a --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/DeferredAccountGrpcTransportTest.java @@ -0,0 +1,210 @@ +package net.firedevops.firemud.accountservice.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.protobuf.StatusProto; +import io.micrometer.core.instrument.Meter; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.net.InetSocketAddress; +import java.util.List; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountServiceGrpc; +import net.firedevops.firemud.account.v1.AddCurrencyRequest; +import net.firedevops.firemud.account.v1.ExportAccountRequest; +import net.firedevops.firemud.account.v1.ExportTenantDataRequest; +import net.firedevops.firemud.account.v1.GetBalanceRequest; +import net.firedevops.firemud.account.v1.LinkExternalAccountRequest; +import net.firedevops.firemud.account.v1.RequestEmailVerificationRequest; +import net.firedevops.firemud.account.v1.SpendCurrencyRequest; +import net.firedevops.firemud.account.v1.VirtualCurrencyServiceGrpc; +import net.firedevops.firemud.accountservice.service.AccountService; +import net.firedevops.firemud.accountservice.service.PingService; +import net.firedevops.firemud.common.grpc.MetricsInterceptor; +import net.firedevops.firemud.shared.v1.ErrorDetail; +import org.junit.jupiter.api.Test; + +/** Transport-only loopback proof; workload TLS and authorization belong to the peer fixtures. */ +class DeferredAccountGrpcTransportTest { + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; + private static final String CALLER_UNAVAILABLE = "No authorized internal caller is configured"; + + @Test + void allSevenDeferredAdaptersReturnNonOkDetailsWithoutOwnerAccessOnRepeatedCalls() + throws Exception { + AccountService owner = mock(AccountService.class); + PingService ping = mock(PingService.class); + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + try { + registry.config().commonTags("service", "account-service"); + try (TransportServer server = startServer(owner, ping, registry); + ClientTransport client = + new ClientTransport( + NettyChannelBuilder.forAddress("127.0.0.1", server.port()) + .usePlaintext() + .build())) { + var account = AccountServiceGrpc.newBlockingStub(client.channel()); + var currency = VirtualCurrencyServiceGrpc.newBlockingStub(client.channel()); + List calls = + List.of( + new Refusal( + () -> + currency + .withDeadlineAfter(5, TimeUnit.SECONDS) + .getBalance( + GetBalanceRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .build()), + "GetBalance is unavailable"), + new Refusal( + () -> + currency + .withDeadlineAfter(5, TimeUnit.SECONDS) + .addCurrency( + AddCurrencyRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .setAmount(10) + .build()), + "AddCurrency is unavailable"), + new Refusal( + () -> + currency + .withDeadlineAfter(5, TimeUnit.SECONDS) + .spendCurrency( + SpendCurrencyRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .setAmount(5) + .build()), + "SpendCurrency is unavailable"), + new Refusal( + () -> + account + .withDeadlineAfter(5, TimeUnit.SECONDS) + .exportAccount( + ExportAccountRequest.newBuilder().setAccountId(ACCOUNT_ID).build()), + CALLER_UNAVAILABLE), + new Refusal( + () -> + account + .withDeadlineAfter(5, TimeUnit.SECONDS) + .exportTenantData( + ExportTenantDataRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .build()), + CALLER_UNAVAILABLE), + new Refusal( + () -> + account + .withDeadlineAfter(5, TimeUnit.SECONDS) + .linkExternalAccount( + LinkExternalAccountRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setProvider("example") + .setExternalId("untrusted-subject") + .build()), + CALLER_UNAVAILABLE), + new Refusal( + () -> + account + .withDeadlineAfter(5, TimeUnit.SECONDS) + .requestEmailVerification( + RequestEmailVerificationRequest.newBuilder() + .setAccountId(ACCOUNT_ID) + .build()), + CALLER_UNAVAILABLE)); + + int refusedCalls = 0; + for (int attempt = 0; attempt < 2; attempt++) { + for (Refusal call : calls) { + assertRefused(call); + refusedCalls++; + verifyNoInteractions(owner, ping); + assertEquals( + (double) refusedCalls, + registry + .get("grpc.app_error") + .tags("service", "account-service", "code", "FAILED_PRECONDITION") + .counter() + .count()); + } + } + List errorMeters = + registry.getMeters().stream() + .filter(meter -> meter.getId().getName().equals("grpc.app_error")) + .toList(); + assertEquals(1, errorMeters.size()); + assertEquals( + List.of("code", "service"), + errorMeters.get(0).getId().getTags().stream().map(tag -> tag.getKey()).toList()); + } + } finally { + registry.close(); + } + } + + private static void assertRefused(Refusal call) throws Exception { + StatusRuntimeException error = assertThrows(StatusRuntimeException.class, call.invoke()::run); + assertEquals(Status.Code.FAILED_PRECONDITION, error.getStatus().getCode()); + assertEquals(call.message(), error.getStatus().getDescription()); + com.google.rpc.Status status = StatusProto.fromThrowable(error); + assertNotNull(status); + assertEquals(Status.Code.FAILED_PRECONDITION.value(), status.getCode()); + assertEquals(call.message(), status.getMessage()); + assertEquals(1, status.getDetailsCount()); + assertEquals( + ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(call.message()).build(), + status.getDetails(0).unpack(ErrorDetail.class)); + } + + private static TransportServer startServer( + AccountService owner, PingService ping, SimpleMeterRegistry registry) throws Exception { + return new TransportServer( + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .intercept(new MetricsInterceptor(registry)) + .addService(new AccountGrpcService(ping, owner, registry)) + .addService(new VirtualCurrencyGrpcService(registry)) + .build() + .start()); + } + + private record Refusal(Runnable invoke, String message) {} + + private record TransportServer(Server server) implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + if (!server.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback deferred Account server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback deferred Account client did not terminate"); + } + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java index 139dddb6fe..c8d24fc805 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyGrpcServiceTest.java @@ -2,187 +2,157 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.protobuf.StatusProto; import io.grpc.stub.StreamObserver; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.ArrayList; import java.util.List; +import java.util.function.Consumer; import net.firedevops.firemud.account.v1.AddCurrencyRequest; import net.firedevops.firemud.account.v1.AddCurrencyResponse; import net.firedevops.firemud.account.v1.GetBalanceRequest; import net.firedevops.firemud.account.v1.GetBalanceResponse; import net.firedevops.firemud.account.v1.SpendCurrencyRequest; import net.firedevops.firemud.account.v1.SpendCurrencyResponse; -import net.firedevops.firemud.accountservice.service.VirtualCurrencyService; +import net.firedevops.firemud.shared.v1.ErrorDetail; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; class VirtualCurrencyGrpcServiceTest { - @Test - void getBalanceFailsClosedForRepeatedValidRequestsWithoutReadingBalance() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, meterRegistry); - List responses = new ArrayList<>(); - CompletionCounter completions = new CompletionCounter(); - - StreamObserver observer = collecting(responses, completions); - GetBalanceRequest request = - GetBalanceRequest.newBuilder() - .setTenantId("1") - .setAccountId("11111111-1111-4111-8111-111111111111") - .setCurrencyCode("GOLD") - .build(); - service.getBalance(request, observer); - service.getBalance(request, observer); - - assertUnavailable(responses, completions, 2, "GetBalance is unavailable"); - assertAppErrorCount(meterRegistry, 2); - Mockito.verifyNoInteractions(currencyService); - } + private static final String ACCOUNT_ID = "11111111-1111-4111-8111-111111111111"; @Test - void addCurrencyFailsClosedForRepeatedValidRequestsWithoutAddingCurrency() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, meterRegistry); - List responses = new ArrayList<>(); - CompletionCounter completions = new CompletionCounter(); - - StreamObserver observer = collecting(responses, completions); - AddCurrencyRequest request = - AddCurrencyRequest.newBuilder() - .setTenantId("1") - .setAccountId("11111111-1111-4111-8111-111111111111") - .setCurrencyCode("GOLD") - .setAmount(10) - .build(); - service.addCurrency(request, observer); - service.addCurrency(request, observer); - - assertUnavailable(responses, completions, 2, "AddCurrency is unavailable"); - assertAppErrorCount(meterRegistry, 2); - Mockito.verifyNoInteractions(currencyService); + void getBalanceFailsClosedForRepeatedValidRequests() throws Exception { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + try { + VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(registry); + GetBalanceRequest request = + GetBalanceRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .build(); + assertRepeatedRefusal( + (StreamObserver observer) -> service.getBalance(request, observer), + "GetBalance is unavailable"); + assertAppErrorCount(registry, 2); + } finally { + registry.close(); + } } @Test - void spendCurrencyFailsClosedForRepeatedValidRequestsWithoutSpendingCurrency() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - VirtualCurrencyGrpcService service = - new VirtualCurrencyGrpcService(currencyService, meterRegistry); - List responses = new ArrayList<>(); - CompletionCounter completions = new CompletionCounter(); - - StreamObserver observer = collecting(responses, completions); - SpendCurrencyRequest request = - SpendCurrencyRequest.newBuilder() - .setTenantId("1") - .setAccountId("11111111-1111-4111-8111-111111111111") - .setCurrencyCode("GOLD") - .setAmount(5) - .build(); - service.spendCurrency(request, observer); - service.spendCurrency(request, observer); - - assertUnavailable(responses, completions, 2, "SpendCurrency is unavailable"); - assertAppErrorCount(meterRegistry, 2); - Mockito.verifyNoInteractions(currencyService); + void addCurrencyFailsClosedForRepeatedValidRequests() throws Exception { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + try { + VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(registry); + AddCurrencyRequest request = + AddCurrencyRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .setAmount(10) + .build(); + assertRepeatedRefusal( + (StreamObserver observer) -> service.addCurrency(request, observer), + "AddCurrency is unavailable"); + assertAppErrorCount(registry, 2); + } finally { + registry.close(); + } } @Test - void singleArgumentConstructorFailsClosedWithoutOwnerAccess() { - VirtualCurrencyService currencyService = Mockito.mock(VirtualCurrencyService.class); - VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(currencyService); - List balanceResponses = new ArrayList<>(); - List addResponses = new ArrayList<>(); - List spendResponses = new ArrayList<>(); - CompletionCounter balanceCompletions = new CompletionCounter(); - CompletionCounter addCompletions = new CompletionCounter(); - CompletionCounter spendCompletions = new CompletionCounter(); - - service.getBalance( - GetBalanceRequest.newBuilder() - .setTenantId("1") - .setAccountId("11111111-1111-4111-8111-111111111111") - .setCurrencyCode("GOLD") - .build(), - collecting(balanceResponses, balanceCompletions)); - service.addCurrency( - AddCurrencyRequest.newBuilder() - .setTenantId("1") - .setAccountId("11111111-1111-4111-8111-111111111111") - .setCurrencyCode("GOLD") - .setAmount(10) - .build(), - collecting(addResponses, addCompletions)); - service.spendCurrency( - SpendCurrencyRequest.newBuilder() - .setTenantId("1") - .setAccountId("11111111-1111-4111-8111-111111111111") - .setCurrencyCode("GOLD") - .setAmount(5) - .build(), - collecting(spendResponses, spendCompletions)); - - assertUnavailable(balanceResponses, balanceCompletions, 1, "GetBalance is unavailable"); - assertUnavailable(addResponses, addCompletions, 1, "AddCurrency is unavailable"); - assertUnavailable(spendResponses, spendCompletions, 1, "SpendCurrency is unavailable"); - Mockito.verifyNoInteractions(currencyService); + void spendCurrencyFailsClosedForRepeatedValidRequests() throws Exception { + SimpleMeterRegistry registry = new SimpleMeterRegistry(); + try { + VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(registry); + SpendCurrencyRequest request = + SpendCurrencyRequest.newBuilder() + .setTenantId("1") + .setAccountId(ACCOUNT_ID) + .setCurrencyCode("GOLD") + .setAmount(5) + .build(); + assertRepeatedRefusal( + (StreamObserver observer) -> + service.spendCurrency(request, observer), + "SpendCurrency is unavailable"); + assertAppErrorCount(registry, 2); + } finally { + registry.close(); + } } - private static StreamObserver collecting( - List responses, CompletionCounter completions) { - return new StreamObserver<>() { - @Override - public void onNext(T value) { - responses.add(value); - } - - @Override - public void onError(Throwable error) { - throw new AssertionError("Expected an application-level fail-closed response", error); - } - - @Override - public void onCompleted() { - completions.count++; - } - }; + @Test + void nullRegistryStillRefusesAllOperationsBeforeInspectingRequests() throws Exception { + VirtualCurrencyGrpcService service = new VirtualCurrencyGrpcService(null); + assertRepeatedRefusal( + (StreamObserver observer) -> service.getBalance(null, observer), + "GetBalance is unavailable"); + assertRepeatedRefusal( + (StreamObserver observer) -> service.addCurrency(null, observer), + "AddCurrency is unavailable"); + assertRepeatedRefusal( + (StreamObserver observer) -> service.spendCurrency(null, observer), + "SpendCurrency is unavailable"); } - private static void assertUnavailable( - List responses, CompletionCounter completions, int expectedCalls, String message) { - assertEquals(expectedCalls, responses.size()); - assertEquals(expectedCalls, completions.count); - for (Object response : responses) { - assertNotNull(response); - if (response instanceof GetBalanceResponse getBalanceResponse) { - assertEquals("FAILED_PRECONDITION", getBalanceResponse.getError().getCode()); - assertEquals(message, getBalanceResponse.getError().getMessage()); - } else if (response instanceof AddCurrencyResponse addCurrencyResponse) { - assertEquals("FAILED_PRECONDITION", addCurrencyResponse.getError().getCode()); - assertEquals(message, addCurrencyResponse.getError().getMessage()); - } else if (response instanceof SpendCurrencyResponse spendCurrencyResponse) { - assertEquals("FAILED_PRECONDITION", spendCurrencyResponse.getError().getCode()); - assertEquals(message, spendCurrencyResponse.getError().getMessage()); - } else { - throw new AssertionError("Unexpected response type: " + response.getClass()); - } + private static void assertRepeatedRefusal(Consumer> call, String message) + throws Exception { + for (int attempt = 0; attempt < 2; attempt++) { + RecordingObserver observer = new RecordingObserver<>(); + call.accept(observer); + assertTrue(observer.responses.isEmpty()); + assertEquals(0, observer.completions); + assertEquals(1, observer.errors.size()); + Throwable error = observer.errors.get(0); + assertTrue(error instanceof StatusRuntimeException); + assertEquals(Status.Code.FAILED_PRECONDITION, Status.fromThrowable(error).getCode()); + assertEquals(message, Status.fromThrowable(error).getDescription()); + com.google.rpc.Status status = StatusProto.fromThrowable(error); + assertNotNull(status); + assertEquals(Status.Code.FAILED_PRECONDITION.value(), status.getCode()); + assertEquals(message, status.getMessage()); + assertEquals(1, status.getDetailsCount()); + assertEquals( + ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").setMessage(message).build(), + status.getDetails(0).unpack(ErrorDetail.class)); } } - private static void assertAppErrorCount(MeterRegistry meterRegistry, int expectedCount) { + private static void assertAppErrorCount(MeterRegistry registry, int expectedCount) { assertEquals( (double) expectedCount, - meterRegistry.get("grpc.app_error").tag("code", "FAILED_PRECONDITION").counter().count()); - assertEquals(1, meterRegistry.getMeters().size()); + registry.get("grpc.app_error").tag("code", "FAILED_PRECONDITION").counter().count()); + assertEquals(1, registry.getMeters().size()); + assertEquals( + List.of("code"), + registry.getMeters().get(0).getId().getTags().stream().map(tag -> tag.getKey()).toList()); } - private static final class CompletionCounter { - private int count; + private static final class RecordingObserver implements StreamObserver { + private final List responses = new ArrayList<>(); + private final List errors = new ArrayList<>(); + private int completions; + + @Override + public void onNext(T value) { + responses.add(value); + } + + @Override + public void onError(Throwable error) { + errors.add(error); + } + + @Override + public void onCompleted() { + completions++; + } } } From 3c4295571a2b5404dac7272a83c319a071b2071d Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:35:12 +1300 Subject: [PATCH 10/16] Explain explicit recovery of invalid local certificate bundles --- design/project-management/ai-observations.md | 3 +++ .../implementation-tracking/player-access-and-session.md | 2 +- dev-tools/certs/README.md | 2 +- dev-tools/certs/generate-dev-certs.sh | 3 +++ dev-tools/tests/dev-certs-retention-contract.sh | 8 ++++++-- 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index acc9130285..5d04c0dc34 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -19,3 +19,6 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): Recovery from a pending patch call needs a fresh file read. - Root saw a patch call remain pending and later used an alternate edit without rereading after that call ended. The original patch had landed, so the local certificate test briefly contained duplicate fixture setup. Diff inspection caught and removed it before publication, and the corrected contract was rerun successfully. Next: inspect current scoped bytes after an uncertain mutation before constructing recovery; a pending result does not establish that no edit occurred. + +- `2026-11-01` (Pacific/Auckland): Local executable mode loss and a later successful check masked certificate-contract failure. + - During #3367 CLI4 qualification, `generate-dev-certs.sh` was tracked as `100755` but locally `0644` with `core.filemode=false`; `ensure-dev-certs.sh` therefore failed to execute it. The multi-command caller lacked failure propagation and returned the later documentation check’s success. Root inspected the failed contract log, restored only the generator’s tracked executable permission, and reran the contract and ShellCheck with explicit fail-fast propagation; both pass. The original failure remains retained in R1425 and was reported to Overseer. The mode-change cause is unproven; on recurrence, capture the affected file’s mode before and after the scoped mutation rather than changing unrelated worktrees. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 1269a5284c..4be2f28d1f 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -654,7 +654,7 @@ R1418 additionally contains the legacy account-targeted `ExportTenantData` gRPC The same local containment suspends the unused `ExportAccount`, caller-asserted `LinkExternalAccount` and Account-ID `RequestEmailVerification` gRPC adapters before request parsing or owner access. Target export/link capabilities and an authorized internal verification-initiation caller remain incomplete. Separately authorized REST/service exports, neutral email-based initiation and the stronger token-based reset/verification owners remain. The combined current gate passes all 172 selected cases (163 Account unit/loopback cases, including eleven physical mTLS and six actual-profile HTTP wiring cases, plus nine actual PostgreSQL/Spring cases) with zero failures, errors or skips, selected main/test/integration static analysis, full formatting, fresh packaging and documentation checks. The three public-v1 JOIN cases prove actual commit followed by lost acknowledgement/readback, rollback followed by same-original continuation, and unchanged retained committed evidence after scope expiry. Controlled routing/caller inputs and injected failures establish no deployed RPC recovery or production authority. Public POST verification is selected by actual base/prod YAML; GET supplies no verification route or bypass. The email-link/browser handoff remains outside this local API proof. -R1425 corrects the seven disabled Account/currency adapters to non-OK `FAILED_PRECONDITION` with bounded structured status details, retaining error metrics and no owner access. The Account RPC unit cases and a repeated-call loopback transport fixture cover this boundary; OpenAPI now declares the existing bearerless verification POST, with its base/prod HTTP wiring proof retained. All 154 selected cases pass with zero failures, errors or skips: 143 Account RPC, four currency adapter, one repeated-call real loopback gRPC, and six base/prod HTTP composition cases. The loopback fixture checks all seven adapters twice, precise status/details, zero injected owner calls and bounded error-counter labels/counts, with checked transport cleanup. After correcting the fixture compilation and replacing retained mutable-Throwable capture with immutable status capture, the fresh consolidated gate passes all 154 cases, enabled Account main/test Checkstyle and SpotBugs, full formatting, boot-jar packaging and documentation checks. Fresh packaged-runtime proof remains pending. These fixtures do not establish workload TLS, supported export/link/currency operations or browser email-link handoff. +R1425 corrects the seven disabled Account/currency adapters to non-OK `FAILED_PRECONDITION` with bounded structured status details, retaining error metrics and no owner access. The Account RPC unit cases and a repeated-call loopback transport fixture cover this boundary; OpenAPI now declares the existing bearerless verification POST, with its base/prod HTTP wiring proof retained. All 154 selected cases pass with zero failures, errors or skips: 143 Account RPC, four currency adapter, one repeated-call real loopback gRPC, and six base/prod HTTP composition cases. The loopback fixture checks all seven adapters twice, precise status/details, zero injected owner calls and bounded error-counter labels/counts, with checked transport cleanup. After correcting the fixture compilation and replacing retained mutable-Throwable capture with immutable status capture, the fresh consolidated gate passes all 154 cases, enabled Account main/test Checkstyle and SpotBugs, full formatting, boot-jar packaging and documentation checks. Fresh jars and all eleven images at `13953d4c18f452dc84f748d3f625e1eeb9220ca0` pass the canonical held-admission smoke. Authenticated teardown and independent exact-project checks find no remaining containers, networks or volumes. A later diagnostic-only certificate recovery message changes no application/image behavior. These fixtures do not establish workload TLS, supported export/link/currency operations or browser email-link handoff. R1418 subsequently carries published #3365 parent `1d2b862ea5a176f9c7e08dd3a0d76ee2056b9503` into local receiving source `863797ec59361deee0225a40804dcdaf08fd0d86` and freshly rebuilds jars and images for the canonical held-admission smoke. The direct backend LOGIN → PLAY → LOOK proof and Gateway/Telnet denial qualification pass; authenticated teardown succeeds, and independent exact-project checks find no containers, networks or volumes. This qualifies the bounded local Entity credential fixture and current contained startup, not successful public Gateway/Telnet admission, production credential authority, audit delivery, unknown-outcome observation or lawful release. The 172-case aggregate above retains its earlier code-source attribution; the inherited direct-text carry does not change those Account implementation or test bytes. diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index bd24032c7f..54fe3dba50 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -6,7 +6,7 @@ Generated certificate outputs in this directory are ignored by Git and should no ## Script Map -- `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target or `CERT_DIR` is provided. A complete retained bundle is validated for certificate/key/CA agreement and reused without changing bytes or permissions. Incomplete or invalid retained material fails closed; preserve it and select a fresh dedicated directory for replacement material. The implicit script-local default resolves its directory physically. Explicit caller paths and all managed certificate entries and their directory ancestors are checked before writes; symlinks, nonregular files, and hardlinked files are refused. Generation changes only its named outputs, leaving unrelated entries untouched. +- `dev-tools/certs/generate-dev-certs.sh` writes into `dev-tools/certs/` when no explicit target or `CERT_DIR` is provided. A complete retained bundle is validated for certificate/key/CA agreement and reused without changing bytes or permissions. Incomplete or invalid retained material fails closed without automatic replacement. For disposable generated local material, including the default bundle after its 365-day validity expires, explicitly run `bash dev-tools/certs/clean-dev-certs.sh` with the same target (or no target for the default) and retry. Preserve externally managed material and select a fresh dedicated directory instead. The implicit script-local default resolves its directory physically. Explicit caller paths and all managed certificate entries and their directory ancestors are checked before writes; symlinks, nonregular files, and hardlinked files are refused. Generation changes only its named outputs, leaving unrelated entries untouched. - `dev-tools/certs/generate-dev-certs.sh --workload` signs a local development or test-only gRPC workload leaf for any of the eleven Java application workload identities, with the exact SPIFFE URI and service DNS SANs. This mode requires fresh output paths; callers stage replacement leaves before installing them. Ordinary local development uses the dedicated per-workload helper described below; run-owned smoke uses the qualified fixture described below. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. - Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume eight cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. - `dev-tools/certs/ensure-local-compose-mtls.sh` owns ordinary local development certificates for all eleven application workloads. See [ordinary local Compose setup and retained-certificate recovery](../../docker/README.md#local-compose-mtls-certificate-recovery); this authority remains separate from run-owned smoke fixtures. diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index 1a9bedd128..db5eb61351 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -171,6 +171,9 @@ if ((retained)); then done if (( ! valid )); then echo "Invalid retained development certificate bundle; refusing to replace material: $CERT_DIR" >&2 + echo "Only for disposable generated local material (for example expired), explicitly clean and retry:" >&2 + printf ' bash %q %q\n' "$SCRIPT_DIR/clean-dev-certs.sh" "$CERT_DIR" >&2 + echo "Preserve externally managed material; select a fresh dedicated directory instead." >&2 exit 1 fi echo "Dev certificates already exist in $CERT_DIR" diff --git a/dev-tools/tests/dev-certs-retention-contract.sh b/dev-tools/tests/dev-certs-retention-contract.sh index b38018e888..8403757944 100644 --- a/dev-tools/tests/dev-certs-retention-contract.sh +++ b/dev-tools/tests/dev-certs-retention-contract.sh @@ -83,8 +83,12 @@ for corruption in malformed key ca ca-key; do ca) cp -- "$other/ca.crt" "$fixture/ca.crt"; cp -- "$other/ca.key" "$fixture/ca.key"; cp -- "$other/dev-ca.pem" "$fixture/dev-ca.pem" ;; ca-key) cp -- "$other/ca.key" "$fixture/ca.key" ;; esac - expect_unchanged_failure "$fixture" "Invalid retained development certificate bundle" bash "$GENERATOR" "$fixture" - expect_unchanged_failure "$fixture" "Invalid retained development certificate bundle" bash "$ENSURE" "$fixture" + for command in "$GENERATOR" "$ENSURE"; do + expect_unchanged_failure "$fixture" "Invalid retained development certificate bundle" bash "$command" "$fixture" + grep -Fq 'Only for disposable generated local material' "$TEST_ROOT/failure-stderr" + grep -Fq 'clean-dev-certs.sh ' "$TEST_ROOT/failure-stderr" + grep -Fq 'Preserve externally managed material' "$TEST_ROOT/failure-stderr" + done done links="$TEST_ROOT/links" From 659317ffb2caba03c51c7edad52b9ff5eb537a4e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:45:02 +1300 Subject: [PATCH 11/16] Use nonrecursive find for retained certificate link checks --- dev-tools/certs/clean-dev-certs.sh | 6 ++++-- dev-tools/certs/generate-dev-certs.sh | 3 ++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/dev-tools/certs/clean-dev-certs.sh b/dev-tools/certs/clean-dev-certs.sh index 71b8f67ce4..0f3844ca11 100644 --- a/dev-tools/certs/clean-dev-certs.sh +++ b/dev-tools/certs/clean-dev-certs.sh @@ -46,8 +46,10 @@ generated_files=( removed_any=false for filename in "${generated_files[@]}"; do - if [[ -f "$CERT_DIR/$filename" && ! -L "$CERT_DIR/$filename" && "$(stat -c %h -- "$CERT_DIR/$filename")" == 1 ]]; then - rm -f -- "$CERT_DIR/$filename" + entry="$CERT_DIR/$filename" + [[ "$entry" == /* ]] || entry="$PWD/$entry" + if [[ -f "$entry" && ! -L "$entry" && -n "$(find "$entry" -prune -type f -links 1 -print)" ]]; then + rm -f -- "$entry" removed_any=true fi done diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index db5eb61351..1abc4c5734 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -20,8 +20,9 @@ require_safe_directory_path() { require_safe_file_path() { local path="$1" + [[ "$path" == /* ]] || path="$PWD/$path" require_safe_directory_path "$(dirname -- "$path")" || return 1 - if [[ -L "$path" || ( -e "$path" && ( ! -f "$path" || "$(stat -c %h -- "$path")" != 1 ) ) ]]; then + if [[ -L "$path" || ( -e "$path" && ( ! -f "$path" || -z "$(find "$path" -prune -type f -links 1 -print)" ) ) ]]; then echo "Certificate paths must be regular files without symlinks or hardlinks: $path" >&2 return 1 fi From 1c4563c0ef70c22088d5c0a25fb0118e75f598ec Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 09:54:40 +1300 Subject: [PATCH 12/16] Assert Account lock ordering before expired email-token refusal --- .../accountservice/service/impl/AccountServiceImplTest.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index 030cdb497a..50849be523 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -6396,6 +6396,10 @@ void verifyEmailRejectsExpiredAndExactlyExpiringTokenAfterAccountLock(boolean eq } assertFalse(current.isEmailVerified()); + org.mockito.InOrder order = + org.mockito.Mockito.inOrder(emailVerificationTokenRepository, accountRepository); + order.verify(emailVerificationTokenRepository).findByToken("tok"); + order.verify(accountRepository).findByIdForUpdate(1L); org.mockito.Mockito.verify(emailVerificationTokenRepository, org.mockito.Mockito.never()) .consumeIfUnexpired(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any()); org.mockito.Mockito.verify(accountRepository, org.mockito.Mockito.never()) From af5253889950cd6f5fd8439c99ea261bd35014a0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:10:51 +1300 Subject: [PATCH 13/16] Resolve certificate contract temporary roots physically --- dev-tools/tests/dev-certs-retention-contract.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev-tools/tests/dev-certs-retention-contract.sh b/dev-tools/tests/dev-certs-retention-contract.sh index 8403757944..9483f98d16 100644 --- a/dev-tools/tests/dev-certs-retention-contract.sh +++ b/dev-tools/tests/dev-certs-retention-contract.sh @@ -5,7 +5,7 @@ REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" GENERATOR="$REPO_ROOT/dev-tools/certs/generate-dev-certs.sh" ENSURE="$REPO_ROOT/dev-tools/certs/ensure-dev-certs.sh" CLEAN="$REPO_ROOT/dev-tools/certs/clean-dev-certs.sh" -TEST_ROOT="$(mktemp -d)" +TEST_ROOT="$(cd "$(mktemp -d)" && pwd -P)" trap 'rm -rf -- "$TEST_ROOT"' EXIT # Only inspect this test's own fixture; record links without following targets. From dba5460432ce66b2e1a8fc645c19096e4f523f46 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:28:33 +1300 Subject: [PATCH 14/16] Apply scoped Overseer stewardship to resolved observations --- design/project-management/ai-observations.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 5d04c0dc34..82164229d2 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -11,14 +11,8 @@ A small inbox for unresolved agent, tooling, environment, and workflow issues; s - `2026-11-01` (Pacific/Auckland): Java filesystem read-only checks can miss same-device bind mounts. - A proposed `Files.getFileStore(path).isReadOnly()` guard was rejected before implementation: OpenJDK 21 discovers Linux boundaries using device changes and can attribute a bind mount to an ancestor with different read-only state. Exact current-process mountinfo, visible ancestry and pre/post comparison now preserve the readers’ owner/AtomicWriter guards; twelve physical mount cases pass. Next: qualify actual kubelet projection provenance at the existing held deployment boundary; local read-only evidence does not establish it. See [Game Session projection compatibility](../architecture/microservices/game-session-service/operations.md#protected-readiness-projection-compatibility). -- `2026-11-01` (Pacific/Auckland): API helper inputs and reply-file shape required local recovery. - - A read-only helper correctly refused its supplied external proof directory. Root copied and hash-verified the authorized inputs inside the worktree, without changing permissions, then resumed it. The reply command help omitted the required JSON array-of-string-arrays shape, so Root read its validator to construct the response. Next: add a concise help example in the owning API wrapper; this was reported to Overseer and is not a repository runtime blocker. - - `2026-11-01` (Pacific/Auckland): A transient demo-owner authentication deadline terminated Entity startup. - #3367 runtime-images run `41227037637` failed after Entity’s single five-second Account call expired; Entity exited and held smoke observed missing health, while matching local source-built smoke had passed. Complete job logs identify the startup deadline, not an authorization rejection or image-profile mismatch. Thirteen focused cases now qualify bounded transient-only fixture retries, including a real loopback deadline/cancellation regression; fresh canonical image-lane held smoke at `6c63d74546` also passes, with independent empty-project cleanup. Remote replacement CI remains required. The underlying cold-start latency remains unknown; recurrence evidence and the exact run were reported to Overseer for tracking. -- `2026-11-01` (Pacific/Auckland): Recovery from a pending patch call needs a fresh file read. - - Root saw a patch call remain pending and later used an alternate edit without rereading after that call ended. The original patch had landed, so the local certificate test briefly contained duplicate fixture setup. Diff inspection caught and removed it before publication, and the corrected contract was rerun successfully. Next: inspect current scoped bytes after an uncertain mutation before constructing recovery; a pending result does not establish that no edit occurred. - - `2026-11-01` (Pacific/Auckland): Local executable mode loss and a later successful check masked certificate-contract failure. - During #3367 CLI4 qualification, `generate-dev-certs.sh` was tracked as `100755` but locally `0644` with `core.filemode=false`; `ensure-dev-certs.sh` therefore failed to execute it. The multi-command caller lacked failure propagation and returned the later documentation check’s success. Root inspected the failed contract log, restored only the generator’s tracked executable permission, and reran the contract and ShellCheck with explicit fail-fast propagation; both pass. The original failure remains retained in R1425 and was reported to Overseer. The mode-change cause is unproven; on recurrence, capture the affected file’s mode before and after the scoped mutation rather than changing unrelated worktrees. From 98cceee1e4053e16ce5ce25009b641c1855eb99a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:21:31 +1300 Subject: [PATCH 15/16] Explain recovery for incomplete retained development certificates --- dev-tools/certs/generate-dev-certs.sh | 3 +++ dev-tools/tests/dev-certs-retention-contract.sh | 8 ++++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index 1abc4c5734..0d8faef4df 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -151,6 +151,9 @@ if ((retained)); then for filename in "${required_files[@]}"; do if [[ ! -f "$CERT_DIR/$filename" ]]; then echo "Incomplete retained development certificate bundle; refusing to replace material: $CERT_DIR" >&2 + echo "Only for disposable generated local material (for example interrupted generation), explicitly clean and retry:" >&2 + printf ' bash %q %q\n' "$SCRIPT_DIR/clean-dev-certs.sh" "$CERT_DIR" >&2 + echo "Preserve externally managed material; select a fresh dedicated directory instead." >&2 exit 1 fi done diff --git a/dev-tools/tests/dev-certs-retention-contract.sh b/dev-tools/tests/dev-certs-retention-contract.sh index 9483f98d16..29d8549f99 100644 --- a/dev-tools/tests/dev-certs-retention-contract.sh +++ b/dev-tools/tests/dev-certs-retention-contract.sh @@ -69,8 +69,12 @@ bash "$ENSURE" "$fresh" >/dev/null partial="$TEST_ROOT/partial" mkdir "$partial" printf 'retained CA\n' >"$partial/ca.crt" -expect_unchanged_failure "$partial" "Incomplete retained development certificate bundle" bash "$GENERATOR" "$partial" -expect_unchanged_failure "$partial" "Incomplete retained development certificate bundle" bash "$ENSURE" "$partial" +for command in "$GENERATOR" "$ENSURE"; do + expect_unchanged_failure "$partial" "Incomplete retained development certificate bundle" bash "$command" "$partial" + grep -Fq 'Only for disposable generated local material' "$TEST_ROOT/failure-stderr" + grep -Fq 'clean-dev-certs.sh ' "$TEST_ROOT/failure-stderr" + grep -Fq 'Preserve externally managed material' "$TEST_ROOT/failure-stderr" +done other="$TEST_ROOT/other" bash "$GENERATOR" "$other" >"$TEST_ROOT/other-output" 2>&1 From 393600debfee7cf157d1b9561d3a4ff8c6e44362 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:15:50 +1300 Subject: [PATCH 16/16] Refuse expired workload certificate authorities before output writes --- dev-tools/certs/generate-dev-certs.sh | 4 ++ .../tests/dev-certs-retention-contract.sh | 41 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/dev-tools/certs/generate-dev-certs.sh b/dev-tools/certs/generate-dev-certs.sh index 0d8faef4df..772f7d8fa0 100755 --- a/dev-tools/certs/generate-dev-certs.sh +++ b/dev-tools/certs/generate-dev-certs.sh @@ -62,6 +62,10 @@ if [[ "${1:-}" == "--workload" ]]; then echo "Invalid workload certificate authority or mismatched key." >&2 exit 1 } + openssl verify -check_ss_sig -CAfile "$ca_cert" "$ca_cert" >/dev/null 2>&1 || { + echo "Invalid or expired workload certificate authority; refusing to sign workload certificate." >&2 + exit 1 + } for required_file in "$ca_cert" "$ca_key"; do [[ -f "$required_file" ]] || { echo "missing certificate authority file: $required_file" >&2 diff --git a/dev-tools/tests/dev-certs-retention-contract.sh b/dev-tools/tests/dev-certs-retention-contract.sh index 29d8549f99..5ae5f18ba5 100644 --- a/dev-tools/tests/dev-certs-retention-contract.sh +++ b/dev-tools/tests/dev-certs-retention-contract.sh @@ -49,6 +49,47 @@ expect_unchanged_failure() { fi } +expired_ca="$TEST_ROOT/expired-ca" +mkdir -p "$expired_ca/new-certs" +: >"$expired_ca/index.txt" +printf '1000\n' >"$expired_ca/serial" +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$expired_ca/ca.key" >/dev/null 2>&1 +openssl req -new -key "$expired_ca/ca.key" -subj '/CN=Expired-Workload-CA' -out "$expired_ca/ca.csr" +cat >"$expired_ca/openssl.cnf" </dev/null 2>&1 +openssl verify -no_check_time -check_ss_sig -CAfile "$expired_ca/ca.crt" "$expired_ca/ca.crt" >/dev/null +if openssl verify -check_ss_sig -CAfile "$expired_ca/ca.crt" "$expired_ca/ca.crt" >/dev/null 2>&1; then + echo 'Expired workload CA fixture unexpectedly verifies at the current time.' >&2 + exit 1 +fi +expect_unchanged_failure "$expired_ca" "Invalid or expired workload certificate authority" bash "$GENERATOR" --workload \ + "$expired_ca/ca.crt" "$expired_ca/ca.key" "$expired_ca/output/nested/client.crt" \ + "$expired_ca/output/nested/client.key" dev world-management-service +[[ ! -e "$expired_ca/output" ]] + fresh="$TEST_ROOT/fresh" mkdir "$fresh" printf 'foreign material\n' >"$fresh/foreign.pem"