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 1/2] 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 2/2] 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