From e7f1cd130d3736d700b472f23b0c284bc94f96dc Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sat, 7 Nov 2026 20:13:38 +1300 Subject: [PATCH 01/20] fix(gamesession): pin private LOGIN result lifetime through owned work --- .../player-access-and-session.md | 2 + .../dto/CanonicalGameplayLoginResult.java | 77 +++- .../service/InitialGameplayLoginOwner.java | 170 ++++++-- ...eplayLoginContextRedisIntegrationTest.java | 376 +++++++++++++++++- ...meplayLoginPhysicalCompositionFixture.java | 5 + .../dto/CanonicalGameplayLoginResultTest.java | 103 +++++ .../InitialGameplayLoginOwnerTest.java | 363 ++++++++++++++++- 7 files changed, 1050 insertions(+), 46 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 41a3e8d327..0df3e75f82 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -430,6 +430,8 @@ Account's private gameplay LOGIN implementation is source-only and remains unreg Canonical disposal and original-attempt rules belong to [JWT and token contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal), the [Redis initial-context acknowledgement owner](../../architecture/system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy), and [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status). Protected binding-history/restore qualification, production trust and custody, and runtime activation remain gaps; source fixtures do not establish authenticated intake or playable LOGIN. +The unregistered [initial LOGIN owner](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java) now pins the identical retained private result through each owned callback and drains existing borrows before transfer or custody-loss cleanup, without holding owner/result monitors across callbacks or SQL/Redis/Account work. Direct result closure also drains pins before erasure; reentrant lifecycle changes are refused and exact-original cleanup remains retryable after `HELD`. Focused owner/result units exercise identity, failure release, transfer, closure and concurrent draining. Three prepared additions to [physical LOGIN-context proof](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java) compose actual installed LOGIN bytes with retained non-admitting lobby storage and the SQL-row-to-result ordering. Physical execution is unrun locally because Docker is unavailable; controlled Account/transport/routing fixtures do not establish authenticated ingress association, backend-generation binding, reset qualification, registration, admission, activation or canonical PLAY Smoke readiness. + ### Account signer/currentness storage evidence preparation Account V99–V125 and the associated owner repositories, typed evidence carriers, mounted-bundle signer source, and validator-profile sources form a passive storage/evidence preparation only. The selected RPCs, coordinators, transport composition, provisioning, receiver execution, runtime registration, and consumer enforcement are not included or activated. The earlier local result of 727 Account and 154 Common Security cases is historical. The later local Account result is 738 cases with one skip; integration sources compiled, while local integration execution skipped 99 of 101 definitions without Docker. Exact-head hosted Account integration task 114264913703 passed on `607004fe786b2a9e1270a31c90f9031b486b3278` and is historical; its retained evidence does not expose per-suite case or skip counts. The later exact-head result at `7b79a8860baa6f08d3b4ae51d166f64ccf08004f` is also historical: hosted Account task 114304559873, Validation 38083268673, and artifact 11681094163 recorded physical PostgreSQL 18.6 readiness storage proof with 1 case, 70.952 seconds, and 0 skipped, including lawful expired-dispatch recovery. At `e63729562c39e664513bad2be2222e11a6886388`, the required Validation and Smoke checks passed. Hosted Account run 38088195334, task 114319172067, and artifact 11683606431 tested merge commit `05304721b3e705925b4344280a98a65c094f8823`, with parents `75e92718a983ac134cbb75fafbf173ac6b0360e0` and `e63729562c39e664513bad2be2222e11a6886388`, using immutable PostgreSQL 18.6 image `sha256:74935e72241653ca55e0414067e6d8763aceb8a810eb51b452253ec3dcfc4336`; the readiness and inventory suites each passed 2 of 2 cases with zero skips or failures. This is bounded storage proof with synthetic inventory/resource inputs, not evidence of live Kubernetes currentness, readiness activation, or signer activation. The AA-1.3 capability remains `partial` / `drift-found`; this subsection updates its passive anchors and proof limits without changing that state or closing a gate. Other capability rows and prior gates remain unchanged. Runtime readiness is not claimed. This preparation does not establish an issuer/currentness path or close `PLAY`, admission, or playable readiness; the canonical design remains [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md), with Account-local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status). diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java index 14b7c392cb..94b61a6315 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java @@ -9,12 +9,14 @@ import java.security.MessageDigest; import java.time.Clock; import java.util.Arrays; +import java.util.HashSet; import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.UUID; +import java.util.function.Function; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -64,6 +66,8 @@ public final class CanonicalGameplayLoginResult implements AutoCloseable { private final byte[] compactJwt; private final NonSecretEvidence evidence; private final Object lifecycleMutex = new Object(); + private final Set borrowers = new HashSet<>(); + private Thread closingThread; private boolean closed; private CanonicalGameplayLoginResult(byte[] compactJwt, NonSecretEvidence evidence) { @@ -294,20 +298,83 @@ private static UUID v4(String text) { public byte[] compactJwtBytes() { synchronized (lifecycleMutex) { - if (closed) throw new IllegalStateException("Canonical LOGIN private result is closed"); + if (closed || (closingThread != null && !borrowers.contains(Thread.currentThread()))) { + throw new IllegalStateException("Canonical LOGIN private result is closed"); + } return compactJwt.clone(); } } - /** Ends this invocation's owned compact-token custody and overwrites its private byte array. */ + /** + * Pins this identical process-local result and its private bytes through the callback. Closing + * refuses new pins and drains existing callbacks before erasure, without holding a monitor across + * callback work. A callback must not retain the result or perform reentrant lifecycle operations. + * This lifetime guard supplies no transport, currentness, or admission authority. + */ + public T withLivePrivateResult(Function action) { + Objects.requireNonNull(action, "Private result action required"); + Thread borrower = Thread.currentThread(); + synchronized (lifecycleMutex) { + if (closed || closingThread != null || !borrowers.add(borrower)) { + throw new IllegalStateException("Canonical LOGIN private result is unavailable"); + } + } + try { + return action.apply(this); + } finally { + synchronized (lifecycleMutex) { + borrowers.remove(borrower); + lifecycleMutex.notifyAll(); + } + } + } + + /** + * Refuses lifecycle mutation by this result's current callback thread, without changing state. + */ + public void requireNotBorrowedByCurrentThread() { + synchronized (lifecycleMutex) { + if (borrowers.contains(Thread.currentThread()) || closingThread == Thread.currentThread()) { + throw new IllegalStateException("Canonical LOGIN private result is borrowed"); + } + } + } + @Override public void close() { + boolean interrupted = false; synchronized (lifecycleMutex) { - if (!closed) { - Arrays.fill(compactJwt, (byte) 0); - closed = true; + if (borrowers.contains(Thread.currentThread()) || closingThread == Thread.currentThread()) { + throw new IllegalStateException("Canonical LOGIN private result is borrowed"); + } + while (closingThread != null) { + try { + lifecycleMutex.wait(); + } catch (InterruptedException interruption) { + interrupted = true; + } + } + if (closed) { + if (interrupted) Thread.currentThread().interrupt(); + return; } + closingThread = Thread.currentThread(); + while (!borrowers.isEmpty()) { + try { + lifecycleMutex.wait(); + } catch (InterruptedException interruption) { + interrupted = true; + } + } + } + // No callback or secret reader can start while erasure runs outside the lifecycle monitor. + Arrays.fill(compactJwt, (byte) 0); + synchronized (lifecycleMutex) { + closed = true; + closingThread = null; + lifecycleMutex.notifyAll(); } + if (interrupted) Thread.currentThread().interrupt(); } public NonSecretEvidence evidence() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java index a107392d88..0d3bc4a846 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java @@ -1,8 +1,11 @@ package net.firedevops.firemud.gamesession.service; +import java.util.HashSet; import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; +import java.util.function.Function; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; @@ -232,6 +235,8 @@ public static final class Outcome implements AutoCloseable { private CanonicalGameplayLoginResult transferredResult; private final Object lifecycleMutex = new Object(); private boolean resultTransferred; + private final Set borrowers = new HashSet<>(); + private Thread drainingThread; private boolean closed; private Optional custodyLossCleanup = Optional.empty(); @@ -293,43 +298,135 @@ public InitialGameplayLoginCleanupOwner.Status cleanupStatus() { return cleanupStatus; } - /** Transfers the verified private result exactly once to its receiving caller. */ - public Optional takePrivateResult() { + /** + * Borrows the identical installed result while this outcome retains ownership. Transfer, + * closure and retirement first block new borrows and drain existing callbacks. Neither owner + * nor result monitors cover callback work or cleanup I/O. Reentrant borrowing and lifecycle + * mutation are refused. This process-local guard supplies no transport or admission authority. + */ + public T withOwnedPrivateResult(Function action) { + Objects.requireNonNull(action, "Private result action required"); + Thread borrower = Thread.currentThread(); + CanonicalGameplayLoginResult result; synchronized (lifecycleMutex) { - if (closed) throw new IllegalStateException("Initial LOGIN outcome is closed"); - if (status != Status.INSTALLED_NON_ADMITTING) return Optional.empty(); - if (resultTransferred) - throw new IllegalStateException("Initial LOGIN result was transferred"); - resultTransferred = true; - CanonicalGameplayLoginResult result = privateResult; - privateResult = null; - transferredResult = result; - return Optional.of(result); + if (closed + || drainingThread != null + || resultTransferred + || privateResult == null + || !borrowers.add(borrower)) { + throw new IllegalStateException("Owned initial LOGIN result is unavailable"); + } + result = privateResult; + } + try { + return result.withLivePrivateResult(action); + } finally { + synchronized (lifecycleMutex) { + borrowers.remove(borrower); + lifecycleMutex.notifyAll(); + } + } + } + + private void beginDrain() { + CanonicalGameplayLoginResult retained; + synchronized (lifecycleMutex) { + if (borrowers.contains(Thread.currentThread()) + || drainingThread == Thread.currentThread()) { + throw new IllegalStateException("Initial LOGIN result is borrowed"); + } + retained = privateResult != null ? privateResult : transferredResult; + } + // A direct result callback must not wait behind a drain that is itself waiting for its pin. + // Check before any mutation, outside the Outcome monitor, including transferred custody. + if (retained != null) retained.requireNotBorrowedByCurrentThread(); + boolean interrupted = false; + synchronized (lifecycleMutex) { + while (drainingThread != null) { + try { + lifecycleMutex.wait(); + } catch (InterruptedException interruption) { + interrupted = true; + } + } + drainingThread = Thread.currentThread(); + while (!borrowers.isEmpty()) { + try { + lifecycleMutex.wait(); + } catch (InterruptedException interruption) { + interrupted = true; + } + } + } + if (interrupted) Thread.currentThread().interrupt(); + } + + private void endDrain() { + synchronized (lifecycleMutex) { + drainingThread = null; + lifecycleMutex.notifyAll(); + } + } + + /** Transfers the verified private result exactly once after draining owned borrows. */ + public Optional takePrivateResult() { + beginDrain(); + try { + synchronized (lifecycleMutex) { + if (closed) throw new IllegalStateException("Initial LOGIN outcome is closed"); + if (status != Status.INSTALLED_NON_ADMITTING) return Optional.empty(); + if (resultTransferred) + throw new IllegalStateException("Initial LOGIN result was transferred"); + resultTransferred = true; + CanonicalGameplayLoginResult result = privateResult; + privateResult = null; + transferredResult = result; + return Optional.of(result); + } + } finally { + endDrain(); } } /** - * Called only when the original pre-admission LOGIN custody is actually lost. This is not a - * retained-edge rebind or post-admission disconnect signal. It wipes this owner's retained - * result, then asks the existing owner to clean the exact original coordinates. + * Called only at actual original pre-admission custody loss, including after transfer or a HELD + * cleanup observation. It drains owned callbacks, erases the exact result and retries cleanup + * against the exact original coordinates. It is not a rebind or reset authority. */ public InitialGameplayLoginCleanupOwner.CleanupObservation abandonOriginalAfterCustodyLoss() { - synchronized (lifecycleMutex) { + beginDrain(); + try { if (status != Status.INSTALLED_NON_ADMITTING) { throw new IllegalStateException("Only an installed original LOGIN can be abandoned"); } - if (privateResult != null) { - privateResult.close(); - privateResult = null; - } - if (transferredResult != null) { - transferredResult.close(); - transferredResult = null; - } + eraseRetainedResults(true); + return recordOriginalCleanup(); + } finally { + endDrain(); + } + } + + private void eraseRetainedResults(boolean includeTransferred) { + CanonicalGameplayLoginResult retained; + synchronized (lifecycleMutex) { closed = true; - custodyLossCleanup = Optional.of(attemptOriginalCleanup()); - return custodyLossCleanup.orElseThrow(); + retained = + privateResult != null ? privateResult : includeTransferred ? transferredResult : null; + } + // Draining excludes new callbacks; result.close also drains direct result borrowers. + if (retained != null) retained.close(); + synchronized (lifecycleMutex) { + privateResult = null; + if (includeTransferred) transferredResult = null; + } + } + + private InitialGameplayLoginCleanupOwner.CleanupObservation recordOriginalCleanup() { + var observation = attemptOriginalCleanup(); + synchronized (lifecycleMutex) { + custodyLossCleanup = Optional.of(observation); } + return observation; } public Optional custodyLossCleanup() { @@ -339,21 +436,22 @@ public Optional custodyLoss } /** - * Wipes and cleans an untransferred installed result because abandoning this owner before - * transfer loses the original private custody. After transfer, cleanup belongs to the caller - * and requires its explicit pre-admission custody-loss callback. + * Closing untransferred custody drains and wipes its result, then attempts exact-original + * cleanup. Transfer leaves cleanup to the explicit custody-loss callback. A held observation + * remains retryable through that callback; cleanup never runs under a lifecycle monitor. */ @Override public void close() { - synchronized (lifecycleMutex) { - if (!closed) { - closed = true; - if (privateResult != null) { - privateResult.close(); - privateResult = null; - custodyLossCleanup = Optional.of(attemptOriginalCleanup()); - } + beginDrain(); + try { + boolean retained; + synchronized (lifecycleMutex) { + retained = privateResult != null; } + eraseRetainedResults(false); + if (retained) recordOriginalCleanup(); + } finally { + endDrain(); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index 90fdfd7209..c45ec5adbb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -62,31 +62,47 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; import java.util.function.Supplier; 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.InitialGameplayLoginTokenWitness; +import net.firedevops.firemud.account.v1.IssueDirectTextConnectScopeResponse; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; 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.client.CanonicalGameplayLoginAccountClient; +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.dto.InitialGameplayLoginDisposalResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.Disposition; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult.ProofKind; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; +import net.firedevops.firemud.gamesession.repository.DirectTextAuthenticatedLobbyRepository; import net.firedevops.firemud.gamesession.repository.InitialGameplayLoginCoordinationJournalRepository; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyCustody; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; import net.firedevops.firemud.test.TestContainerImages; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -101,6 +117,7 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.DockerClientFactory; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; @@ -109,7 +126,9 @@ /** * Physical standalone AOF primary/replica, scoped ACL and PostgreSQL journal proof. Fresh PENDING - * records are seeded exclusively by the test administrator: no trusted producer is established. + * records use administrator seeding or the actual unregistered LOGIN owner in named compositions; + * no trusted ingress producer is established. Lobby routing, transport and Account scope replies + * remain controlled, without authenticated ingress or reset/replacement qualification. * Qualification is stipulated by the controlled external-authority fixture, including exclusion * through Account continuation; this is not genuine restore/promotion qualification, Cluster, TLS, * deployed custody, authenticated Account transport or LOGIN activation proof. ACK-loss injection @@ -174,6 +193,7 @@ class InitialGameplayLoginContextRedisIntegrationTest { private StatefulRedisConnection adminConnection; private RedisCommands admin; private String schema; + private DriverManagerDataSource journalDataSource; private InitialGameplayLoginCoordinationJournalRepository journal; @BeforeAll @@ -859,6 +879,359 @@ void originalClosureCannotCreateAbsentOrTouchReplacementAndNewContext(String con .containsExactly(InitialGameplayLoginContextState.pending(newContext).encode()); } + @Test + void installedOwnerBorrowsGenuineResultIntoRetainedNonAdmittingLobbyScope() throws Exception { + var fixture = installedLobbyFixture(() -> {}); + try (var installed = fixture.installed()) { + var scope = fixture.realms(); + var original = installed.coordinates(); + assertThat(fixture.repository().readCommittedScope(scope).encode()) + .containsExactly(scope.encode()); + assertThat(scope.original()).isEqualTo(original); + assertThat(scope.evidence()).isEqualTo(fixture.result().evidence()); + assertThat(scope.transport()).isEqualTo(fixture.transport()); + assertThat(admin.get(key(original))) + .containsExactly( + InitialGameplayLoginContextState.installed(original, fixture.result()).encode()); + assertThat(journal.readCommitted(original).orElseThrow().verifiedWitness()) + .contains(witness(fixture.result())); + byte[] token = fixture.result().compactJwtBytes(); + try { + assertThat(containsSequence(scope.encode(), token)).isFalse(); + assertThat(containsSequence(admin.get(key(original)), token)).isFalse(); + assertThat(new String(scope.encode(), StandardCharsets.UTF_8)) + .doesNotContain("fixture-transient-secret"); + } finally { + Arrays.fill(token, (byte) 0); + } + assertThat(installed.status()) + .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); + } + assertThatThrownBy(() -> fixture.result().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void actualInstalledBorrowExcludesCleanupUntilLobbyReadbackAndRefusesLaterBorrow() + throws Exception { + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var closing = new CountDownLatch(1); + var fixture = + installedLobbyFixture( + () -> { + entered.countDown(); + awaitLobby(release); + }); + try (var executor = Executors.newFixedThreadPool(2)) { + var borrowing = executor.submit(fixture::realms); + try { + assertThat(entered.await(10, TimeUnit.SECONDS)).isTrue(); + var closed = + executor.submit( + () -> { + closing.countDown(); + fixture.installed().close(); + }); + assertThat(closing.await(10, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> closed.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + release.countDown(); + var scope = borrowing.get(15, TimeUnit.SECONDS); + closed.get(15, TimeUnit.SECONDS); + assertThat(fixture.repository().readCommittedScope(scope).encode()) + .containsExactly(scope.encode()); + assertThat( + journal.readCommitted(fixture.installed().coordinates()).orElseThrow().abandoned()) + .isTrue(); + assertThat(admin.get(key(fixture.installed().coordinates()))) + .containsExactly( + InitialGameplayLoginContextState.closed(fixture.installed().coordinates()) + .encode()); + assertThat( + journal + .readCommitted(fixture.installed().coordinates()) + .orElseThrow() + .frozenRetirementRequest()) + .contains( + InitialGameplayLoginJournalSnapshot.request( + fixture.installed().coordinates(), witness(fixture.result()))); + assertThat(fixture.installed().custodyLossCleanup()).isPresent(); + assertThatThrownBy(fixture::realms).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> fixture.result().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + verify(fixture.lobbyAccount()).issueDirectTextConnectScope(any(), any()); + } finally { + release.countDown(); + } + } finally { + fixture.installed().close(); + } + } + + @Test + void sqlRowThenResultReadProgressesWhileBorrowWaitsForRowAndCloseDrains() throws Exception { + var fixture = installedLobbyFixture(() -> {}); + var scope = fixture.realms(); + var rowLocked = new CountDownLatch(1); + var borrowEntered = new CountDownLatch(1); + var readResult = new CountDownLatch(1); + var closing = new CountDownLatch(1); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(journalDataSource)); + try (var executor = Executors.newFixedThreadPool(3)) { + var rowOwner = + executor.submit( + () -> + transaction.execute( + status -> { + fixture + .repository() + .verifyOriginal(fixture.installed().coordinates(), fixture.result()); + rowLocked.countDown(); + awaitLobby(readResult); + // This is the actual repository ordering: original SQL row, then live + // result bytes. + scope.requireCurrent( + fixture.installed().coordinates(), + fixture.result(), + fixture.transport(), + CLOCK); + // Neither drain waiting nor cleanup may hold the Outcome monitor across SQL + // work. + assertThat(fixture.installed().custodyLossCleanup()).isEmpty(); + return true; + })); + try { + assertThat(rowLocked.await(10, TimeUnit.SECONDS)).isTrue(); + var borrowing = + executor.submit( + () -> + fixture + .installed() + .withOwnedPrivateResult( + result -> { + assertThat(result).isSameAs(fixture.result()); + borrowEntered.countDown(); + return transaction.execute( + status -> { + DSL.using( + new TransactionAwareDataSourceProxy(journalDataSource), + SQLDialect.POSTGRES) + .execute("SET LOCAL lock_timeout = '5s'"); + return fixture + .repository() + .current( + fixture.installed().coordinates(), + result, + fixture.transport(), + CLOCK); + }); + })); + assertThat(borrowEntered.await(10, TimeUnit.SECONDS)).isTrue(); + var closed = + executor.submit( + () -> { + closing.countDown(); + fixture.installed().close(); + }); + assertThat(closing.await(10, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> closed.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + readResult.countDown(); + assertThat(rowOwner.get(15, TimeUnit.SECONDS)).isTrue(); + assertThat(borrowing.get(15, TimeUnit.SECONDS).encode()).containsExactly(scope.encode()); + closed.get(15, TimeUnit.SECONDS); + assertThat( + journal.readCommitted(fixture.installed().coordinates()).orElseThrow().abandoned()) + .isTrue(); + } finally { + readResult.countDown(); + } + } finally { + fixture.installed().close(); + } + } + + /** + * Actual LOGIN installation and lobby storage, with controlled Account, routing and transport. + */ + private LobbyFixture installedLobbyFixture(Runnable duringScopeCall) throws Exception { + var contexts = + client( + new TracedProvider(writer), + new ControlledAuthority(), + new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 3_000)); + var account = mock(CanonicalGameplayLoginAccountClient.class); + var cleanup = cleanup(contexts, account); + var result = new AtomicReference(); + when(account.retireInitialGameplayLogin(any())) + .thenAnswer( + call -> { + var request = + call.getArgument( + 0, net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.class); + return new InitialGameplayLoginDisposalResult( + UUID.fromString(request.getRequestId()), + UUID.fromString(request.getCallerContextId()), + UUID.randomUUID(), + Disposition.PENDING, + ProofKind.NONE); + }); + when(account.authenticate(any(AuthenticateRequest.class), any())) + .thenAnswer( + call -> { + var value = + validatedResult( + call.getArgument(0, AuthenticateRequest.class), UUID.randomUUID()); + result.set(value); + return value; + }); + var installed = + new InitialGameplayLoginOwner(contexts, cleanup, account) + .receive( + new InitialGameplayLoginCredentialPresentation( + "player@example.test", + "203.0.113.10", + "fixture-transient-secret".toCharArray())); + ownedKeys.add( + InitialGameplayLoginContextRedisKeys.contextKey(installed.coordinates().callerContextId())); + assertThat(installed.status()) + .isEqualTo(InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING); + var target = lobbyTarget(); + 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()))); + var selection = + new DirectTextWorldSelectionService( + GameplayWorldCatalog.forWorldSupplier(() -> List.of(world)), routes, CLOCK); + var repository = + new DirectTextAuthenticatedLobbyRepository( + DSL.using(new TransactionAwareDataSourceProxy(journalDataSource), SQLDialect.POSTGRES)); + var lobbyAccount = mock(AccountClient.class); + when(lobbyAccount.issueDirectTextConnectScope(any(), any())) + .thenAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + duringScopeCall.run(); + return IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("controlled-scope") + .setEvaluatedAt(CLOCK.instant().minusSeconds(1).toString()) + .setConnectScopeExpiresAt(CLOCK.instant().plusSeconds(60).toString()) + .build(); + }); + return new LobbyFixture( + installed, + result.get(), + new ObservedDirectTextTransport("00042", UUID.randomUUID()), + new DirectTextAuthenticatedLobbyOwner( + repository, + selection, + lobbyAccount, + new DataSourceTransactionManager(journalDataSource), + CLOCK), + repository, + selection, + lobbyAccount); + } + + /** + * Transport is deliberately controlled; this fixture is not an authenticated ingress producer. + */ + private record LobbyFixture( + InitialGameplayLoginOwner.Outcome installed, + CanonicalGameplayLoginResult result, + ObservedDirectTextTransport transport, + DirectTextAuthenticatedLobbyOwner lobby, + DirectTextAuthenticatedLobbyRepository repository, + DirectTextWorldSelectionService selection, + AccountClient lobbyAccount) { + DirectTextAuthenticatedLobbyScope realms() { + return installed.withOwnedPrivateResult( + borrowed -> { + assertThat(borrowed).isSameAs(result); + var custody = + new DirectTextAuthenticatedLobbyCustody() { + @Override + public T withCurrent( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult candidate, + Function action) { + assertThat(original).isEqualTo(installed.coordinates()); + assertThat(candidate).isSameAs(borrowed); + return action.apply(transport); + } + }; + return lobby.realms( + installed.coordinates(), borrowed, custody, selection.browse().orElseThrow(), "1"); + }); + } + } + + private static void awaitLobby(CountDownLatch latch) { + try { + if (!latch.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("Controlled lobby gate timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Controlled lobby gate interrupted", failure); + } + } + + private static CanonicalPlayableTarget lobbyTarget() { + 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, + CLOCK.instant().minusSeconds(1), + "ALLOW_NEW"); + } + private InitialGameplayLoginCleanupOwner cleanup( InitialGameplayLoginContextRedisClient client, CanonicalGameplayLoginAccountClient account) { schema = "gs_context_" + UUID.randomUUID().toString().replace("-", ""); @@ -866,6 +1239,7 @@ private InitialGameplayLoginCleanupOwner cleanup( new DriverManagerDataSource( POSTGRES.getJdbcUrl(), POSTGRES.getUsername(), POSTGRES.getPassword()); dataSource.setSchema(schema); + journalDataSource = dataSource; CanonicalGameplayIssuerTestFixtures.migrateSchema( dataSource, schema, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java index 0c778a8049..14050a4939 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginPhysicalCompositionFixture.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.lettuce.core.AclSetuserArgs; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; @@ -169,6 +170,10 @@ public InitialGameplayLoginAttemptCoordinates coordinates() { } /** The actual owner outcome, retained for explicit pre-admission custody-loss cleanup. */ + @SuppressFBWarnings( + value = "EI_EXPOSE_REP", + justification = + "The fixture deliberately shares its identical live Outcome for exact-original cleanup; copying or reconstructing it would lose the owned lifecycle obligation.") public InitialGameplayLoginOwner.Outcome outcome() { return outcome; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java index 3048066146..4453778fb0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java @@ -22,6 +22,11 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -117,6 +122,104 @@ void closeOverwritesOwnedCompactTokenAndRefusesFurtherSecretAccess() throws Exce assertThat(result.evidence().accountId()).isEqualTo(ACCOUNT); } + @Test + void liveBorrowPreservesExactIdentityRefusesReentrancyAndReleasesAfterCallbackFailure() + throws Exception { + var result = decode(response(claims())); + assertThat( + result.withLivePrivateResult( + borrowed -> { + assertThat(borrowed).isSameAs(result); + assertThatThrownBy(borrowed::close).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> borrowed.withLivePrivateResult(nested -> true)) + .isInstanceOf(IllegalStateException.class); + return borrowed.compactJwtBytes().length; + })) + .isPositive(); + assertThatThrownBy( + () -> + result.withLivePrivateResult( + borrowed -> { + throw new IllegalStateException("controlled callback failure"); + })) + .hasMessage("controlled callback failure"); + result.close(); + assertThatThrownBy(() -> result.withLivePrivateResult(borrowed -> true)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void directCloseDrainsAllBorrowersWithoutHoldingResultMonitorAndThenErasesBytes() + throws Exception { + var wire = response(claims()); + var result = decode(wire); + var field = CanonicalGameplayLoginResult.class.getDeclaredField("compactJwt"); + field.setAccessible(true); + byte[] owned = (byte[]) field.get(result); + byte[] expected = wire.getAuthToken().getBytes(StandardCharsets.US_ASCII); + var entered = new CountDownLatch(2); + var release = new CountDownLatch(1); + var closingThread = new AtomicReference(); + try (var executor = Executors.newFixedThreadPool(3)) { + var first = executor.submit(() -> borrowUntilReleased(result, entered, release, expected)); + var second = executor.submit(() -> borrowUntilReleased(result, entered, release, expected)); + try { + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + var closing = + executor.submit( + () -> { + closingThread.set(Thread.currentThread()); + result.close(); + }); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (closingThread.get() == null + || closingThread.get().getState() != Thread.State.WAITING) { + if (System.nanoTime() >= deadline) throw new IllegalStateException("Close did not drain"); + Thread.sleep(1); + } + assertThatThrownBy(() -> result.withLivePrivateResult(borrowed -> true)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(result::compactJwtBytes).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> closing.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + assertThat(owned).containsExactly(expected); + release.countDown(); + assertThat(first.get(5, TimeUnit.SECONDS)).isTrue(); + assertThat(second.get(5, TimeUnit.SECONDS)).isTrue(); + closing.get(5, TimeUnit.SECONDS); + assertThat(owned).containsOnly((byte) 0); + result.close(); + } finally { + release.countDown(); + } + } finally { + Arrays.fill(expected, (byte) 0); + result.close(); + } + } + + private static boolean borrowUntilReleased( + CanonicalGameplayLoginResult result, + CountDownLatch entered, + CountDownLatch release, + byte[] expected) { + return result.withLivePrivateResult( + borrowed -> { + assertThat(borrowed).isSameAs(result); + entered.countDown(); + try { + if (!release.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Borrow timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Borrow interrupted", failure); + } + // Reads must still progress while close waits for this callback's pin. + assertThat(borrowed.compactJwtBytes()).containsExactly(expected); + return true; + }); + } + @ParameterizedTest @ValueSource( strings = { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java index aa3b50cc4e..83dc0d0af3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java @@ -1,19 +1,31 @@ package net.firedevops.firemud.gamesession.service; 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.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +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 io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.account.v1.AuthenticateRequest; import net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness; import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; @@ -23,6 +35,8 @@ import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginDisposalResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginJournalSnapshot; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.InOrder; /** Source ordering and owned-buffer proof; no Account, Redis, wire, or admission claim. */ @@ -112,17 +126,342 @@ void transferredResultAndOutcomeCloseLeaveCleanupOwnershipToExplicitLossCallback verify(success.fixture().cleanup).abandonAndRetire(coordinates); } + @Test + void ownedBorrowPinsExactResultAndRefusesReentrantLifecycleChanges() { + var success = successfulOutcome(); + var outcome = success.outcome(); + var value = + outcome.withOwnedPrivateResult( + result -> { + assertThat(result).isSameAs(success.result()); + assertThatThrownBy(outcome::close).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(result::close).isInstanceOf(IllegalStateException.class); + assertThat(result.compactJwtBytes()).isNotEmpty(); + assertThatThrownBy(outcome::takePrivateResult) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(outcome::abandonOriginalAfterCustodyLoss) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> outcome.withOwnedPrivateResult(nested -> true)) + .isInstanceOf(IllegalStateException.class); + return "non-admitting"; + }); + assertThat(value).isEqualTo("non-admitting"); + verify(success.result()).close(); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + org.mockito.Mockito.clearInvocations(success.result()); + outcome.close(); + verify(success.result()).close(); + verify(success.fixture().cleanup).abandonAndRetire(outcome.coordinates()); + assertThatThrownBy(() -> outcome.withOwnedPrivateResult(result -> true)) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void callbackFailureReleasesBorrowWithoutTransferringOrRetiringTheResult() { + var success = successfulOutcome(); + var outcome = success.outcome(); + assertThatThrownBy( + () -> + outcome.withOwnedPrivateResult( + result -> { + throw new IllegalStateException("controlled callback failure"); + })) + .hasMessage("controlled callback failure"); + assertThat(outcome.withOwnedPrivateResult(result -> result == success.result())) + .isTrue(); + assertThat(outcome.takePrivateResult()).containsSame(success.result()); + assertThatThrownBy(() -> outcome.withOwnedPrivateResult(result -> true)) + .isInstanceOf(IllegalStateException.class); + outcome.abandonOriginalAfterCustodyLoss(); + verify(success.result()).close(); + } + + @Test + void concurrentCloseWaitsForOwnedBorrowThenRetiresExactOriginal() throws Exception { + var success = successfulOutcome(); + var outcome = success.outcome(); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var closing = new CountDownLatch(1); + try (var executor = Executors.newFixedThreadPool(2)) { + var borrowed = + executor.submit( + () -> + outcome.withOwnedPrivateResult( + result -> { + entered.countDown(); + try { + if (!release.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("test timeout"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return result == success.result(); + })); + try { + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + var closed = + executor.submit( + () -> { + closing.countDown(); + outcome.close(); + }); + assertThat(closing.await(5, TimeUnit.SECONDS)).isTrue(); + assertThatThrownBy(() -> closed.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + verify(success.result(), never()).close(); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + release.countDown(); + assertThat(borrowed.get(5, TimeUnit.SECONDS)).isTrue(); + closed.get(5, TimeUnit.SECONDS); + verify(success.result()).close(); + verify(success.fixture().cleanup).abandonAndRetire(outcome.coordinates()); + } finally { + release.countDown(); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"transfer", "abandon", "direct-close"}) + void lifecycleDrainKeepsBorrowedBytesLiveAndBlocksNewBorrows(String operation) throws Exception { + var success = successfulOutcome(); + var outcome = success.outcome(); + var entered = new CountDownLatch(1); + var release = new CountDownLatch(1); + var lifecycleThread = new AtomicReference(); + byte[] expected = success.result().compactJwtBytes(); + try (var executor = Executors.newFixedThreadPool(2)) { + var borrowed = + executor.submit( + () -> + outcome.withOwnedPrivateResult( + result -> { + assertThat(result).isSameAs(success.result()); + entered.countDown(); + await(release); + assertThat(result.compactJwtBytes()).containsExactly(expected); + return true; + })); + try { + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + var mutation = + executor.submit( + () -> { + lifecycleThread.set(Thread.currentThread()); + return switch (operation) { + case "transfer" -> outcome.takePrivateResult().orElseThrow(); + case "abandon" -> outcome.abandonOriginalAfterCustodyLoss(); + default -> { + success.result().close(); + yield true; + } + }; + }); + awaitWaiting(lifecycleThread); + assertThatThrownBy(() -> outcome.withOwnedPrivateResult(result -> true)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> mutation.get(100, TimeUnit.MILLISECONDS)) + .isInstanceOf(TimeoutException.class); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + release.countDown(); + assertThat(borrowed.get(5, TimeUnit.SECONDS)).isTrue(); + Object result = mutation.get(5, TimeUnit.SECONDS); + if (operation.equals("transfer")) { + assertThat(result).isSameAs(success.result()); + assertThat(success.result().compactJwtBytes()).containsExactly(expected); + outcome.close(); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + outcome.abandonOriginalAfterCustodyLoss(); + } else if (operation.equals("direct-close")) { + outcome.close(); + } + assertThatThrownBy(() -> success.result().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + verify(success.fixture().cleanup).abandonAndRetire(outcome.coordinates()); + } finally { + release.countDown(); + } + } finally { + Arrays.fill(expected, (byte) 0); + outcome.close(); + } + } + + @Test + void heldOriginalCleanupRetriesOutsideOutcomeMonitorAndRefusesReentrantMutation() + throws Exception { + var success = successfulOutcome(); + var outcome = success.outcome(); + var accessed = new AtomicBoolean(); + try (var executor = Executors.newSingleThreadExecutor()) { + when(success.fixture().cleanup.abandonAndRetire(outcome.coordinates())) + .thenAnswer( + call -> { + assertThatThrownBy(outcome::close).isInstanceOf(IllegalStateException.class); + accessed.set( + executor + .submit(() -> outcome.custodyLossCleanup().isEmpty()) + .get(5, TimeUnit.SECONDS)); + return held(outcome.coordinates()); + }); + outcome.close(); + assertThat(accessed).isTrue(); + assertThat(outcome.custodyLossCleanup().orElseThrow().status()) + .isEqualTo(InitialGameplayLoginCleanupOwner.Status.HELD); + org.mockito.Mockito.doReturn( + new InitialGameplayLoginCleanupOwner.CleanupObservation( + outcome.coordinates(), + InitialGameplayLoginCleanupOwner.Status.ACCOUNT_PENDING, + Optional.empty(), + Optional.empty())) + .when(success.fixture().cleanup) + .abandonAndRetire(outcome.coordinates()); + assertThat(outcome.abandonOriginalAfterCustodyLoss().status()) + .isEqualTo(InitialGameplayLoginCleanupOwner.Status.ACCOUNT_PENDING); + verify(success.fixture().cleanup, times(2)).abandonAndRetire(outcome.coordinates()); + verify(success.result()).close(); + } + } + + @Test + void equalReconstructedEvidenceCannotReplaceClosedGenuineOwnedResult() { + var success = successfulOutcome(); + try (var reconstructed = controlledPrivateResult(success.outcome().coordinates())) { + assertThat(reconstructed.evidence()).isEqualTo(success.result().evidence()); + assertThat(reconstructed).isNotSameAs(success.result()); + success.result().close(); + assertThatThrownBy(() -> success.outcome().withOwnedPrivateResult(result -> true)) + .isInstanceOf(IllegalStateException.class); + assertThat(success.outcome().takePrivateResult()).containsSame(success.result()); + assertThat(reconstructed.compactJwtBytes()).isNotEmpty(); + success.outcome().abandonOriginalAfterCustodyLoss(); + verify(success.fixture().cleanup).abandonAndRetire(success.outcome().coordinates()); + } + } + + @Test + void directResultBorrowRefusesOwnerReentrancyWithoutChangingOwnedState() { + var success = successfulOutcome(); + success + .result() + .withLivePrivateResult( + result -> { + assertThatThrownBy(success.outcome()::close) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::takePrivateResult) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::abandonOriginalAfterCustodyLoss) + .isInstanceOf(IllegalStateException.class); + assertThat(result.compactJwtBytes()).isNotEmpty(); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + return true; + }); + assertThat( + success.outcome().withOwnedPrivateResult(result -> result == success.result())) + .isTrue(); + success.outcome().close(); + verify(success.fixture().cleanup).abandonAndRetire(success.outcome().coordinates()); + assertThatThrownBy(() -> success.result().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void directResultPinCannotWaitBehindOutcomeDrainThatIsWaitingForTheSamePin(boolean transferred) + throws Exception { + var success = successfulOutcome(); + if (transferred) + assertThat(success.outcome().takePrivateResult()).containsSame(success.result()); + var entered = new CountDownLatch(1); + var attemptLifecycle = new CountDownLatch(1); + var closingThread = new AtomicReference(); + var borrowed = new CompletableFuture(); + var closed = new CompletableFuture(); + // Daemon workers keep this logical-deadlock regression bounded even if the cycle returns. + Thread.ofPlatform() + .daemon() + .start( + () -> { + try { + borrowed.complete( + success + .result() + .withLivePrivateResult( + result -> { + entered.countDown(); + await(attemptLifecycle); + assertThatThrownBy(success.outcome()::close) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::takePrivateResult) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::abandonOriginalAfterCustodyLoss) + .isInstanceOf(IllegalStateException.class); + assertThat(result.compactJwtBytes()).isNotEmpty(); + return true; + })); + } catch (Throwable failure) { + borrowed.completeExceptionally(failure); + } + }); + assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); + Thread.ofPlatform() + .daemon() + .start( + () -> { + closingThread.set(Thread.currentThread()); + try { + if (transferred) success.outcome().abandonOriginalAfterCustodyLoss(); + else success.outcome().close(); + closed.complete(null); + } catch (Throwable failure) { + closed.completeExceptionally(failure); + } + }); + try { + awaitWaiting(closingThread); + assertThat(closed).isNotDone(); + attemptLifecycle.countDown(); + assertThat(borrowed.get(5, TimeUnit.SECONDS)).isTrue(); + closed.get(5, TimeUnit.SECONDS); + verify(success.fixture().cleanup).abandonAndRetire(success.outcome().coordinates()); + assertThatThrownBy(() -> success.result().compactJwtBytes()) + .isInstanceOf(IllegalStateException.class); + } finally { + attemptLifecycle.countDown(); + } + } + + private static void await(CountDownLatch latch) { + try { + if (!latch.await(5, TimeUnit.SECONDS)) throw new IllegalStateException("Test gate timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Test gate interrupted", failure); + } + } + + private static void awaitWaiting(AtomicReference thread) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (thread.get() == null || thread.get().getState() != Thread.State.WAITING) { + if (System.nanoTime() >= deadline) throw new IllegalStateException("Lifecycle did not drain"); + Thread.sleep(1); + } + } + private static SuccessfulOutcome successfulOutcome() { var fixture = new Fixture(); var secret = "original-private-secret".toCharArray(); var credentials = presentation(secret); - var result = mock(CanonicalGameplayLoginResult.class); - when(result.evidence()).thenAnswer(invocation -> evidence(fixture.coordinates)); + var result = new AtomicReference(); when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) .thenAnswer( invocation -> { fixture.accountRequest = invocation.getArgument(0); - return result; + var retained = spy(controlledPrivateResult(fixture.coordinates)); + result.set(retained); + return retained; }); when(fixture.contexts.createPending(any())) .thenAnswer( @@ -137,7 +476,23 @@ private static SuccessfulOutcome successfulOutcome() { when(fixture.cleanup.abandonAndRetire(any())) .thenAnswer(invocation -> held(invocation.getArgument(0))); - return new SuccessfulOutcome(fixture, fixture.owner.receive(credentials), result, secret); + var outcome = fixture.owner.receive(credentials); + return new SuccessfulOutcome(fixture, outcome, result.get(), secret); + } + + /** Controlled private bytes only: this unit fixture supplies no authenticated Account origin. */ + private static CanonicalGameplayLoginResult controlledPrivateResult( + InitialGameplayLoginAttemptCoordinates coordinates) { + try { + var constructor = + CanonicalGameplayLoginResult.class.getDeclaredConstructor( + byte[].class, NonSecretEvidence.class); + constructor.setAccessible(true); + return constructor.newInstance( + "controlled-private-token".getBytes(StandardCharsets.US_ASCII), evidence(coordinates)); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException("Controlled result fixture unavailable", failure); + } } @Test From 9695f4f38774c7f91ac087ba90a8b6c5240b0eaf Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 8 Nov 2026 05:15:24 +1300 Subject: [PATCH 02/20] Verify mapped Gateway custody and exact shared namespace --- ...d-identity-controller-manifest-contract.sh | 26 +++- .../GameplayWebSocketBridgeConfigTest.java | 111 +++++++++++++++++- 2 files changed, 128 insertions(+), 9 deletions(-) diff --git a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh index bbfc345460..82c607da96 100644 --- a/dev-tools/tests/hosted-identity-controller-manifest-contract.sh +++ b/dev-tools/tests/hosted-identity-controller-manifest-contract.sh @@ -4904,13 +4904,14 @@ def allows_shared_namespace_identity(service, env): "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", "valueFrom": {"fieldRef": {"fieldPath": "metadata.namespace"}}, } - if service == "logging-admin-service": + if service in {"logging-admin-service", "spring-cloud-gateway"}: return namespace_identity == expected_namespace_identity return namespace_identity is None -# The exact downward-API namespace identity is valid only for Logging & Admin -# among shared transports; every other shared service must reject this shape. +# Logging & Admin and Gateway's separate gameplay client need the exact downward-API +# namespace identity while their gRPC transports retain the shared secret and paths. +# Every other shared service must reject this shape. negative_shared_namespace_fixture = { "FIREMUD_GRPC_WORKLOAD_NAMESPACE": { "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", @@ -4918,10 +4919,23 @@ negative_shared_namespace_fixture = { } } for service in shared_services: - if service != "logging-admin-service" and allows_shared_namespace_identity( - service, negative_shared_namespace_fixture + if ( + service not in {"logging-admin-service", "spring-cloud-gateway"} + and allows_shared_namespace_identity(service, negative_shared_namespace_fixture) ): fail(f"shared namespace identity fixture unexpectedly accepted for {service}") +for service in ("logging-admin-service", "spring-cloud-gateway"): + for invalid_identity in ( + {"name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", "value": "literal-namespace"}, + { + "name": "FIREMUD_GRPC_WORKLOAD_NAMESPACE", + "valueFrom": {"fieldRef": {"fieldPath": "metadata.name"}}, + }, + ): + if allows_shared_namespace_identity( + service, {"FIREMUD_GRPC_WORKLOAD_NAMESPACE": invalid_identity} + ): + fail(f"shared namespace identity fixture accepted malformed identity for {service}") def assert_distinct_workload_service(service, deployment_map, source): @@ -5008,7 +5022,7 @@ for service in shared_services: container, service, "/tls/client.crt", "/tls/client.key", "/tls/ca.crt" ) env = env_map(container, service) - if service == "logging-admin-service": + if service in {"logging-admin-service", "spring-cloud-gateway"}: if not allows_shared_namespace_identity(service, env): fail( f"Deployment/{service} must derive FIREMUD_GRPC_WORKLOAD_NAMESPACE " diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java index d69547f164..9d9ebca787 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java @@ -1,20 +1,46 @@ package net.firedevops.firemud.springcloudgateway.config; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.time.Clock; import java.time.Instant; +import java.time.ZoneOffset; +import java.util.HashMap; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.springcloudgateway.filter.HeaderTrustFilter; +import net.firedevops.firemud.springcloudgateway.filter.TcpProxyTrustPolicy; +import net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketBridgeHandler; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketObservability; import org.junit.jupiter.api.Test; +import org.mockito.MockedConstruction; import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.http.server.reactive.SslInfo; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; +import org.springframework.web.reactive.socket.WebSocketHandler; +import org.springframework.web.reactive.socket.WebSocketSession; +import org.springframework.web.reactive.socket.server.support.HandshakeWebSocketService; import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter; +import org.springframework.web.server.WebHandler; +import reactor.core.publisher.Mono; class GameplayWebSocketBridgeConfigTest { @@ -40,7 +66,8 @@ void gameplayWebSocketPathIsOwnedByGatewayCode() { SimpleUrlHandlerMapping mapping = context.getBean(SimpleUrlHandlerMapping.class); assertThat(mapping.getUrlMap()).containsKeys("/ws/game", "/ws/game/**"); assertThat(mapping.getUrlMap().get("/ws/game")) - .isSameAs(context.getBean(GameplayWebSocketBridgeHandler.class)); + .isInstanceOf(WebHandler.class) + .isSameAs(mapping.getUrlMap().get("/ws/game/**")); }); } @@ -49,8 +76,8 @@ void gameplayWebSocketMappingUsesPathPatternSemanticsForMatrixParameters() { contextRunner.run( context -> { SimpleUrlHandlerMapping mapping = context.getBean(SimpleUrlHandlerMapping.class); - GameplayWebSocketBridgeHandler handler = - context.getBean(GameplayWebSocketBridgeHandler.class); + Object handler = mapping.getUrlMap().get("/ws/game"); + assertThat(handler).isInstanceOf(WebHandler.class); for (String path : new String[] {"/ws/game;probe", "/ws;probe/game", "/ws/game;probe/child"}) { @@ -74,6 +101,84 @@ void gameplayWebSocketMappingUsesPathPatternSemanticsForMatrixParameters() { }); } + @Test + void mappedWebHandlerBindsOnlyVerifiedTcpProxyOriginBeforeDelegatingUpgrade() throws Exception { + GameplayWebSocketBridgeHandler handler = mock(GameplayWebSocketBridgeHandler.class); + WebSocketSession session = mock(WebSocketSession.class); + when(session.getAttributes()).thenReturn(new HashMap<>()); + AtomicReference received = new AtomicReference<>(); + when(handler.handle(session)) + .thenAnswer( + invocation -> { + received.set(VerifiedTcpProxyOrigin.from(session)); + return Mono.empty(); + }); + X509Certificate certificate; + try (InputStream input = + Objects.requireNonNull(getClass().getResourceAsStream("/certs/tcp-proxy-client.pem"))) { + certificate = + (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + long notBefore = certificate.getNotBefore().getTime(); + long notAfter = certificate.getNotAfter().getTime(); + Clock clock = + Clock.fixed(Instant.ofEpochMilli(notBefore + (notAfter - notBefore) / 2), ZoneOffset.UTC); + GatewayTcpProxyListenerProperties listener = new GatewayTcpProxyListenerProperties(); + listener.setEnabled(true); + listener.setPort(8443); + listener.setCertificateChainPath("server.crt"); + listener.setPrivateKeyPath("server.key"); + listener.setTrustedClientCaPath("client-ca.crt"); + listener.setEnvironment("production"); + listener.setTrustProfile("production_uri"); + listener.getProductionUri().setUriSan("spiffe://firemud/ns/firemud/sa/tcp-proxy-service"); + GatewayHeaderTrustProperties headers = new GatewayHeaderTrustProperties(); + HeaderTrustFilter trust = + new HeaderTrustFilter( + headers, new TcpProxyTrustPolicy(listener, headers, 8080, clock, Set.of("test"))); + // SslInfo models the authenticated TLS peer; the actual trust policy and filter + // qualify it and produce the private origin carried by the mapping's upgrade wrapper. + SslInfo peer = mock(SslInfo.class); + when(peer.getPeerCertificates()).thenReturn(new X509Certificate[] {certificate}); + MockServerHttpRequest request = + MockServerHttpRequest.get("/ws/game") + .localAddress(new InetSocketAddress("127.0.0.1", 8443)) + .remoteAddress(new InetSocketAddress("127.0.0.1", 50000)) + .sslInfo(peer) + .header("X-Proxy-Client-IP", "203.0.113.99") + .header("X-Proxy-Connection-Id", "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814") + .build(); + + try (MockedConstruction upgrades = + mockConstruction( + HandshakeWebSocketService.class, + (upgrade, construction) -> + when(upgrade.handleRequest(any(), any())) + .thenAnswer( + invocation -> + invocation.getArgument(1).handle(session)))) { + SimpleUrlHandlerMapping mapping = + (SimpleUrlHandlerMapping) + new GameplayWebSocketBridgeConfig().gameplayWebSocketBridgeMapping(handler); + WebHandler bridge = (WebHandler) mapping.getUrlMap().get("/ws/game"); + + trust.filter(MockServerWebExchange.from(request), bridge::handle).block(); + assertThat(received.get()).isNotNull(); + assertThat(received.get().clientAddress()).isEqualTo("203.0.113.99"); + assertThat(received.get().proxyConnectionId().toString()) + .isEqualTo("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"); + + // Identical headers without the filter's private proof cannot inherit the prior + // upgraded session's origin, even when the same controlled session is reused. + bridge.handle(MockServerWebExchange.from(request)).block(); + assertThat(received.get()).isNull(); + assertThat(VerifiedTcpProxyOrigin.from(session)).isNull(); + assertThat(upgrades.constructed()).hasSize(1); + verify(upgrades.constructed().getFirst(), times(2)).handleRequest(any(), any()); + verify(handler, times(2)).handle(session); + } + } + @Configuration static class TestRuntimeIdentityConfig { @Bean From abe3bc2b8603e68f3ae0d6fba8e9636bdac89f07 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Sun, 8 Nov 2026 05:39:50 +1300 Subject: [PATCH 03/20] Align secure Gateway preview and TLS admission fixtures --- .../test_validate_preview_artifact.py | 31 +++++++++++++++++++ ...xyTlsListenerAdmissionIntegrationTest.java | 14 +++++---- 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index 817c2c0702..5c4d3fc272 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -1878,6 +1878,10 @@ def _policy_documents(self, mode): {"protocol": "TCP", "port": 53}, ], }, + { + "to": [{"podSelector": {"matchLabels": {"app": "game-session-service"}}}], + "ports": [{"protocol": "TCP", "port": 8444}], + }, { "to": [ { @@ -2585,6 +2589,16 @@ def _gateway_document(self): "mountPath": "/tls", "readOnly": True, }, + { + "name": "gameplay-client-tls", + "mountPath": "/gameplay-client-tls", + "readOnly": True, + }, + { + "name": "gameplay-client-trust", + "mountPath": "/gameplay-client-trust", + "readOnly": True, + }, { "name": "jwt-signing-keys", "mountPath": "/var/run/secrets/firemud/jwt", @@ -2603,6 +2617,23 @@ def _gateway_document(self): "name": "grpc-tls", "secret": {"secretName": "firemud-grpc-tls"}, }, + { + "name": "gameplay-client-tls", + "secret": { + "secretName": "firemud-grpc-spring-cloud-gateway", + "items": [ + {"key": "tls.crt", "path": "tls.crt"}, + {"key": "tls.key", "path": "tls.key"}, + ], + }, + }, + { + "name": "gameplay-client-trust", + "secret": { + "secretName": "firemud-grpc-tls", + "items": [{"key": "ca.crt", "path": "ca.crt"}], + }, + }, { "name": "jwt-signing-keys", "secret": {"secretName": "jwt-signing-keys"}, diff --git a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java index 9436e1439c..6c191efea1 100644 --- a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java +++ b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java @@ -54,6 +54,8 @@ class TcpProxyTlsListenerAdmissionIntegrationTest { private static final String TCP_PROXY_URI = "spiffe://firemud/ns/firemud/sa/tcp-proxy-service"; + private static final String PROXY_CONNECTION_ID = "9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"; + private static final String NO_FRAME_PROXY_CONNECTION_ID = "7c507311-b226-4d26-8f34-1bbb4159fd33"; @Test void productionConfigurationMapsHealthAndReadinessWhenInternalTlsIsDisabled() { @@ -138,9 +140,8 @@ void websocketUpgradePromotesOnlyTheConfiguredClientWorkload() throws Exception session -> { admittedHeaders.set(session.getHandshakeInfo().getHeaders()); admittedConnections.incrementAndGet(); - if ("no-frame" - .equals( - session.getHandshakeInfo().getHeaders().getFirst("X-Proxy-Connection-Id"))) { + if (NO_FRAME_PROXY_CONNECTION_ID.equals( + session.getHandshakeInfo().getHeaders().getFirst("X-Proxy-Connection-Id"))) { return reactor.core.publisher.Mono.never(); } return session.send( @@ -163,7 +164,8 @@ void websocketUpgradePromotesOnlyTheConfiguredClientWorkload() throws Exception assertThat(admittedConnections).hasValue(1); assertThat(admittedHeaders.get().getFirst("X-Client-IP")).isEqualTo("203.0.113.99"); assertThat(admittedHeaders.get().getFirst("X-Proxy-Client-IP")).isNull(); - assertThat(admittedHeaders.get().getFirst("X-Proxy-Connection-Id")).isEqualTo("conn-123"); + assertThat(admittedHeaders.get().getFirst("X-Proxy-Connection-Id")) + .isEqualTo(PROXY_CONNECTION_ID); assertThat(admittedHeaders.get().getFirst("X-Tenant-Id")).isEqualTo("7"); assertThat(admittedHeaders.get().getFirst("X-Game-Instance-Id")).isEqualTo("42"); assertThat(admittedHeaders.get().getFirst("X-Firemud-Connection-Mode")) @@ -187,7 +189,7 @@ void websocketUpgradePromotesOnlyTheConfiguredClientWorkload() throws Exception .hasValue(2); HttpHeaders noFrameHeaders = bridgeHeaders(); - noFrameHeaders.set("X-Proxy-Connection-Id", "no-frame"); + noFrameHeaders.set("X-Proxy-Connection-Id", NO_FRAME_PROXY_CONNECTION_ID); assertThatThrownBy( () -> connect( @@ -348,7 +350,7 @@ private static Stream enabledTrustProfiles() { private static HttpHeaders bridgeHeaders() { HttpHeaders headers = new HttpHeaders(); headers.set("X-Proxy-Client-IP", "203.0.113.99"); - headers.set("X-Proxy-Connection-Id", "conn-123"); + headers.set("X-Proxy-Connection-Id", PROXY_CONNECTION_ID); headers.set("X-Proxy-Tenant-Id", "7"); headers.set("X-Proxy-Game-Instance-Id", "42"); headers.set("X-Firemud-Connection-Mode", "first_party_web"); From 4e4c4d57c11979fa6be61b709811d4a01e4643c2 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 19:56:55 +1300 Subject: [PATCH 04/20] Move protected LOGIN source composition to JWKS successor --- .../account-service/configuration.md | 14 - .../account-service/runtime-and-data.md | 6 +- .../game-session-service/configuration.md | 17 +- .../game-session-service/runtime-and-data.md | 1 - .../player-access-and-session.md | 6 +- ...layLoginProtectedSourcesConfiguration.java | 142 --------- ...countGameplayLoginSourceConfiguration.java | 178 ----------- ...CanonicalGameplayRuntimeConfiguration.java | 56 ---- ...oginProtectedSourcesConfigurationTest.java | 198 ------------ ...tGameplayLoginSourceConfigurationTest.java | 301 ------------------ ...enticatedGameplayRuntimeConfiguration.java | 104 ------ ...layLoginProtectedSourcesConfiguration.java | 117 ------- ...nitialGameplayLoginConnectionProvider.java | 62 ---- ...oginProtectedSourcesConfigurationTest.java | 183 ----------- ...alGameplayLoginConnectionProviderTest.java | 130 -------- 15 files changed, 6 insertions(+), 1509 deletions(-) delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfiguration.java delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfiguration.java delete mode 100644 services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java delete mode 100644 services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfiguration.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfiguration.java delete mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProvider.java delete mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java delete mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java diff --git a/design/architecture/microservices/account-service/configuration.md b/design/architecture/microservices/account-service/configuration.md index aafe9fb678..ce8775571a 100644 --- a/design/architecture/microservices/account-service/configuration.md +++ b/design/architecture/microservices/account-service/configuration.md @@ -68,17 +68,3 @@ The source-only Control-UI issuance preparation reads the configured margin thro ## Proto Files The gRPC schemas for this service live in [`protos/account/v1`](../../../../protos/account/v1). Use `./gradlew generateProto` to regenerate Java stubs when the definitions change. - -## Canonical Gameplay LOGIN Receiving - -Canonical credential envelopes and exact-original retirement share the existing AccountService registration through `AccountGameplayAuthenticateReceiver`. The receiver, complete initial-LOGIN source graph and protected source selection all require `firemud.account.gameplay-login.enabled=true`; they are absent by default. `AccountGameplayLoginSourceConfiguration` composes the existing issuance/evidence/encrypted-response repositories, protected signer and trusted JWKS reader, issuer/account projection publisher, token registry, commit, activation and exact response-recovery owners. Registration supplies no synthetic owner evidence and performs no enrollment, key generation, publication or Redis mutation. - -The enabled composition requires these explicitly delivered inputs: - -- `firemud.grpc.workload-namespace` and `firemud.account.gameplay-login.jwks-api-binding-path=/etc/firemud/account-jwt-api/binding.json`. The existing protected API binding and enabled `firemud.account.jwt-signer.materialization` trust binding must be readable and agree on environment, cluster, namespace and cluster/namespace incarnations. Their namespace must equal the configured workload namespace. The API identity is pinned at composition and rechecked by the existing owners on use; this does not create the enrolled signer, committed promotion or Account-owned public publication evidence. -- `firemud.account.gameplay-login.coordination.uri`, delivered through protected application configuration, selects only the dedicated standalone Coordination endpoint. Its shape is `rediss://account_coord_app:@:/0`; missing credentials, another principal/database, plaintext, URI query options and fragments are rejected. TLS peer verification remains enabled against the platform-provisioned JVM trust anchors. Do not put this credential-bearing value in diagnostics or substitute generic `firemud.redis.*` configuration. The dedicated Lettuce provider disables automatic reconnect and closes with the application; the existing Redis owner independently checks the live ACL identity. -- `firemud.account.gameplay-login.coordination.command-timeout-millis`, `required-local-aof-count`, `required-replica-aof-count` and `acknowledgement-timeout-millis` under that same `coordination` prefix. Both timeouts must be between 1 and 60,000 milliseconds; the local AOF count must be one, and the replica count must be between one and sixteen. Game Session's separate qualified single-node exception does not apply to Account. No timeout or ACK policy is inherited from the ambient Redis client. -- `firemud.account.gameplay-login.registry-cleanup-margin-millis`, explicitly between zero and 300,000 milliseconds. The registered record byte ceiling remains the fixed approved delegation profile limit; this margin does not authorize cleanup of held disposal markers or retained SQL evidence. -- The absolute normalized `firemud.account.gameplay-login.request-digest-keyring-path` and `firemud.account.response-envelope.keyring-path` mounts. Existing mounted-key readers retain their active/retained-key, freshness and withdrawal checks; configuration does not create keys or replace absent mounted material. - -Missing or mismatched protected trust, absent selectors and invalid explicit policy prevent enabled composition. Missing current key, enrollment, publication, authority or Redis evidence still denies the existing owner operation. Source-bearing requests never fall back to legacy Authenticate. This configuration does not provision credentials, qualify external Redis reset/restore/promotion continuity, register Game Session's separate initial-context authority or enable gameplay admission. Source and proof status belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md index 0cffedacf4..12623d04c1 100644 --- a/design/architecture/microservices/account-service/runtime-and-data.md +++ b/design/architecture/microservices/account-service/runtime-and-data.md @@ -26,7 +26,7 @@ The additive [V1003 source-protection storage](../../../../services/account-serv The manually composed admission acquisition owner reads the retained original Account participation and Game Session attempt in a short transaction, obtains a fresh authenticated Game Session current-attempt read with no Account transaction open, then uses Account's existing currentness callback and source-key-before-protection lock order to install or replay the immutable protection. A separate committed read verifies the exact current protection bytes. The settlement owner reads the retained protection, obtains the exact Game Session terminal through its purpose-specific authenticated read outside SQL, stores the matching immutable Account settlement, and independently reads that receipt back. A missing, pending, unavailable, expired, or mismatched result does not release Account's source-writer exclusion; neither acquisition nor settlement renews the original lease. These source owners remain unregistered and provide no production admission or activation path. The [API contract](./api-contracts.md#startsession-admission-protection-acquisition) owns the transport boundary, and the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#original-startsession-source-protection-storage) owns proof status. -Account's initial private gameplay LOGIN source graph has an explicit default-off composition for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. The [configuration owner](./configuration.md#canonical-gameplay-login-receiving) specifies its required protected delivery and policy inputs. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. Conditional registration through the existing Account gRPC service does not provision signer enrollment, committed publication, key material or Redis custody; deployed ACL/TLS, consumer authorization, gameplay admission and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. +Account has an unregistered initial private gameplay LOGIN source slice for request-bound credential digests, signer and JWKS trust, pending and committed registry ownership, authority projection reads, and encrypted response recovery. Before its final Account transaction, the commit source publishes the current issuer and Account projections and requires an exact matching observation; publication or observation failure denies the commit. Caller currentness and response recovery may use an older committed signer generation only while the exact original public-key fingerprint remains in the current trusted JWKS and current owner evidence, including the original issuance JTI, still matches; the applicable authority, API, source, expiry, and compromise fences remain required. The source fixes the explicitly approved `game-session-account-delegation` profile and has no caller-selected profile or property bypass. It adds no endpoint or runtime registration; deployed ACL/TLS, signer-key custody, caller authentication, consumer authorization, gameplay admission, and runtime activation remain unproved. See the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake) for exact unit and physical fixture proof scope. Account's unregistered original-ACK owner preserves the original physical COMMIT and its separately committed receipt. Forward V1013 extends historical receipt recovery to PostgreSQL 18 while retaining V144/V146 and the original evidence. The private owner captures one fixed snapshot and WAL fence, releases its SQL locks, positively observes coverage of that unchanged fence, and independently compares the exact receipt. Focused PostgreSQL 18 proof covers this recovery boundary. The manually composed Java owner and current full migration lineage require PostgreSQL 18; the retained SQL reader’s historical PostgreSQL 16 predicate does not establish Java-owner or full-lineage support on that major. This source remains unregistered and supplies no caller authentication or gameplay admission. Migration provenance, proof and remaining gaps belong to the [Player Access and Session tracker](../../../project-management/implementation-tracking/player-access-and-session.md#account-fresh-original-ack-storage-preparation). @@ -82,7 +82,7 @@ With default composition absent, Account public bootstrap, `IssueDirectTextConne The target capacity retry contract uses stable outer `(tenantId, requestId, admissionId)`, fresh per-attempt `admissionAttemptId`, current `capacityRearmFence`, exact complete entitlement evidence, bounded `capacityDelta`, and a versioned `mutationDigest` over that attempt identity, fence, and complete payload. Exact retries replay the stored result. A new attempt requires an Account-owned atomic CAS over the same outer tuple, terminal `OWNER_EXECUTION/NOT_EXECUTED_AFTER_AUTHORIZATION` plus durable no-commit evidence, current fence, and prior digest; the CAS advances the fence without creating a second reservation. Changed fields without a matching rearm return `IDEMPOTENCY_CONFLICT`; stale or losing fences return `FENCE_REJECTED` only with durable no-accept/no-runtime-mutation proof. This remains target-only and follows the canonical [capacity-attempt proof obligations](../../system-architecture-versioning-runtime.md#focused-capacity-attempt-proof-obligations). -The canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. The adapter participates only in the explicitly enabled protected LOGIN composition; default deployment behavior remains unchanged. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). Deployed authenticated issuance and timing parity remain unproved. +The unregistered canonical gameplay LOGIN primary-credential adapter reuses Account’s password and email-OTP authority without creating a legacy token or session. Its owner transaction retains the verified challenge identity and consumes it only after new PENDING issuance; denial accounting and expiry cleanup commit under the existing owner denial path. Exact pending retry does not reverify or reconsume. Canonical-only verification pads to two KDF comparisons with non-authorizing process-local random decoy evidence using the existing Argon2 profile. Focused unit and real PostgreSQL proof and its controlled upstream/external-owner limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). No runtime bean, RPC, authenticated caller or signer/registry composition is activated; deployed timing parity remains unproved. Local unregistered Account owners now cover tenant-creation intent, admission, current authorization, and final initial-owner consent/reauthentication completion; the private Game Design receiver is also present. The dispatch and original read/close/recovery composition is present locally, while physical cross-owner qualification and public/default registration remain incomplete; creation and runtime admission are not enabled. The normative admission and recovery ordering belongs to [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md#account-tenant-creation-admission-receipt); implementation and proof status remain in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#account-tenant-creation-admission-preparation). @@ -180,7 +180,7 @@ If you change Redis usage for this service, you must read and apply: ## Session and Token Model -Initial LOGIN disposal uses forward V1005 `account_initial_gameplay_login_disposals` as immutable purpose identity, durable intent, closed owner-proof storage and original-request anti-resurrection guard. Account first locks the original Account when present, then the shared request advisory lock; a no-row race that discovers a newly inserted original retries in Account-first order. The new issuance writer trigger and repository/recovery/fence checks deny guarded original operations without modifying V150/V151, completing public logout, deleting issuance evidence or changing unrelated generations. Exact known hashes receive the single-key denied tombstone, pinned durability/readback and immutable physical proof described in the [token owner contract](../../system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal). No-row/unbound guard and complete current shape are independently read back from the durable primary with no Redis lookup. They remain `PENDING` because the protected retained binding-history/restore qualifier needed to produce the distinct `NO_ISSUANCE_BINDING` terminal proof is absent; bare current shape cannot replace it. Retention is held in SQL and denied Redis markers until explicit owner horizons and safe cleanup exist. The explicit default-off LOGIN composition includes this disposal owner through the existing Account service; it supplies neither the missing history qualifier nor runtime activation proof. +Initial LOGIN disposal uses forward V1005 `account_initial_gameplay_login_disposals` as immutable purpose identity, durable intent, closed owner-proof storage and original-request anti-resurrection guard. Account first locks the original Account when present, then the shared request advisory lock; a no-row race that discovers a newly inserted original retries in Account-first order. The new issuance writer trigger and repository/recovery/fence checks deny guarded original operations without modifying V150/V151, completing public logout, deleting issuance evidence or changing unrelated generations. Exact known hashes receive the single-key denied tombstone, pinned durability/readback and immutable physical proof described in the [token owner contract](../../system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal). No-row/unbound guard and complete current shape are independently read back from the durable primary with no Redis lookup. They remain `PENDING` because the protected retained binding-history/restore qualifier needed to produce the distinct `NO_ISSUANCE_BINDING` terminal proof is absent; bare current shape cannot replace it. Retention is held in SQL and denied Redis markers until explicit owner horizons and safe cleanup exist. These sources register no Spring bean or endpoint and provide no runtime activation proof. **Target state:** Authentication generates a `control-ui`, player-bootstrap, or receiver-specific private player-delegation JWT and establishes exactly one server-side `session:auth:token:` registry record before returning it, following [ADR 0035](../../decisions/adr-0035-single-record-issued-token-registry.md). The record proves exact issuance and active state; signed claims plus Account-owned revocation/version state determine tenant and global authority without scope-duplicated token keys. **Current runtime:** it still uses the legacy Account session key and does not yet provide this registry proof. diff --git a/design/architecture/microservices/game-session-service/configuration.md b/design/architecture/microservices/game-session-service/configuration.md index af0db29c64..da1714a54f 100644 --- a/design/architecture/microservices/game-session-service/configuration.md +++ b/design/architecture/microservices/game-session-service/configuration.md @@ -80,19 +80,4 @@ The generated reference carries the current defaults, descriptions, valid values ## Authenticated TCP Receiving -The [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving) owns the dedicated Gateway-to-Game Session mTLS configuration and custody contract. This receiver requires distinct same-namespace workload leaves and a separately reachable internal TLS port; the ordinary HTTP/WebSocket route and shared legacy TLS leaf cannot supply its authority. Public receiving composes only actual protected LOGIN/lobby source owners. Missing source qualification remains unavailable rather than selecting numeric entitlement or legacy credential fallback. See the [player access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) for current proof and missing provider boundaries. - -### Initial LOGIN protected sources - -`InitialGameplayLoginProtectedSourcesConfiguration` is disabled unless `firemud.game-session.initial-gameplay-login.protected-sources.enabled=true` is explicitly delivered. It composes only the dedicated initial-context Coordination connection provider and binding over independently delivered inputs. It does not register a public-key source, JWT cache or verifier. - -The remaining required properties share the `firemud.game-session.initial-gameplay-login.protected-sources` prefix: - -- `coordination.uri` is an independently delivered Secret-backed value with the exact `rediss` scheme, explicit host/port, `gamesession_coord_app` principal, nonempty credential and `/0` database. Query and fragment options are rejected. TLS peer/hostname verification is enabled, and the provider never consumes the ambient Redis factory or its endpoint. -- `coordination.command-timeout-millis` is explicit and between 1 and 60,000 milliseconds. -- `coordination.protected-binding-id` must identify the independently protected deployment binding. Configuration does not attest that identity or create maintenance authority. -- `coordination.profile`, `coordination.required-local-aof-count`, `coordination.required-replica-aof-count` and `coordination.acknowledgement-timeout-millis` select the existing [initial-context acknowledgement policy](../../system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy). Selecting `SINGLE_NODE_NO_FAILOVER` does not qualify the deployment as no-failover. - -The owner-local Lettuce provider disables reconnect before opening any binary connection and owns its dedicated client lifecycle. Each initial-context invocation owns its physical connection; the existing helper retains live principal, registered-script, same-connection acknowledgement and readback enforcement. Endpoint/TLS/ACL provisioning and deployment custody remain external prerequisites. - -This source opt-in supplies neither a steady-state asymmetric verifier nor `InitialGameplayLoginCoordinationQualification`; the existing authenticated runtime composition requires both, and both remain unavailable. Account's `GetCurrentReadinessReceiverMetadata` and the Game Session protected readiness identity/JWKS readers belong to finite rotation-readiness operations with complete, unexpired plans. They are not ordinary LOGIN trust sources and are not composed here. A genuine steady-state consumer must obtain Account-owned current publication provenance under the [JWT verification and rotation contract](../../system-architecture-jwt-and-token-contracts.md#signing-key-rotation-contract-normative), independently of readiness-plan lifetime. This configuration registers no readiness receiver or gameplay endpoint, provisions no source, and establishes no LOGIN success, protected admission or runtime activation. Detailed current proof and remaining qualification belong to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). +The [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving) owns the dedicated Gateway-to-Game Session mTLS configuration and custody contract. This receiver requires distinct same-namespace workload leaves and a separately reachable internal TLS port; the ordinary HTTP/WebSocket route and shared legacy TLS leaf cannot supply its authority. Public receiving accepts only actual protected LOGIN/lobby source owners. Their runtime and protected-source composition is a separate successor boundary; absent owners or source qualification remain unavailable rather than selecting numeric entitlement or legacy credential fallback. See the [player access tracker](../../../project-management/implementation-tracking/player-access-and-session.md) for current proof and missing provider boundaries. 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 46d578a6bc..ae4a0a4a80 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -63,7 +63,6 @@ The sections below define the target-state runtime contract. Current implementat - The current `IpConnectionLimiter` stores the source address directly in `ipconn:
` keys and `sessionip:` values, and registration passes both keys to one Lua invocation without a shared hash slot, so it fails with `CROSSSLOT` on Redis Cluster. This is not the ADR 0087 opaque-HMAC subject contract and has no evidenced tenant/policy scope or current Cache/Rate-Limit loss profile. The limiter remains a current heuristic seam; convergence requires one mutation on one opaque subject bucket, session lifecycle correlation outside exact cross-key atomicity, an owner-declared subject scope, opaque full-digest mapping, and focused privacy, isolation, eviction, reset, clustered, and unavailable-store proof; no final reverse-index design is implied. - Current Redis session-context and movement writers persist a projection without the raw `game-session-account-delegation` JWT, preserving other binding fields. Canonical/index and movement legacy reads return the same non-secret projection without rewriting retained values or extending their lifetime. Existing stored bytes are not globally erased: owner-fenced retained-value cleanup, complete rotation/rebind metadata and the rest of [ADR 0031](../../decisions/adr-0031-revocation-safe-session-token-rotation-and-logout.md) remain incomplete. Focused receiving proof and limits are tracked in [Player Access](../../../project-management/implementation-tracking/player-access-and-session.md#session-secret-and-presence-containment). - An unregistered initial-LOGIN journal, cleanup owner and exact-context Redis CAS/closure adapter are prepared independently of that legacy handler. The adapter follows the [initial-context owner](../../system-architecture-redis.md#initial-login-context-aggregate) and requires the separately supplied protected binding and external qualification; it does not implement legacy Redis context save/delete, trusted TCP custody or runtime LOGIN. Qualified source and physical proof status belongs to [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#initial-private-gameplay-login-issuance-source-intake). -- The default-off [initial LOGIN protected-source composition](./configuration.md#initial-login-protected-sources) supplies only a dedicated no-reconnect, verified-TLS Coordination client and binding over independently delivered inputs. It does not use the generic Redis factory or provide JWT trust or maintenance qualification. The steady-state Account-publication verifier and real external maintenance qualifier remain absent, so the authenticated LOGIN runtime gate remains closed. Finite rotation-readiness metadata and its protected projection readers cannot supply ordinary LOGIN provenance. Deployed Redis/source custody and live cross-owner proof remain separate prerequisites; no runtime activation or LOGIN success is established by this source preparation. - Bounded durable semantic reconnect-context persistence is partial: ordered `resume_transcript_entry` rows and best-effort Redis caching are live, while namespace-key migration to `{tenantId, playableStateNamespaceId, characterId}`, the distinct durable `resumeContextGeneration` episode fence and termination protocol, complete-envelope hard-bound accounting and omission-marker convergence, and durable logout invalidation remain implementation/proof gaps. Current reconnect suppresses private-context presentation without deleting retained rows; bounded receiving proof and the remaining episode/generation limits are recorded in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#reconnect-and-continuity). - Current live-presence registration, returned legacy projections and ordinary activity updates use `PLAYER`: no independently verified gameplay-grant carrier is available. JWT global/scoped roles and retained cached elevation grant no gameplay capability. Read projection does not persist the demotion or refresh TTL; ordinary activity writes retain their existing lifetime behavior and preserve other fields. The [authentication owner](../../system-architecture-authentication.md#global-role-to-route-class-matrix-normative) defines grant authority; [Player Experience](../../../project-management/implementation-tracking/player-experience-commands-and-communication.md#communication-social-and-presence) records implementation/proof limits. - Current live/recent presence projection wiring is implementation drift: `gameplaypresence:session:`, its game-instance/account set indexes, and `accountrecentpresence::` are written with untagged, separate Redis value/index operations. Game Session remains the target owner, but the physical shapes, storage-role classification, exact scope, partial-write handling, reset/rebuild/readback behavior, and private-by-failure contract are unproved; the [Redis owner and reset catalog](../../system-architecture-redis-reset-and-recovery.md#reset-policy-matrix-prefix-summary) records these current families without accepting them as target authority. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 737864888c..7d5bbed4b8 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -440,9 +440,7 @@ The passive Account source-fence seam leaves Draft source mutation and abort pen ### Initial private gameplay LOGIN issuance source intake -Account's private gameplay LOGIN has dispatch through the existing Account gRPC registration and an explicit default-off composition of the complete existing issuer, response-recovery, registry, evidence-repository, trusted-JWKS and disposal graph. Its protected configuration requires the independently delivered Account Coordination URI/principal, bounded explicit command/ACK policy with a positive replica minimum, canonical JWKS API binding, matching materializer/workload namespace identities and existing request-digest/response key mounts. Both initial issuer/account projection script contributions are installed; enabling a property does not create signer enrollment, committed publication or external custody evidence. Focused configuration tests use real intermediate implementations with controlled SQL, primary-credential, Redis transport and protected API/trust edges and therefore cannot qualify deployed custody or genuine LOGIN. Game Session still requires its independently supplied protected Redis binding, external qualification and trusted Account verifier; neither composition establishes playable LOGIN or canonical PLAY. The targeted source and fixture results, including their historical baselines and limits, are collected in [Initial private gameplay LOGIN source proof](#initial-private-gameplay-login-source-proof). - -The default-off Game Session source composition supplies only a dedicated verified-TLS, no-reconnect Coordination client and explicit initial-context binding/ACK policy over independently delivered inputs. It supplies no JWT verifier, readiness client or maintenance qualifier. The existing readiness metadata graph is finite and operation-scoped, so it is not reused as steady-state LOGIN provenance. A genuine Account current-publication consumer and external reset/restore/promotion exclusion remain missing; the authenticated runtime gate remains held. The current-parent focused graph passes 187 cases with zero failures, errors or skips: 7 core evidence, 103 Account source/selector and 77 Game Session source/owner/client cases. Account and Game Session main/unit Checkstyle, SpotBugs, formatting, affected compilation and Markdown checks pass. Controlled provider/configuration cases cover strict source selection and the owned client lifecycle; this component boundary does not establish deployed Redis, PKI, or maintenance custody. +Account's private gameplay LOGIN has fail-closed dispatch through the existing Account gRPC registration, but its issuer, response-recovery, registry, evidence-repository, trusted-JWKS and disposal graph remains unregistered. Canonical envelopes and exact-original retirement are unavailable without an independently supplied receiver and never select legacy credential fallback. The protected-source and runtime composition, including its configuration and focused proof, belongs to the successor source-composition boundary in [#3409](https://github.com/benhook1013/FireMUD/pull/3409). Game Session's protected Coordination binding, LOGIN/lobby runtime graph, external maintenance qualification and trusted Account verifier remain absent here; the authenticated receiver fails closed without them. The targeted source and fixture results, including their historical baselines and limits, are collected in [Initial private gameplay LOGIN source proof](#initial-private-gameplay-login-source-proof). Canonical disposal and original-attempt rules belong to [JWT and token contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#initial-gameplay-login-disposal), the [Redis initial-context acknowledgement owner](../../architecture/system-architecture-redis-usage-and-profiles.md#initial-login-context-acknowledgement-policy), and [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md#implementation-status). Protected binding-history/restore qualification, production trust and custody, and runtime activation remain gaps; source fixtures do not establish authenticated intake or playable LOGIN. @@ -456,7 +454,7 @@ The exact live backend socket/generation owns the genuine `InitialGameplayLoginO The latest completed focused gate passes 54 Gateway and 94 Game Session cases with zero failures, errors or skips, including actual mutual-TLS WebSocket upgrade, wrong-workload/namespace refusal before HTTP origin headers, exact-result custody, overlapping replacement drain, shutdown revocation and friendly JOIN wire routing. These cases use controlled upstream Account/result sources and are not genuine end-to-end Account issuance or public LOGIN-to-PLAY proof. The first Account dispatch run preserved 144 passing cases and four failed reject-before-payload assertions. After moving canonical selector dispatch behind the existing peer guard, the exact 148-case Account suite passes with zero failures, errors or skips. The physical Tomcat connector case requires client TLS, accepts only the exact Gateway namespace/workload, denies forged headers over public HTTP and limits the dedicated listener to the gameplay path. -Affected main, unit and integration sources compile. The initial nine Checkstyle scopes and three Gateway SpotBugs scopes passed, while four Game Session static findings required correction. The corrected source snapshots singleton header values and retains the canonical parsed literal address with an IPv6 regression case. The later Game Session main/unit/integration and Account static recovery scopes pass; its Markdown environment failure is retained separately from the subsequent successful formatting and Markdown checks. The current-parent Account and Game Session main/unit static graph also passes as recorded above. Base NetworkPolicy contract passes; hosted chart and deployment preflight contracts remain locally unrun because Helm and kubectl are unavailable. Protected Redis client composition now exists, but deployed Redis binding, external reset/restore/promotion exclusion, signing/currentness/source custody, final admission and real preview/CI LOGIN-to-PLAY remain incomplete. No fixture, mounted URI or process-local flag qualifies those authorities. +Affected main, unit and integration sources compile. The initial nine Checkstyle scopes and three Gateway SpotBugs scopes passed, while four Game Session static findings required correction. The corrected source snapshots singleton header values and retains the canonical parsed literal address with an IPv6 regression case. The later Game Session main/unit/integration and Account static recovery scopes pass; its Markdown environment failure is retained separately from the subsequent successful formatting and Markdown checks. The earlier complete source-composition graph has separately recorded Account and Game Session main/unit static proof in the successor; that historical result does not qualify this narrower patch boundary. Base NetworkPolicy contract passes; hosted chart and deployment preflight contracts remain locally unrun because Helm and kubectl are unavailable. Protected Redis client and runtime composition is retained in the successor; deployed Redis binding, external reset/restore/promotion exclusion, signing/currentness/source custody, final admission and real preview/CI LOGIN-to-PLAY remain incomplete. No fixture, mounted URI or process-local flag qualifies those authorities. ### Account signer/currentness storage evidence preparation diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfiguration.java deleted file mode 100644 index 7b95cb9ad8..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfiguration.java +++ /dev/null @@ -1,142 +0,0 @@ -package net.firedevops.firemud.accountservice.config; - -import io.lettuce.core.RedisCredentials; -import io.lettuce.core.RedisCredentialsProvider; -import io.lettuce.core.RedisURI; -import java.net.URI; -import java.nio.file.Path; -import java.time.Duration; -import java.util.Arrays; -import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; -import net.firedevops.firemud.accountservice.service.session.LettuceAccountCoordinationPinnedConnectionProvider; -import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** Selects delivered protected sources; never enrolls a signer or provisions Redis or keys. */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnProperty( - prefix = "firemud.account.gameplay-login", - name = "enabled", - havingValue = "true") -public class AccountGameplayLoginProtectedSourcesConfiguration { - static final String COORDINATION_CONNECTIONS = "accountGameplayLoginCoordinationConnections"; - static final String ACKNOWLEDGEMENT_REQUIREMENTS = "accountGameplayLoginAcknowledgements"; - private static final String JWKS_API_BINDING_PATH = "/etc/firemud/account-jwt-api/binding.json"; - - @Bean - AccountJwtJwksApiBinding accountGameplayLoginJwksApiBinding( - AccountJwtSignerMaterializerTrustBinding materializerTrust, - @Value("${firemud.account.gameplay-login.jwks-api-binding-path:}") String bindingPath, - @Value("${firemud.grpc.workload-namespace:}") String namespace) { - if (!JWKS_API_BINDING_PATH.equals(bindingPath) - || !GrpcPeerIdentity.isValidNamespace(namespace)) { - throw unavailable(); - } - try { - var api = new AccountJwtJwksApiBinding(true, bindingPath); - var materializer = materializerTrust.current().orElseThrow(); - var current = api.current(); - if (!namespace.equals(materializer.namespace()) - || !namespace.equals(current.namespace()) - || !materializer.environmentId().equals(current.environmentId()) - || !materializer.clusterId().equals(current.clusterId()) - || !materializer - .expectedClusterIncarnationUid() - .equals(current.expectedClusterIncarnationUid()) - || !materializer.expectedNamespaceUid().equals(current.expectedNamespaceUid())) { - throw unavailable(); - } - // current() pins the protected API identity. Existing owners reread and compare both trust - // sources on use; a later materializer namespace cannot replace this accepted API identity. - return api; - } catch (RuntimeException failure) { - throw unavailable(); - } - } - - @Bean(name = COORDINATION_CONNECTIONS, destroyMethod = "close") - LettuceAccountCoordinationPinnedConnectionProvider accountGameplayLoginCoordinationConnections( - @Value("${firemud.account.gameplay-login.coordination.uri:}") String configuredUri, - @Value("${firemud.account.gameplay-login.coordination.command-timeout-millis:0}") - int commandTimeoutMillis) { - try { - return new LettuceAccountCoordinationPinnedConnectionProvider( - requiredCoordinationUri(configuredUri, commandTimeoutMillis)); - } catch (RuntimeException failure) { - throw unavailable(); - } - } - - @Bean(name = ACKNOWLEDGEMENT_REQUIREMENTS) - AcknowledgementRequirements accountGameplayLoginAcknowledgements( - @Value("${firemud.account.gameplay-login.coordination.required-local-aof-count:0}") - int localAof, - @Value("${firemud.account.gameplay-login.coordination.required-replica-aof-count:0}") - int replicaAof, - @Value("${firemud.account.gameplay-login.coordination.acknowledgement-timeout-millis:0}") - int timeoutMillis) { - return new AcknowledgementRequirements(localAof, replicaAof, timeoutMillis); - } - - static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) { - char[] password = null; - try { - if (configuredUri == null - || configuredUri.length() > 4096 - || timeoutMillis < 1 - || timeoutMillis > 60_000) { - throw unavailable(); - } - URI uri = URI.create(configuredUri); - String userInfo = uri.getUserInfo(); - String principal = AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY; - if (!"rediss".equals(uri.getScheme()) - || uri.getHost() == null - || uri.getHost().isBlank() - || uri.getPort() < 1 - || uri.getPort() > 65_535 - || !"/0".equals(uri.getRawPath()) - || uri.getRawQuery() != null - || uri.getRawFragment() != null - || userInfo == null - || !userInfo.startsWith(principal + ":") - || userInfo.length() == principal.length() + 1 - || userInfo.chars().anyMatch(Character::isISOControl)) { - throw unavailable(); - } - password = userInfo.substring(principal.length() + 1).toCharArray(); - var credentials = RedisCredentials.just(principal, password); - return RedisURI.Builder.redis(uri.getHost(), uri.getPort()) - .withSsl(true) - .withVerifyPeer(true) - .withAuthentication(RedisCredentialsProvider.from(() -> credentials)) - .withDatabase(0) - .withTimeout(Duration.ofMillis(timeoutMillis)) - .build(); - } catch (RuntimeException failure) { - // In particular, do not retain URI/parser causes containing the delivered password. - throw unavailable(); - } finally { - if (password != null) Arrays.fill(password, '\0'); - } - } - - static Path requiredMount(String value) { - if (value == null || value.isBlank()) throw unavailable(); - try { - Path path = Path.of(value); - if (!path.isAbsolute() || !path.equals(path.normalize())) throw unavailable(); - return path; - } catch (RuntimeException failure) { - throw unavailable(); - } - } - - private static IllegalArgumentException unavailable() { - return new IllegalArgumentException("Protected Account gameplay LOGIN configuration required"); - } -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfiguration.java deleted file mode 100644 index 5886704d20..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfiguration.java +++ /dev/null @@ -1,178 +0,0 @@ -package net.firedevops.firemud.accountservice.config; - -import java.time.Clock; -import java.util.List; -import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; -import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; -import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; -import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisScriptContribution; -import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider; -import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisScriptContribution; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; -import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; -import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; -import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; -import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; -import org.jooq.DSLContext; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.PlatformTransactionManager; - -/** Complete initial-LOGIN owner graph over the existing protected source implementations. */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnProperty( - prefix = "firemud.account.gameplay-login", - name = "enabled", - havingValue = "true") -public class AccountGameplayLoginSourceConfiguration { - @Bean - AccountAuthEvidenceBundleRepository accountGameplayLoginEvidenceBundles( - DSLContext dsl, - AccountAuthorityGenerationRepository generations, - AccountAuthorityOutboxRepository outbox) { - return new AccountAuthEvidenceBundleRepository(dsl, generations, outbox); - } - - @Bean - AccountGameplayDelegationIssuanceRepository accountGameplayLoginIssuanceRepository( - DSLContext dsl, - AccountAuthoritySourceEvidenceRepository sources, - AccountAuthEvidenceBundleRepository bundles) { - return new AccountGameplayDelegationIssuanceRepository(dsl, sources, bundles); - } - - @Bean - AccountGameplayDelegationResponseEnvelopeRepository accountGameplayLoginResponseEnvelopes( - DSLContext dsl, - AccountAuthoritySourceEvidenceRepository sources, - AccountAuthEvidenceBundleRepository bundles, - AccountGameplayDelegationIssuanceRepository issuance, - @Qualifier("accountResponseEnvelopeCryptography") AccountResponseEnvelopeCryptography crypto, - @Value("${firemud.account.response-envelope.keyring-path:}") String responseKeyring) { - AccountGameplayLoginProtectedSourcesConfiguration.requiredMount(responseKeyring); - return new AccountGameplayDelegationResponseEnvelopeRepository( - dsl, sources, bundles, issuance, crypto); - } - - @Bean - AccountGameplayDelegationResponseEnvelopeService accountGameplayLoginResponseEnvelopeService( - AccountGameplayDelegationResponseEnvelopeRepository envelopes) { - return new AccountGameplayDelegationResponseEnvelopeService(envelopes); - } - - @Bean - AccountJwtJwksConfigMapClient accountGameplayLoginJwksClient(AccountJwtJwksApiBinding api) { - return new AccountJwtJwksConfigMapClient(api); - } - - @Bean - AccountJwtJwksTrustedSource accountGameplayLoginTrustedJwks( - AccountJwtJwksConfigMapClient client, - AccountJwtSignerMaterializerTrustBinding trust, - AccountJwtSignerDesiredStateRepository signers, - AccountJwtJwksPublicationRepository publications, - @Qualifier("transactionManager") PlatformTransactionManager transactions) { - return new AccountJwtJwksTrustedSource(client, trust, signers, publications, transactions); - } - - @Bean - AccountGameplayDelegationSigner accountGameplayLoginSigner( - AccountGameplayDelegationIssuanceRepository issuance, - AccountJwtSignerDesiredStateRepository signers, - AccountJwtSignerMaterializerTrustBinding trust, - AccountJwtJwksApiBinding api, - AccountJwtJwksTrustedSource jwks, - AccountGameplayDelegationResponseEnvelopeService envelopes, - @Qualifier("transactionManager") PlatformTransactionManager transactions) { - return new AccountGameplayDelegationSigner( - issuance, signers, trust, api, jwks, envelopes, transactions, Clock.systemUTC()); - } - - @Bean - AccountGameplayDelegationRedisClient accountGameplayLoginRedis( - @Qualifier(AccountGameplayLoginProtectedSourcesConfiguration.COORDINATION_CONNECTIONS) - AccountCoordinationPinnedConnectionProvider connections, - @Qualifier(AccountGameplayLoginProtectedSourcesConfiguration.ACKNOWLEDGEMENT_REQUIREMENTS) - AcknowledgementRequirements acknowledgements) { - return new AccountGameplayDelegationRedisClient( - connections, - RedisScriptCatalog.fromContributions( - List.of( - new AccountGameplayDelegationRedisScriptContribution(), - new AccountGenerationProjectionRedisScriptContribution())), - acknowledgements, - Clock.systemUTC(), - GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, - AccountGameplayDelegationRedisClient.class.getClassLoader()); - } - - @Bean - AccountGameplayDelegationAuthorityProjection accountGameplayLoginAuthorityProjection( - AccountAuthoritySourceEvidenceRepository sources, - @Qualifier("transactionManager") PlatformTransactionManager transactions, - AccountGameplayDelegationRedisClient redis) { - return new AccountGameplayDelegationAuthorityProjection(sources, transactions, redis); - } - - @Bean - AccountGameplayDelegationTokenRegistry accountGameplayLoginTokenRegistry( - AccountGameplayDelegationIssuanceRepository issuance, - @Qualifier("transactionManager") PlatformTransactionManager transactions, - AccountGameplayDelegationRedisClient redis, - @Value("${firemud.account.gameplay-login.registry-cleanup-margin-millis}") - long cleanupMargin) { - return new AccountGameplayDelegationTokenRegistry( - issuance, - transactions, - redis, - Clock.systemUTC(), - GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES, - cleanupMargin); - } - - @Bean - AccountGameplayDelegationIssuanceCommitService accountGameplayLoginCommits( - AccountGameplayDelegationSigner signer, - AccountGameplayDelegationTokenRegistry registry, - AccountGameplayDelegationAuthorityProjection projections, - AccountGameplayDelegationIssuanceRepository issuance, - @Qualifier("transactionManager") PlatformTransactionManager transactions) { - return new AccountGameplayDelegationIssuanceCommitService( - signer, registry, projections, issuance, transactions, Clock.systemUTC()); - } - - @Bean - AccountGameplayDelegationCommittedIssuanceOwner accountGameplayLoginCommittedIssuance( - AccountGameplayDelegationIssuanceRepository issuance, - AccountGameplayDelegationSigner signer, - AccountGameplayDelegationTokenRegistry registry, - @Qualifier("transactionManager") PlatformTransactionManager transactions) { - return new AccountGameplayDelegationCommittedIssuanceOwner( - issuance, signer, registry, transactions, Clock.systemUTC()); - } - - @Bean - AccountGameplayDelegationResponseRecoveryOwner accountGameplayLoginResponseRecovery( - AccountGameplayDelegationResponseEnvelopeRepository envelopes, - AccountGameplayDelegationCommittedIssuanceOwner committed, - @Qualifier("transactionManager") PlatformTransactionManager transactions) { - return new AccountGameplayDelegationResponseRecoveryOwner(envelopes, committed, transactions); - } -} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java deleted file mode 100644 index 36447ee6cd..0000000000 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/CanonicalGameplayRuntimeConfiguration.java +++ /dev/null @@ -1,56 +0,0 @@ -package net.firedevops.firemud.accountservice.config; - -import java.time.Clock; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; -import net.firedevops.firemud.accountservice.repository.AccountInitialGameplayLoginDisposalRepository; -import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAuthenticateReceiver; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayCanonicalLoginOwner; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayPrimaryCredentialVerifier; -import net.firedevops.firemud.accountservice.service.session.AccountInitialGameplayLoginDisposalOwner; -import net.firedevops.firemud.accountservice.service.session.AccountMountedGameplayCredentialDigestKeySource; -import org.jooq.DSLContext; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.PlatformTransactionManager; - -/** Receiving composition over the actual protected issuance, recovery and registry owners. */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnProperty( - prefix = "firemud.account.gameplay-login", - name = "enabled", - havingValue = "true") -public class CanonicalGameplayRuntimeConfiguration { - @Bean - AccountGameplayAuthenticateReceiver canonicalGameplayAuthenticateReceiver( - AccountRepository accounts, - AccountGameplayDelegationIssuanceRepository issuance, - AccountGameplayDelegationIssuanceCommitService commits, - AccountGameplayDelegationResponseRecoveryOwner recovery, - AccountGameplayDelegationTokenRegistry registry, - AccountServiceImpl primary, - DSLContext dsl, - @Qualifier("transactionManager") PlatformTransactionManager transactions, - @Value("${firemud.account.gameplay-login.request-digest-keyring-path:}") String digestKeyring, - @Value("${firemud.grpc.workload-namespace:}") String namespace) { - var clock = Clock.systemUTC(); - var digestKeys = - new AccountMountedGameplayCredentialDigestKeySource( - AccountGameplayLoginProtectedSourcesConfiguration.requiredMount(digestKeyring), clock); - var owner = - new AccountGameplayCanonicalLoginOwner( - accounts, issuance, digestKeys, commits, recovery, transactions, clock); - var disposal = - new AccountInitialGameplayLoginDisposalOwner( - new AccountInitialGameplayLoginDisposalRepository(dsl), registry, transactions); - return new AccountGameplayAuthenticateReceiver( - owner, new AccountGameplayPrimaryCredentialVerifier(primary), namespace, disposal); - } -} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java deleted file mode 100644 index 6748fa22df..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java +++ /dev/null @@ -1,198 +0,0 @@ -package net.firedevops.firemud.accountservice.config; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockConstruction; -import static org.mockito.Mockito.when; - -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import io.lettuce.core.RedisURI; -import java.net.URI; -import java.nio.file.Path; -import java.time.Duration; -import java.util.List; -import java.util.Optional; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -/** Controlled configuration proof only; no production credentials or protected mounts are read. */ -class AccountGameplayLoginProtectedSourcesConfigurationTest { - static final String API_PATH = "/etc/firemud/account-jwt-api/binding.json"; - private final AccountGameplayLoginProtectedSourcesConfiguration configuration = - new AccountGameplayLoginProtectedSourcesConfiguration(); - - @Test - void dedicatedUriRetainsExplicitTlsAclDatabaseAndCommandDeadline() { - RedisURI uri = - AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( - "rediss://account_coord_app:test-only-password@coordination.example.invalid:6380/0", - 875); - - assertThat(uri.getHost()).isEqualTo("coordination.example.invalid"); - assertThat(uri.getPort()).isEqualTo(6380); - assertThat(uri.getDatabase()).isZero(); - assertThat(uri.isSsl()).isTrue(); - assertThat(uri.isVerifyPeer()).isTrue(); - var credentials = - uri.getCredentialsProvider().resolveCredentials().block(Duration.ofSeconds(1)); - assertThat(credentials).isNotNull(); - assertThat(credentials.getUsername()).isEqualTo("account_coord_app"); - assertThat(credentials.getPassword()).containsExactly("test-only-password".toCharArray()); - assertThat(uri.getTimeout()).isEqualTo(Duration.ofMillis(875)); - } - - @ParameterizedTest - @ValueSource( - strings = { - "", - "redis://account_coord_app:secret@coordination.example.invalid:6380/0", - "rediss://default:secret@coordination.example.invalid:6380/0", - "rediss://account_coord_app:@coordination.example.invalid:6380/0", - "rediss://account_coord_app:secret@coordination.example.invalid/0", - "rediss://account_coord_app:secret@coordination.example.invalid:6380", - "rediss://account_coord_app:secret@coordination.example.invalid:6380/1", - "rediss://account_coord_app:secret@coordination.example.invalid:6380/0?verifyPeer=false", - "rediss://account_coord_app:secret@coordination.example.invalid:6380/0#extra", - "rediss://account_coord_app:secret%0a@coordination.example.invalid:6380/0", - "not a URI containing secret" - }) - void refusesMissingAmbiguousOrWeakerUriWithoutRetainingCredentialCauses(String uri) { - assertThatThrownBy( - () -> - AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri(uri, 500)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Protected Account gameplay LOGIN configuration required") - .hasNoCause(); - } - - @ParameterizedTest - @ValueSource(ints = {0, -1, 60_001}) - void commandDeadlineMustBeExplicitAndBounded(int timeout) { - assertThatThrownBy( - () -> - AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( - "rediss://account_coord_app:secret@coordination.example.invalid:6380/0", - timeout)) - .isInstanceOf(IllegalArgumentException.class) - .hasNoCause(); - } - - @Test - void accountAcknowledgementsCannotUseTheGameSessionSingleNodeException() { - var ack = configuration.accountGameplayLoginAcknowledgements(1, 2, 750); - assertThat(ack.requiredLocalAofCount()).isEqualTo(1); - assertThat(ack.requiredReplicaAofCount()).isEqualTo(2); - assertThat(ack.timeoutMillis()).isEqualTo(750); - assertThatThrownBy(() -> configuration.accountGameplayLoginAcknowledgements(1, 0, 750)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> configuration.accountGameplayLoginAcknowledgements(0, 1, 750)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> configuration.accountGameplayLoginAcknowledgements(1, 1, 0)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - void protectedApiAndMaterializerMustMatchTheConfiguredNamespaceAndIncarnations() { - var trust = mock(AccountJwtSignerMaterializerTrustBinding.class); - when(trust.current()).thenReturn(Optional.of(materializerBinding())); - try (var construction = - mockConstruction( - AccountJwtJwksApiBinding.class, - (api, context) -> when(api.current()).thenReturn(apiBinding("test", "cluster-a")))) { - assertThat(configuration.accountGameplayLoginJwksApiBinding(trust, API_PATH, "test")) - .isSameAs(construction.constructed().getFirst()); - assertThatThrownBy( - () -> configuration.accountGameplayLoginJwksApiBinding(trust, API_PATH, "other")) - .isInstanceOf(IllegalArgumentException.class) - .hasNoCause(); - } - try (var construction = - mockConstruction( - AccountJwtJwksApiBinding.class, - (api, context) -> - when(api.current()).thenReturn(apiBinding("test", "other-cluster")))) { - assertThatThrownBy( - () -> configuration.accountGameplayLoginJwksApiBinding(trust, API_PATH, "test")) - .isInstanceOf(IllegalArgumentException.class) - .hasNoCause(); - assertThat(construction.constructed()).hasSize(1); - } - } - - @Test - void missingWithdrawnOrAlternateProtectedSourcesNeverProduceAnApiBinding() { - var trust = mock(AccountJwtSignerMaterializerTrustBinding.class); - when(trust.current()).thenReturn(Optional.empty()); - try (var construction = mockConstruction(AccountJwtJwksApiBinding.class)) { - assertThatThrownBy( - () -> configuration.accountGameplayLoginJwksApiBinding(trust, API_PATH, "test")) - .isInstanceOf(IllegalArgumentException.class) - .hasNoCause(); - assertThat(construction.constructed()).hasSize(1); - } - when(trust.current()).thenReturn(Optional.of(materializerBinding())); - try (var construction = - mockConstruction( - AccountJwtJwksApiBinding.class, - (api, context) -> - when(api.current()) - .thenThrow(new AccountJwtJwksApiBinding.BindingRejectedException()))) { - assertThatThrownBy( - () -> configuration.accountGameplayLoginJwksApiBinding(trust, API_PATH, "test")) - .isInstanceOf(IllegalArgumentException.class) - .hasNoCause(); - assertThat(construction.constructed()).hasSize(1); - } - assertThatThrownBy( - () -> - configuration.accountGameplayLoginJwksApiBinding( - trust, "/alternate/binding", "test")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> configuration.accountGameplayLoginJwksApiBinding(trust, API_PATH, "")) - .isInstanceOf(IllegalArgumentException.class); - } - - @ParameterizedTest - @ValueSource(strings = {"", "relative/keyring", "/run/../other/keyring"}) - void missingRelativeOrUnnormalizedMountSelectorsFail(String path) { - assertThatThrownBy(() -> AccountGameplayLoginProtectedSourcesConfiguration.requiredMount(path)) - .isInstanceOf(IllegalArgumentException.class) - .hasNoCause(); - } - - static AccountJwtSignerMaterializerTrustBinding.Binding materializerBinding() { - String clusterUid = "11111111-1111-4111-8111-111111111111"; - String namespaceUid = "22222222-2222-4222-8222-222222222222"; - String peer = "spiffe://firemud/ns/test/sa/account-jwt-signer-materializer"; - List pins = List.of("a".repeat(64)); - String digest = - AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( - "test-revision", "test", "cluster-a", "test", clusterUid, namespaceUid, peer, pins); - return new AccountJwtSignerMaterializerTrustBinding.Binding( - "test", "cluster-a", "test", clusterUid, namespaceUid, peer, pins, "test-revision", digest); - } - - @SuppressFBWarnings( - value = "DMI_HARDCODED_ABSOLUTE_FILENAME", - justification = - "Fixed nonexistent paths identify controlled API metadata in this wiring-only test; no protected mount, token or certificate is read.") - static AccountJwtJwksApiBinding.ParsedBinding apiBinding(String namespace, String cluster) { - var trust = materializerBinding(); - return new AccountJwtJwksApiBinding.ParsedBinding( - "test-api-revision", - trust.environmentId(), - cluster, - URI.create("https://api.example.invalid:6443/"), - "api.example.invalid", - Path.of("/not-read-by-configuration-test/serving-ca.pem"), - "b".repeat(64), - Path.of("/not-read-by-configuration-test/token"), - namespace, - trust.expectedClusterIncarnationUid(), - trust.expectedNamespaceUid(), - "system:serviceaccount:" + namespace + ":account-service", - "c".repeat(64)); - } -} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java deleted file mode 100644 index 614dfd3ac5..0000000000 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java +++ /dev/null @@ -1,301 +0,0 @@ -package net.firedevops.firemud.accountservice.config; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockConstruction; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -import io.lettuce.core.ClientOptions; -import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; -import io.lettuce.core.codec.ByteArrayCodec; -import java.util.List; -import java.util.Optional; -import net.firedevops.firemud.accountservice.repository.AccountAuthEvidenceBundleRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; -import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; -import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository; -import net.firedevops.firemud.accountservice.repository.AccountJwtJwksPublicationRepository; -import net.firedevops.firemud.accountservice.repository.AccountJwtSignerDesiredStateRepository; -import net.firedevops.firemud.accountservice.repository.AccountRepository; -import net.firedevops.firemud.accountservice.service.AccountGenerationProjectionRedisContract; -import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; -import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider.AcknowledgementRequirements; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayAuthenticateReceiver; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationAuthorityProjection; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationIssuanceCommitService; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationRedisClient; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseEnvelopeService; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationResponseRecoveryOwner; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; -import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; -import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksConfigMapClient; -import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; -import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; -import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeKeyring; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; -import org.jooq.DSLContext; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; -import org.springframework.boot.test.context.TestConfiguration; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.springframework.context.annotation.Bean; -import org.springframework.test.util.ReflectionTestUtils; -import org.springframework.transaction.PlatformTransactionManager; - -/** - * Real intermediate-owner wiring with controlled SQL, primary credentials, API trust and Redis - * transport edges. This does not prove protected key custody, enrolled signer state or LOGIN. - */ -class AccountGameplayLoginSourceConfigurationTest { - private static final Class[] CONFIGURATIONS = { - CanonicalGameplayRuntimeConfiguration.class, - AccountGameplayLoginSourceConfiguration.class, - AccountGameplayLoginProtectedSourcesConfiguration.class - }; - - @Test - void entireGraphIsAbsentByDefaultEvenWithoutOwnerInfrastructure() { - new ApplicationContextRunner() - .withUserConfiguration(CONFIGURATIONS) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(AccountGameplayAuthenticateReceiver.class); - assertThat(context).doesNotHaveBean(AccountGameplayDelegationSigner.class); - assertThat(context).doesNotHaveBean(AccountJwtJwksApiBinding.class); - assertThat(context).doesNotHaveBean(AccountGameplayDelegationRedisClient.class); - }); - new ApplicationContextRunner() - .withUserConfiguration(CONFIGURATIONS) - .withPropertyValues("firemud.account.gameplay-login.enabled=false") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(AccountGameplayAuthenticateReceiver.class); - }); - } - - @Test - void explicitEnableCannotSilentlyLeaveTheReceiverUncomposed() { - new ApplicationContextRunner() - .withUserConfiguration(CONFIGURATIONS) - .withPropertyValues("firemud.account.gameplay-login.enabled=true") - .run(context -> assertThat(context).hasFailed()); - } - - @Test - void fullCompositionUsesGenuineIntermediateOwnersAndClosesItsDedicatedClient() { - RedisClient client = mock(RedisClient.class); - try (var redisFactory = mockStatic(RedisClient.class); - var apiConstruction = - mockConstruction( - AccountJwtJwksApiBinding.class, - (api, construction) -> - when(api.current()) - .thenReturn( - AccountGameplayLoginProtectedSourcesConfigurationTest.apiBinding( - "test", "cluster-a")))) { - redisFactory.when(() -> RedisClient.create(any(RedisURI.class))).thenReturn(client); - enabledContext() - .run( - context -> { - assertThat(context).hasNotFailed(); - for (Class owner : - List.of( - AccountAuthEvidenceBundleRepository.class, - AccountGameplayDelegationIssuanceRepository.class, - AccountGameplayDelegationResponseEnvelopeRepository.class, - AccountGameplayDelegationResponseEnvelopeService.class, - AccountJwtJwksConfigMapClient.class, - AccountJwtJwksTrustedSource.class, - AccountGameplayDelegationSigner.class, - AccountGameplayDelegationRedisClient.class, - AccountGameplayDelegationAuthorityProjection.class, - AccountGameplayDelegationTokenRegistry.class, - AccountGameplayDelegationIssuanceCommitService.class, - AccountGameplayDelegationCommittedIssuanceOwner.class, - AccountGameplayDelegationResponseRecoveryOwner.class, - AccountGameplayAuthenticateReceiver.class)) { - assertThat(context).hasSingleBean(owner); - } - - var issuance = context.getBean(AccountGameplayDelegationIssuanceRepository.class); - var signer = context.getBean(AccountGameplayDelegationSigner.class); - var commits = context.getBean(AccountGameplayDelegationIssuanceCommitService.class); - var recovery = - context.getBean(AccountGameplayDelegationResponseRecoveryOwner.class); - var registry = context.getBean(AccountGameplayDelegationTokenRegistry.class); - var envelopes = - context.getBean(AccountGameplayDelegationResponseEnvelopeRepository.class); - assertThat(ReflectionTestUtils.getField(signer, "issuanceRepository")) - .isSameAs(issuance); - assertThat(ReflectionTestUtils.getField(commits, "signer")).isSameAs(signer); - assertThat(ReflectionTestUtils.getField(commits, "tokenRegistry")) - .isSameAs(registry); - assertThat(ReflectionTestUtils.getField(recovery, "responseEnvelopes")) - .isSameAs(envelopes); - assertThat(ReflectionTestUtils.getField(envelopes, "responseCryptography")) - .isSameAs(context.getBean("accountResponseEnvelopeCryptography")); - var receiver = context.getBean(AccountGameplayAuthenticateReceiver.class); - var login = ReflectionTestUtils.getField(receiver, "owner"); - assertThat(ReflectionTestUtils.getField(login, "commitOwner")).isSameAs(commits); - assertThat(ReflectionTestUtils.getField(login, "responseOwner")).isSameAs(recovery); - assertThat(ReflectionTestUtils.getField(receiver, "expectedWorkload")) - .isEqualTo("spiffe://firemud/ns/test/sa/game-session-service"); - assertThat(context.getBean(AcknowledgementRequirements.class)) - .isEqualTo(new AcknowledgementRequirements(1, 2, 900)); - var catalog = - (RedisScriptCatalog) - ReflectionTestUtils.getField( - context.getBean(AccountGameplayDelegationRedisClient.class), - "scriptCatalog"); - assertThat(catalog).isNotNull(); - assertThat(catalog.require(AccountGenerationProjectionRedisContract.SCRIPT_ID)) - .isEqualTo(AccountGenerationProjectionRedisContract.descriptor()); - assertThat( - catalog.require(AccountGameplayDelegationRedisClient.SCRIPT_ID).principal()) - .isEqualTo("account_coord_app"); - assertThat( - catalog - .require( - AccountGameplayDelegationRedisClient - .INITIAL_LOGIN_DISPOSAL_SCRIPT_ID) - .principal()) - .isEqualTo("account_coord_app"); - assertThat(apiConstruction.constructed()).hasSize(1); - verifyNoInteractions(context.getBean(DSLContext.class)); - verifyNoInteractions(context.getBean(AccountServiceImpl.class)); - verify(client, never()).connect(ByteArrayCodec.INSTANCE); - }); - var options = ArgumentCaptor.forClass(ClientOptions.class); - verify(client).setOptions(options.capture()); - assertThat(options.getValue().isAutoReconnect()).isFalse(); - verify(client).shutdown(); - } - } - - @Test - void absentMountSelectorsAndUnboundedRetentionFailWithoutOpeningConnections() { - RedisClient client = mock(RedisClient.class); - try (var redisFactory = mockStatic(RedisClient.class); - var apiConstruction = - mockConstruction( - AccountJwtJwksApiBinding.class, - (api, construction) -> - when(api.current()) - .thenReturn( - AccountGameplayLoginProtectedSourcesConfigurationTest.apiBinding( - "test", "cluster-a")))) { - redisFactory.when(() -> RedisClient.create(any(RedisURI.class))).thenReturn(client); - enabledContext() - .withPropertyValues("firemud.account.gameplay-login.request-digest-keyring-path=") - .run(context -> assertThat(context).hasFailed()); - enabledContext() - .withPropertyValues("firemud.account.response-envelope.keyring-path=") - .run(context -> assertThat(context).hasFailed()); - enabledContext() - .withPropertyValues( - "firemud.account.gameplay-login.registry-cleanup-margin-millis=300001") - .run(context -> assertThat(context).hasFailed()); - assertThat(apiConstruction.constructed()).isNotEmpty(); - verify(client, never()).connect(ByteArrayCodec.INSTANCE); - } - } - - private static ApplicationContextRunner enabledContext() { - return new ApplicationContextRunner() - .withUserConfiguration(CONFIGURATIONS) - .withUserConfiguration(ExistingOwnerInfrastructure.class) - .withPropertyValues( - "firemud.account.gameplay-login.enabled=true", - "firemud.grpc.workload-namespace=test", - "firemud.account.gameplay-login.jwks-api-binding-path=" - + AccountGameplayLoginProtectedSourcesConfigurationTest.API_PATH, - "firemud.account.gameplay-login.coordination.uri=" - + "rediss://account_coord_app:test-only-password@coordination.example.invalid:6380/0", - "firemud.account.gameplay-login.coordination.command-timeout-millis=800", - "firemud.account.gameplay-login.coordination.required-local-aof-count=1", - "firemud.account.gameplay-login.coordination.required-replica-aof-count=2", - "firemud.account.gameplay-login.coordination.acknowledgement-timeout-millis=900", - "firemud.account.gameplay-login.registry-cleanup-margin-millis=5000", - "firemud.account.gameplay-login.request-digest-keyring-path=/not-read-by-configuration-test/digest", - "firemud.account.response-envelope.keyring-path=/not-read-by-configuration-test/response"); - } - - @TestConfiguration(proxyBeanMethods = false) - static class ExistingOwnerInfrastructure { - @Bean - DSLContext dsl() { - return mock(DSLContext.class); - } - - @Bean - AccountAuthorityGenerationRepository generations(DSLContext dsl) { - return new AccountAuthorityGenerationRepository(dsl); - } - - @Bean - AccountAuthorityOutboxRepository outbox(DSLContext dsl) { - return new AccountAuthorityOutboxRepository(dsl); - } - - @Bean - AccountAuthoritySourceEvidenceRepository sources( - DSLContext dsl, - AccountAuthorityGenerationRepository generations, - AccountAuthorityOutboxRepository outbox) { - return new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); - } - - @Bean - AccountRepository accounts(DSLContext dsl, AccountAuthoritySourceEvidenceRepository sources) { - return new AccountRepository(dsl, sources); - } - - @Bean - AccountJwtSignerDesiredStateRepository signers(DSLContext dsl) { - return new AccountJwtSignerDesiredStateRepository(dsl); - } - - @Bean - AccountJwtJwksPublicationRepository publications( - DSLContext dsl, AccountJwtSignerDesiredStateRepository signers) { - return new AccountJwtJwksPublicationRepository(dsl, signers); - } - - @Bean - AccountServiceImpl primaryCredentials() { - return mock(AccountServiceImpl.class); - } - - @Bean(name = "transactionManager") - PlatformTransactionManager transactions() { - return mock(PlatformTransactionManager.class); - } - - @Bean - AccountJwtSignerMaterializerTrustBinding materializerTrust() { - var trust = mock(AccountJwtSignerMaterializerTrustBinding.class); - when(trust.current()) - .thenReturn( - Optional.of( - AccountGameplayLoginProtectedSourcesConfigurationTest.materializerBinding())); - return trust; - } - - @Bean - AccountResponseEnvelopeCryptography accountResponseEnvelopeCryptography() { - return new AccountResponseEnvelopeCryptography( - new AccountResponseEnvelopeKeyring("/not-read-by-configuration-test/response")); - } - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfiguration.java deleted file mode 100644 index 404fd31c08..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfiguration.java +++ /dev/null @@ -1,104 +0,0 @@ -package net.firedevops.firemud.gamesession.config; - -import java.time.Clock; -import java.time.Duration; -import java.util.List; -import net.firedevops.firemud.common.config.ServiceEndpointsProperties; -import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.grpc.GrpcChannelFactory; -import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; -import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; -import net.firedevops.firemud.gamesession.client.AccountClient; -import net.firedevops.firemud.gamesession.client.CanonicalGameplayLoginAccountClient; -import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; -import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; -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.InitialGameplayLoginCleanupOwner; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginContextRedisClient; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCoordinationQualification; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisAttemptClosure; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisScriptContribution; -import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; -import org.jooq.DSLContext; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.PlatformTransactionManager; - -/** Composes genuine receiving owners only from independently supplied protected source custody. */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnBean({ - InitialGameplayLoginRedisBinding.class, - InitialGameplayLoginCoordinationQualification.class, - AccountAsymmetricJwtVerifier.class, - CanonicalPlayerRouteReadService.class -}) -public class AuthenticatedGameplayRuntimeConfiguration { - @Bean(initMethod = "initialize", destroyMethod = "close") - CanonicalGameplayLoginAccountClient canonicalGameplayLoginAccountClient( - ServiceEndpointsProperties endpoints, - CommonGrpcClientProperties tls, - GrpcChannelFactory channels, - BlockingGrpcStubCustomizer customizer, - AccountAsymmetricJwtVerifier verifier, - @Value("${firemud.grpc.workload-namespace:}") String namespace) { - return new CanonicalGameplayLoginAccountClient( - endpoints, - tls, - channels, - customizer, - namespace, - Clock.systemUTC(), - Duration.ofSeconds(3), - verifier); - } - - @Bean - InitialGameplayLoginOwner initialGameplayLoginOwner( - InitialGameplayLoginRedisBinding binding, - InitialGameplayLoginCoordinationQualification qualification, - CanonicalGameplayLoginAccountClient account, - DSLContext dsl, - @Qualifier("transactionManager") PlatformTransactionManager transactions) { - var contexts = - new InitialGameplayLoginContextRedisClient( - binding, - RedisScriptCatalog.fromContributions( - List.of(new InitialGameplayLoginRedisScriptContribution())), - qualification); - var cleanup = - new InitialGameplayLoginCleanupOwner( - new InitialGameplayLoginCoordinationJournalRepository(dsl), - new InitialGameplayLoginRedisAttemptClosure(contexts), - account, - transactions); - return new InitialGameplayLoginOwner(contexts, cleanup, account); - } - - @Bean - DirectTextWorldSelectionService authenticatedDirectTextWorldSelections( - GameplayWorldCatalog catalog, CanonicalPlayerRouteReadService routes) { - return new DirectTextWorldSelectionService(catalog, routes, Clock.systemUTC()); - } - - @Bean - DirectTextAuthenticatedLobbyOwner directTextAuthenticatedLobbyOwner( - DSLContext dsl, - DirectTextWorldSelectionService selections, - AccountClient account, - @Qualifier("transactionManager") PlatformTransactionManager transactions) { - return new DirectTextAuthenticatedLobbyOwner( - new DirectTextAuthenticatedLobbyRepository(dsl), - selections, - account, - transactions, - Clock.systemUTC()); - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfiguration.java deleted file mode 100644 index fe5841b034..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfiguration.java +++ /dev/null @@ -1,117 +0,0 @@ -package net.firedevops.firemud.gamesession.config; - -import io.lettuce.core.RedisCredentials; -import io.lettuce.core.RedisCredentialsProvider; -import io.lettuce.core.RedisURI; -import java.net.URI; -import java.time.Duration; -import java.util.Arrays; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.AcknowledgementPolicy; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding.Profile; -import net.firedevops.firemud.gamesession.service.LettuceInitialGameplayLoginConnectionProvider; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Composes the dedicated Coordination source without granting JWT trust, maintenance qualification - * or gameplay. Endpoint, credential and deployment custody must be independently delivered. - */ -@Configuration(proxyBeanMethods = false) -@ConditionalOnProperty( - prefix = "firemud.game-session.initial-gameplay-login.protected-sources", - name = "enabled", - havingValue = "true") -public class InitialGameplayLoginProtectedSourcesConfiguration { - @Bean(destroyMethod = "close") - LettuceInitialGameplayLoginConnectionProvider initialGameplayLoginCoordinationConnections( - @Value("${firemud.game-session.initial-gameplay-login.protected-sources.coordination.uri:}") - String configuredUri, - @Value( - "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.command-timeout-millis:0}") - int commandTimeoutMillis) { - try { - return new LettuceInitialGameplayLoginConnectionProvider( - requiredCoordinationUri(configuredUri, commandTimeoutMillis)); - } catch (RuntimeException failure) { - throw unavailable(); - } - } - - @Bean - InitialGameplayLoginRedisBinding initialGameplayLoginRedisBinding( - LettuceInitialGameplayLoginConnectionProvider connections, - @Value( - "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.protected-binding-id:}") - String protectedBindingId, - @Value( - "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.profile:}") - String profile, - @Value( - "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.required-local-aof-count:0}") - int localAof, - @Value( - "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.required-replica-aof-count:0}") - int replicaAof, - @Value( - "${firemud.game-session.initial-gameplay-login.protected-sources.coordination.acknowledgement-timeout-millis:0}") - int timeoutMillis) { - try { - return new InitialGameplayLoginRedisBinding( - protectedBindingId, - connections::openPinnedConnection, - new AcknowledgementPolicy(Profile.valueOf(profile), localAof, replicaAof, timeoutMillis)); - } catch (RuntimeException failure) { - throw unavailable(); - } - } - - static RedisURI requiredCoordinationUri(String configuredUri, int timeoutMillis) { - char[] password = null; - try { - if (configuredUri == null - || configuredUri.length() > 4096 - || timeoutMillis < 1 - || timeoutMillis > 60_000) { - throw unavailable(); - } - URI uri = URI.create(configuredUri); - String userInfo = uri.getUserInfo(); - String principal = InitialGameplayLoginRedisBinding.PRINCIPAL; - if (!"rediss".equals(uri.getScheme()) - || uri.getHost() == null - || uri.getHost().isBlank() - || uri.getPort() < 1 - || uri.getPort() > 65_535 - || !"/0".equals(uri.getRawPath()) - || uri.getRawQuery() != null - || uri.getRawFragment() != null - || userInfo == null - || !userInfo.startsWith(principal + ":") - || userInfo.length() == principal.length() + 1 - || userInfo.chars().anyMatch(Character::isISOControl)) { - throw unavailable(); - } - password = userInfo.substring(principal.length() + 1).toCharArray(); - var credentials = RedisCredentials.just(principal, password); - return RedisURI.Builder.redis(uri.getHost(), uri.getPort()) - .withSsl(true) - .withVerifyPeer(true) - .withAuthentication(RedisCredentialsProvider.from(() -> credentials)) - .withDatabase(0) - .withTimeout(Duration.ofMillis(timeoutMillis)) - .build(); - } catch (RuntimeException failure) { - // URI parsing can include the delivered credential in its message or cause. - throw unavailable(); - } finally { - if (password != null) Arrays.fill(password, '\0'); - } - } - - private static IllegalArgumentException unavailable() { - return new IllegalArgumentException("Protected Game Session initial LOGIN sources required"); - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProvider.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProvider.java deleted file mode 100644 index 2f4ef07a53..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProvider.java +++ /dev/null @@ -1,62 +0,0 @@ -package net.firedevops.firemud.gamesession.service; - -import io.lettuce.core.ClientOptions; -import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; -import io.lettuce.core.api.StatefulRedisConnection; -import io.lettuce.core.codec.ByteArrayCodec; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Owns the dedicated initial-LOGIN Coordination client, never the ambient Spring Redis client. Each - * invocation owns its returned physical connection. Reconnect cannot move a mutation's - * acknowledgement or readback onto another physical connection. - */ -public final class LettuceInitialGameplayLoginConnectionProvider implements AutoCloseable { - private final RedisClient client; - private final AtomicBoolean closed = new AtomicBoolean(); - - public LettuceInitialGameplayLoginConnectionProvider(RedisURI coordinationRedisUri) { - this.client = - Objects.requireNonNull( - RedisClient.create( - Objects.requireNonNull(coordinationRedisUri, "Explicit Coordination URI required")), - "Dedicated Coordination client required"); - try { - client.setOptions(ClientOptions.builder().autoReconnect(false).build()); - } catch (RuntimeException failure) { - try { - client.shutdown(); - } catch (RuntimeException shutdownFailure) { - failure.addSuppressed(shutdownFailure); - } - throw failure; - } - } - - public StatefulRedisConnection openPinnedConnection() { - if (closed.get()) throw unavailable(); - StatefulRedisConnection connection = client.connect(ByteArrayCodec.INSTANCE); - if (closed.get()) { - try { - connection.close(); - } catch (RuntimeException closeFailure) { - IllegalStateException failure = unavailable(); - failure.addSuppressed(closeFailure); - throw failure; - } - throw unavailable(); - } - return connection; - } - - @Override - public void close() { - if (closed.compareAndSet(false, true)) client.shutdown(); - } - - private static IllegalStateException unavailable() { - return new IllegalStateException("Initial LOGIN Coordination client is closed"); - } -} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java deleted file mode 100644 index f283aa5602..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java +++ /dev/null @@ -1,183 +0,0 @@ -package net.firedevops.firemud.gamesession.config; - -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.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; -import java.time.Duration; -import net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier; -import net.firedevops.firemud.common.security.AccountPublicJwksCache; -import net.firedevops.firemud.gamesession.service.GameSessionJwtReadinessProbeOwnerClient; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCoordinationQualification; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; -import net.firedevops.firemud.gamesession.service.InitialGameplayLoginRedisBinding; -import net.firedevops.firemud.gamesession.service.LettuceInitialGameplayLoginConnectionProvider; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -/** Dedicated Redis composition proof with a controlled client; no live source is contacted. */ -class InitialGameplayLoginProtectedSourcesConfigurationTest { - private static final String PREFIX = - "firemud.game-session.initial-gameplay-login.protected-sources."; - private static final String COORDINATION_URI = - "rediss://gamesession_coord_app:test-only-password@coordination.example.invalid:6380/0"; - private final InitialGameplayLoginProtectedSourcesConfiguration configuration = - new InitialGameplayLoginProtectedSourcesConfiguration(); - - @Test - void sourcesAreDisabledByDefaultAndWhenExplicitlyDisabled() { - for (String enabled : new String[] {"", PREFIX + "enabled=false"}) { - var runner = - new ApplicationContextRunner() - .withUserConfiguration(InitialGameplayLoginProtectedSourcesConfiguration.class); - if (!enabled.isEmpty()) runner = runner.withPropertyValues(enabled); - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); - assertThat(context).doesNotHaveBean(InitialGameplayLoginRedisBinding.class); - assertThat(context) - .doesNotHaveBean(LettuceInitialGameplayLoginConnectionProvider.class); - }); - } - } - - @Test - void enablingWithoutDeliveredCoordinationInputsFailsComposition() { - new ApplicationContextRunner() - .withUserConfiguration(InitialGameplayLoginProtectedSourcesConfiguration.class) - .withPropertyValues(PREFIX + "enabled=true") - .run(context -> assertThat(context).hasFailed()); - } - - @Test - void dedicatedUriRequiresExactTlsPrincipalDatabaseAndFiniteDeadline() { - RedisURI uri = - InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( - COORDINATION_URI, 875); - - assertThat(uri.getHost()).isEqualTo("coordination.example.invalid"); - assertThat(uri.getPort()).isEqualTo(6380); - assertThat(uri.isSsl()).isTrue(); - assertThat(uri.isVerifyPeer()).isTrue(); - assertThat(uri.getDatabase()).isZero(); - assertThat(uri.getTimeout()).isEqualTo(Duration.ofMillis(875)); - var credentials = - uri.getCredentialsProvider().resolveCredentials().block(Duration.ofSeconds(1)); - assertThat(credentials).isNotNull(); - assertThat(credentials.getUsername()).isEqualTo(InitialGameplayLoginRedisBinding.PRINCIPAL); - assertThat(credentials.getPassword()).containsExactly("test-only-password".toCharArray()); - } - - @ParameterizedTest - @ValueSource( - strings = { - "", - "redis://gamesession_coord_app:secret@coordination.example.invalid:6380/0", - "rediss://default:secret@coordination.example.invalid:6380/0", - "rediss://account_coord_app:secret@coordination.example.invalid:6380/0", - "rediss://gamesession_coord_app:@coordination.example.invalid:6380/0", - "rediss://gamesession_coord_app:secret@coordination.example.invalid/0", - "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380", - "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380/1", - "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380/0?verifyPeer=false", - "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380/0#alternate", - "rediss://gamesession_coord_app:secret@coordination.example.invalid:99999/0", - "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380/0 bad" - }) - void rejectsAmbientPlaintextChangedOrAmbiguousCoordinationSources(String uri) { - assertThatThrownBy( - () -> - InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri(uri, 875)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Protected Game Session initial LOGIN sources required") - .hasNoCause(); - } - - @ParameterizedTest - @ValueSource(ints = {-1, 0, 60_001}) - void rejectsUnboundedCommandDeadlines(int timeoutMillis) { - assertThatThrownBy( - () -> - InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( - COORDINATION_URI, timeoutMillis)) - .isInstanceOf(IllegalArgumentException.class) - .hasNoCause(); - } - - @Test - void sourceBindingRequiresExplicitProfileIdentityAndAcknowledgements() { - var connections = mock(LettuceInitialGameplayLoginConnectionProvider.class); - assertThatThrownBy( - () -> - configuration.initialGameplayLoginRedisBinding( - connections, "", "REPLICATED", 1, 1, 875)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - configuration.initialGameplayLoginRedisBinding( - connections, "delivered-binding", "", 1, 1, 875)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - configuration.initialGameplayLoginRedisBinding( - connections, "delivered-binding", "REPLICATED", 1, 0, 875)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - configuration.initialGameplayLoginRedisBinding( - connections, "delivered-binding", "SINGLE_NODE_NO_FAILOVER", 1, 1, 875)) - .isInstanceOf(IllegalArgumentException.class); - verifyNoInteractions(connections); - } - - @Test - void concreteRedisSourceDoesNotSupplyVerifierMaintenanceAuthorityOrLogin() { - var client = mock(RedisClient.class); - try (var factory = mockStatic(RedisClient.class)) { - factory.when(() -> RedisClient.create(any(RedisURI.class))).thenReturn(client); - new ApplicationContextRunner() - .withUserConfiguration( - InitialGameplayLoginProtectedSourcesConfiguration.class, - AuthenticatedGameplayRuntimeConfiguration.class) - .withPropertyValues(completeProperties()) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(GameSessionJwtReadinessProbeOwnerClient.class); - assertThat(context).doesNotHaveBean(AccountPublicJwksCache.class); - assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); - assertThat(context).hasSingleBean(InitialGameplayLoginRedisBinding.class); - assertThat(context) - .doesNotHaveBean(InitialGameplayLoginCoordinationQualification.class); - assertThat(context).doesNotHaveBean(InitialGameplayLoginOwner.class); - var binding = context.getBean(InitialGameplayLoginRedisBinding.class); - assertThat(binding.protectedBindingId()).isEqualTo("delivered-binding"); - assertThat(binding.acknowledgementPolicy().requiredReplicaAofCount()).isEqualTo(1); - }); - verify(client, times(1)).shutdown(); - } - } - - private static String[] completeProperties() { - return new String[] { - PREFIX + "enabled=true", - PREFIX + "coordination.uri=" + COORDINATION_URI, - PREFIX + "coordination.command-timeout-millis=875", - PREFIX + "coordination.protected-binding-id=delivered-binding", - PREFIX + "coordination.profile=REPLICATED", - PREFIX + "coordination.required-local-aof-count=1", - PREFIX + "coordination.required-replica-aof-count=1", - PREFIX + "coordination.acknowledgement-timeout-millis=875" - }; - } -} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java deleted file mode 100644 index 52febd0892..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java +++ /dev/null @@ -1,130 +0,0 @@ -package net.firedevops.firemud.gamesession.service; - -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.doThrow; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.lettuce.core.ClientOptions; -import io.lettuce.core.RedisClient; -import io.lettuce.core.RedisURI; -import io.lettuce.core.api.StatefulRedisConnection; -import io.lettuce.core.codec.ByteArrayCodec; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; - -class LettuceInitialGameplayLoginConnectionProviderTest { - @Test - void disablesReconnectBeforeOpeningDedicatedBinaryConnectionAndOwnsClientLifecycle() { - RedisClient client = mock(RedisClient.class); - StatefulRedisConnection connection = connection(); - RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); - when(client.connect(ByteArrayCodec.INSTANCE)).thenReturn(connection); - try (var factory = mockStatic(RedisClient.class)) { - factory.when(() -> RedisClient.create(uri)).thenReturn(client); - var provider = new LettuceInitialGameplayLoginConnectionProvider(uri); - - assertThat(provider.openPinnedConnection()).isSameAs(connection); - - var options = ArgumentCaptor.forClass(ClientOptions.class); - var order = inOrder(client); - order.verify(client).setOptions(options.capture()); - order.verify(client).connect(ByteArrayCodec.INSTANCE); - assertThat(options.getValue().isAutoReconnect()).isFalse(); - - provider.close(); - provider.close(); - verify(client, times(1)).shutdown(); - assertThatThrownBy(provider::openPinnedConnection) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("closed"); - verify(client, times(1)).connect(ByteArrayCodec.INSTANCE); - factory.verify(() -> RedisClient.create(uri), times(1)); - } - } - - @Test - void shutsDownClientIfReconnectConfigurationCannotBeApplied() { - RedisClient client = mock(RedisClient.class); - var failure = new IllegalStateException("options rejected"); - doThrow(failure).when(client).setOptions(any(ClientOptions.class)); - RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); - - try (var factory = mockStatic(RedisClient.class)) { - factory.when(() -> RedisClient.create(uri)).thenReturn(client); - assertThatThrownBy(() -> new LettuceInitialGameplayLoginConnectionProvider(uri)) - .isSameAs(failure); - verify(client).shutdown(); - } - } - - @Test - void preservesConfigurationFailureIfClientShutdownAlsoFails() { - RedisClient client = mock(RedisClient.class); - var failure = new IllegalStateException("options rejected"); - var shutdownFailure = new IllegalStateException("shutdown rejected"); - doThrow(failure).when(client).setOptions(any(ClientOptions.class)); - doThrow(shutdownFailure).when(client).shutdown(); - RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); - - try (var factory = mockStatic(RedisClient.class)) { - factory.when(() -> RedisClient.create(uri)).thenReturn(client); - assertThatThrownBy(() -> new LettuceInitialGameplayLoginConnectionProvider(uri)) - .isSameAs(failure) - .hasSuppressedException(shutdownFailure); - } - } - - @Test - void disposesConnectionThatFinishesAfterConcurrentProviderClose() throws Exception { - RedisClient client = mock(RedisClient.class); - StatefulRedisConnection connection = connection(); - RedisURI uri = RedisURI.Builder.redis("coordination.example.invalid").build(); - var connectStarted = new CountDownLatch(1); - var finishConnect = new CountDownLatch(1); - when(client.connect(ByteArrayCodec.INSTANCE)) - .thenAnswer( - ignored -> { - connectStarted.countDown(); - if (!finishConnect.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("test connection was not released"); - } - return connection; - }); - var executor = Executors.newSingleThreadExecutor(); - try (var factory = mockStatic(RedisClient.class)) { - factory.when(() -> RedisClient.create(uri)).thenReturn(client); - var provider = new LettuceInitialGameplayLoginConnectionProvider(uri); - var opening = executor.submit(provider::openPinnedConnection); - - assertThat(connectStarted.await(5, TimeUnit.SECONDS)).isTrue(); - provider.close(); - finishConnect.countDown(); - - assertThatThrownBy(() -> opening.get(5, TimeUnit.SECONDS)) - .isInstanceOf(ExecutionException.class) - .hasCauseInstanceOf(IllegalStateException.class); - verify(connection).close(); - provider.close(); - verify(client, times(1)).shutdown(); - } finally { - finishConnect.countDown(); - executor.shutdownNow(); - } - } - - @SuppressWarnings("unchecked") - private static StatefulRedisConnection connection() { - return mock(StatefulRedisConnection.class); - } -} From c2dfb1a8040b4f9216f319dfe146aff687f40742 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 8 Nov 2026 20:04:13 +1300 Subject: [PATCH 05/20] Prove authenticated LOGIN refuses absent source owner --- ...nticatedDirectTextCommandReceiverTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index 8bdbdd67da..8361d684f4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -28,6 +28,25 @@ /** Wire-selector routing with controlled owners, not source qualification or admission proof. */ class AuthenticatedDirectTextCommandReceiverTest { + @Test + void authenticatedLoginWithoutOwnerRefusesBeforeDispatch() { + var fixture = fixture(); + var command = + new TextCommand( + TextCommandType.LOGIN, + List.of("player@example.test", "transient-secret"), + "LOGIN player@example.test transient-secret"); + assertThat(command.credentialsPayload()).isPresent(); + + var result = fixture.receiver.receive(fixture.socket, command); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + verifyNoInteractions(fixture.connection, fixture.lobby, fixture.selections); + } + @Test void joinUsesOneFriendlyWorldSelectorButDispatchesOnlyTheRetainedScope() { var fixture = fixture(); From 6fb7f320c77a8c2a1eb1b23f89e4b459ee874705 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 07:16:17 +1300 Subject: [PATCH 06/20] Preserve bounded LOGIN decisions and exact Gateway routing --- .../environment-and-secrets-catalog.md | 2 +- .../environment-and-secrets-overview.md | 2 +- .../system-architecture-deployment-runbook.md | 2 +- .../system-architecture-security.md | 2 + .../player-access-and-session.md | 2 + ...uthenticatedDirectTextCommandReceiver.java | 13 +++ .../AuthenticatedDirectTextSessions.java | 16 +++- .../AuthenticatedDirectTextSessionsTest.java | 81 +++++++++++++++++ .../reconcile/HostedIdentityReconciler.java | 2 +- .../GameplayWebSocketBridgeHandler.java | 2 +- .../GameplayWebSocketBridgeHandlerTest.java | 88 +++++++++++++++++++ 11 files changed, 206 insertions(+), 6 deletions(-) diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index e927cc622c..cdedc77143 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -106,7 +106,7 @@ Before the [initial-context adapter](../system-architecture-redis-usage-and-prof ## TLS & Certificates -Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Ordinary Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; authenticated TCP gameplay receiving requires the [dedicated workload-mTLS hop](../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving); see [Security Architecture](../system-architecture-security.md#cross-service-trust). The canonical target provisions certificates through **cert-manager** and mounts distinct per-workload leaf certificate/private-key Secrets so every service has a concrete private identity. Hosted Helm for `pr-preview` and `dev-demo-cluster` defines eight distinct gRPC workload leaves: five publication workloads plus Account, Game Session, and Social Groups. The shared `firemud-grpc-tls` Secret supplies the common CA trust bundle and remains the leaf source for three other hosted gRPC workloads. A ninth workload identity is the independent client-only `firemud-grpc-spring-cloud-gateway` leaf for authenticated gameplay. Its dedicated gameplay-client TLS paths and mounts leave the existing Gateway management-server binding and Gateway-internal WebSocket server leaf unchanged. Static render and hosted-controller contract checks cover the eight distinct bindings and readiness evidence; live issuance and served-identity convergence remain unproved. Explicit local-development and throwaway-test profiles may use plaintext internal transport, including the documented `ws://` Proxy-to-Gateway bridge, and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. Hosted `pr-preview` remains non-player-facing and does not provide production-promotion evidence; the canonical non-local target remains distinct per-workload mTLS. These certificates secure: +Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Ordinary Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; authenticated TCP gameplay receiving requires the [dedicated workload-mTLS hop](../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving); see [Security Architecture](../system-architecture-security.md#cross-service-trust). The canonical target provisions certificates through **cert-manager** and mounts distinct per-workload leaf certificate/private-key Secrets so every service has a concrete private identity. Hosted Helm for `pr-preview` and `dev-demo-cluster` defines eight distinct gRPC workload leaves: five publication workloads plus Account, Game Session, and Social Groups. The shared `firemud-grpc-tls` Secret supplies the common CA trust bundle and remains the leaf source for three other hosted gRPC workloads. A ninth workload identity is the independent client-only `firemud-grpc-spring-cloud-gateway` leaf for authenticated gameplay. Its dedicated gameplay-client TLS paths and mounts leave the existing Gateway management-server binding and Gateway-internal WebSocket server leaf unchanged. Static render and hosted-controller contract checks cover the eight serving-workload bindings, the client-only Gateway binding, and readiness evidence; live issuance and served-identity convergence remain unproved. Explicit local-development and throwaway-test profiles may use plaintext internal transport, including the documented `ws://` Proxy-to-Gateway bridge, and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. Hosted `pr-preview` remains non-player-facing and does not provide production-promotion evidence; the canonical non-local target remains distinct per-workload mTLS. These certificates secure: - All mTLS-protected gRPC calls between services - Any internal WebSocket bridges that require mTLS (for example, the TCP Proxy Service connecting to Spring Cloud Gateway over `wss://`) diff --git a/design/architecture/infrastructure/environment-and-secrets-overview.md b/design/architecture/infrastructure/environment-and-secrets-overview.md index fe09de7dab..19d6ade592 100644 --- a/design/architecture/infrastructure/environment-and-secrets-overview.md +++ b/design/architecture/infrastructure/environment-and-secrets-overview.md @@ -446,7 +446,7 @@ The catalog document groups these variables by subsystem (PostgreSQL, Redis, TLS ## Certificate Management and Watchers -Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Ordinary Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; authenticated TCP LOGIN/lobby/PLAY receiving instead uses the dedicated workload-mTLS WebSocket boundary; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, Game Session, and Social Groups. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all eight namespace-scoped workload Secrets and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). The separately issued ninth workload leaf, `firemud-grpc-spring-cloud-gateway`, is client-only for authenticated TCP gameplay receiving. Its dedicated `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_*_PATH` binding leaves Gateway management-server `FIREMUD_GRPC_*` paths and its independent TCP-Proxy-facing WebSocket server leaf unchanged. Other gRPC workloads continue to use the legacy shared leaf. Each of the eight distinct workload Pods projects only `tls.crt` and `tls.key` from its own Secret for its private identity, and only the public `ca.crt` key from `firemud-grpc-tls` for peer trust. The shared CA bundle must validate each of the eight distinct workload leaves as well as the shared leaf, so every distinct workload can verify either leaf generation during the intended mixed bootstrap. Hosted rendering remains non-player-facing/non-promotion evidence, and live issuance and consumer convergence remain unproved. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: +Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Ordinary Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; authenticated TCP LOGIN/lobby/PLAY receiving instead uses the dedicated workload-mTLS WebSocket boundary; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, Game Session, and Social Groups. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all eight namespace-scoped serving-workload Secrets, the client-only `firemud-grpc-spring-cloud-gateway` Secret, and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). The separately issued ninth workload leaf, `firemud-grpc-spring-cloud-gateway`, is client-only for authenticated TCP gameplay receiving. Its dedicated `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_*_PATH` binding leaves Gateway management-server `FIREMUD_GRPC_*` paths and its independent TCP-Proxy-facing WebSocket server leaf unchanged. Other gRPC workloads continue to use the legacy shared leaf. Each of the eight distinct serving-workload Pods projects only `tls.crt` and `tls.key` from its own Secret for its private identity, and only the public `ca.crt` key from `firemud-grpc-tls` for peer trust. The shared CA bundle must validate all nine distinct workload leaves as well as the shared leaf, so every distinct workload can verify either leaf generation during the intended mixed bootstrap. Hosted rendering remains non-player-facing/non-promotion evidence, and live issuance and consumer convergence remain unproved. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: - All mTLS-protected gRPC calls between services - Any internal WebSocket bridges that require mTLS (for example, the TCP Proxy Service connecting to Spring Cloud Gateway over `wss://`) diff --git a/design/architecture/system-architecture-deployment-runbook.md b/design/architecture/system-architecture-deployment-runbook.md index 9e0657df5c..9c9fbd1236 100644 --- a/design/architecture/system-architecture-deployment-runbook.md +++ b/design/architecture/system-architecture-deployment-runbook.md @@ -38,7 +38,7 @@ Before the first player-facing deployment into `hobby-self-hosted`, `staging`, o 1. Provision the target namespace and registry pull credentials used by workloads. 2. Provision per-environment PostgreSQL credentials (`postgres-credentials`) and, when rotation Jobs are used, `postgres-admin-credentials`. 3. Select and record the custody state before applying workloads. The checked-in player-facing Kustomize mode is legacy Secret-backed signing plus public Secret JWKS wiring (`jwt-signing-keys` Secret and `jwt-jwks` Secret); it may appear in pre-apply diagnostics but is non-authorizing and is not an accepted player-facing custody state. Hosted preview Helm remains a separate diagnostic ConfigMap-backed path. For `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK`, establish trusted pre-apply evidence for the pre-created interim `jwt-signing-keys` Secret, the separate interim Account-owned public `jwt-jwks` ConfigMap, and the materialization controller's name-scoped RBAC. Account has exclusive mounted/signing use of the private bundle; the materialization controller has only bounded, Account-authorized byte handling needed to materialize it and no competing signing authority. The [JWT and Token Contracts](./system-architecture-jwt-and-token-contracts.md#signing-key-rotation-contract-normative) define custody and operation authority; this runbook requires every private-slot `generate`, `materialize`, `resourceVersion`-CAS, and `prune` action to use a persisted Account-authorized operation, with the controller executing only that operation and unable to choose slots or mutate desired key-ring state independently. For target non-exportable signer mode, establish trusted pre-apply evidence for the approved signer reference, target Account-owned public `jwt-jwks` ConfigMap, Account publication/CAS authority, and no private-material mount or distribution. In both accepted modes, `FIREMUD_AUTH_JWKS_PATH` is mandatory for Account and every validator; only the interim mode sets `FIREMUD_AUTH_JWT_SECRET_PATH`, while target non-exportable signer mode leaves it unset. These bootstrap records prove intended bindings and custody boundaries only; post-apply live signer, public-JWKS, and validator convergence is a separate owner-produced gate. -4. Provision cert-manager issuer bindings and certificate resources required for workload gRPC mTLS, Gateway internal mTLS WebSocket listener, TCP Proxy bridge mTLS client identity, and operator-only client identities where applicable. Also provision the five distinct publication-reader workload certificates as namespace-scoped Secrets named `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`, plus the distinct Account, Game Session, and Social Groups workload Secrets `firemud-grpc-account-service`, `firemud-grpc-game-session-service`, and `firemud-grpc-social-groups-service`. Each of these eight leaf Secrets must contain non-empty `ca.crt`, `tls.crt`, and `tls.key` entries; its `ca.crt` must establish trust for that Secret's own leaf certificate. The `firemud-grpc-tls` shared bundle must contain the shared client leaf and a `ca.crt` trust bundle that validates the shared leaf and all eight distinct workload leaves. Both checked-in Kustomize and hosted Helm Pods for all eight distinct workloads project only `tls.crt` and `tls.key` from their corresponding workload Secret at `/tls` and only `ca.crt` from the shared `firemud-grpc-tls` bundle at `/grpc-trust`. Peer trust uses `/grpc-trust/ca.crt` so these workloads can verify both the retained shared leaf and the distinct workload leaves. This bootstrap requirement describes Secret contents and manifest bindings; it does not claim that issued Secrets, mounted certificates, or live workload readiness have been verified. Each workload leaf must be non-CA and use exactly the `digital signature` and `key encipherment` key usages and exactly the `server auth` and `client auth` extended key usages. For each workload, set exactly the service URI SAN `spiffe://firemud/ns//sa/` and DNS SANs ``, `.`, `..svc`, and `..svc.cluster.local`; replace `` and `` with the target namespace and that Secret's service name. In this SPIFFE URI, `` names the service workload; it is not a value derived from the Pod's Kubernetes ServiceAccount name. Keep every workload leaf and private key distinct. Use the established issuance and trust process for the environment. The [deployment-environment contract](./infrastructure/deployment-environments.md) and [ADR 0038](./decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md) own the canonical identity boundary. `dev-tools/certs/generate-dev-certs.sh --workload` documents the canonical leaf profile, while `dev-tools/hosted/shared/ensure-grpc-tls-secret.sh` shows how hosted setup validates projected cert-manager leaf files and adds their issuer CA to the shared trust bundle. These development/hosted helpers are references for certificate contents and validation; they do not replace production CA custody, issuer authorization, or the environment's approved certificate-issuance procedure. +4. Provision cert-manager issuer bindings and certificate resources required for workload gRPC mTLS, Gateway internal mTLS WebSocket listener, TCP Proxy bridge mTLS client identity, and operator-only client identities where applicable. Also provision the five distinct publication-reader workload certificates as namespace-scoped Secrets named `firemud-grpc-game-design-service`, `firemud-grpc-world-management-service`, `firemud-grpc-entity-management-service`, `firemud-grpc-game-logic-service`, and `firemud-grpc-automation-scripting-service`, plus the distinct Account, Game Session, and Social Groups workload Secrets `firemud-grpc-account-service`, `firemud-grpc-game-session-service`, and `firemud-grpc-social-groups-service`. Separately provision the ninth, client-only `firemud-grpc-spring-cloud-gateway` Secret using the profile owned by the [deployment-environment contract](./infrastructure/deployment-environments.md#kubernetes-characteristics). All nine leaf Secrets must contain non-empty `ca.crt`, `tls.crt`, and `tls.key` entries; each Secret's `ca.crt` must establish trust for its own leaf certificate. The `firemud-grpc-tls` shared bundle must contain the shared client leaf and a `ca.crt` trust bundle that validates the shared leaf and all nine distinct workload leaves. Both checked-in Kustomize and hosted Helm Pods for all eight distinct serving workloads project only `tls.crt` and `tls.key` from their corresponding workload Secret at `/tls` and only `ca.crt` from the shared `firemud-grpc-tls` bundle at `/grpc-trust`. Gateway separately projects its client-only `tls.crt` and `tls.key` at `/gameplay-client-tls` and shared `ca.crt` at `/gameplay-client-trust`, leaving its management-server and TCP-Proxy-facing server bindings unchanged. Peer trust uses `/grpc-trust/ca.crt` for the eight serving workloads and `/gameplay-client-trust/ca.crt` for the Gateway client so these workloads can verify both the retained shared leaf and the distinct workload leaves. This bootstrap requirement describes Secret contents and manifest bindings; it does not claim that issued Secrets, mounted certificates, or live workload readiness have been verified. Each serving-workload leaf must be non-CA and use exactly the `digital signature` and `key encipherment` key usages and exactly the `server auth` and `client auth` extended key usages. For each serving workload, set exactly the service URI SAN `spiffe://firemud/ns//sa/` and DNS SANs ``, `.`, `..svc`, and `..svc.cluster.local`; replace `` and `` with the target namespace and that Secret's service name. In this SPIFFE URI, `` names the service workload; it is not a value derived from the Pod's Kubernetes ServiceAccount name. Keep all nine workload leaves and private keys distinct. Use the established issuance and trust process for the environment. The [deployment-environment contract](./infrastructure/deployment-environments.md) and [ADR 0038](./decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md) own the canonical identity boundary. `dev-tools/certs/generate-dev-certs.sh --workload` documents the canonical leaf profile, while `dev-tools/hosted/shared/ensure-grpc-tls-secret.sh` shows how hosted setup validates projected cert-manager leaf files and adds their issuer CA to the shared trust bundle. These development/hosted helpers are references for certificate contents and validation; they do not replace production CA custody, issuer authorization, or the environment's approved certificate-issuance procedure. 5. Provision per-environment external integration credentials: backup/object-store, asset-store, outbound-communications, and operator-control-plane credentials as needed for that environment class. 6. Run `./dev-tools/deploy/preflight.py ` and require the common checks `PREFLIGHT-BOOTSTRAP-001`, `PREFLIGHT-SECRETS-001`, `PREFLIGHT-SECRETS-002`, `PREFLIGHT-BRIDGE-001`, `PREFLIGHT-REDIS-001`, `PREFLIGHT-EXTERNAL-001`, and `PREFLIGHT-SERVICES-001`, plus exactly one authenticated custody proof whose `proofId`, `custodyMode`, and `contractVersion` exactly match the selected mode: `PREFLIGHT-JWT-INTERIM-001` for `INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK` or `PREFLIGHT-JWT-002` for `TARGET_NON_EXPORTABLE_SIGNER`. Preserve that exact tuple in the deployment record for retry/replay. An unknown, unsupported, or not-yet-implemented state fails closed. `PREFLIGHT-JWT-001` and `PREFLIGHT-JWKS-001` may be emitted as legacy diagnostic wiring results, but they are never custody proof or player-facing readiness evidence and cannot substitute for the selected custody proof. 7. Record trusted pre-apply bootstrap secret-compliance evidence for each Tier A credential class. First deployment may use immutable initial-provisioning evidence (`lastProvisionedAt`) instead of rotation evidence, but the record must still satisfy the canonical secret-compliance schema before the environment is considered promotable or traffic-open. This evidence proves provisioning and binding only; it does not prove live signer or validator convergence. diff --git a/design/architecture/system-architecture-security.md b/design/architecture/system-architecture-security.md index 4ed55bb4f3..5e2fc249ef 100644 --- a/design/architecture/system-architecture-security.md +++ b/design/architecture/system-architecture-security.md @@ -160,6 +160,8 @@ The credential-bearing TCP LOGIN/lobby/PLAY receiver is `/ws/game/tcp` on a dedi Gateway may relay the TCP-origin address and original proxy connection UUID only from its private proof produced after the selected TCP Proxy mTLS trust policy succeeds. Header strings, public ingress, development CIDR trust and network location cannot produce that proof. Game Session validates the relay on the dedicated authenticated connector, allocates a fresh backend generation and binds it to the exact live WebSocket object. Retained UUIDs, numeric transport IDs, menus and SQL witnesses do not reconstruct that custody. +The ordinary HTTP/WebSocket connector is not a supported TCP gameplay fallback. Missing or disabled authenticated Gateway upstream or Game Session listener configuration leaves TCP gameplay unavailable; stripping the trusted TCP connection mode to reach an ordinary receiver cannot supply authenticated custody. + A genuine `InitialGameplayLoginOwner` outcome retains the identical verified private Account result on that connection. Every lobby/entitlement operation borrows that result and exact live transport together; replacement, disconnect, logout and shutdown revoke new use, drain in-flight callbacks, wipe private bytes and attempt exact-original cleanup. A new backend connection never inherits the old LOGIN result. LOGIN and JOIN success do not grant gameplay admission or bypass the canonical World/capacity/final-binding owners. Gateway selects the receiver using `firemud.gateway.gameplay.bridge.authenticated-upstream-url`, a `wss://` URL ending exactly in `/ws/game/tcp`. Gateway's dedicated `firemud.gateway.gameplay.bridge.tls.cert-chain`, `.private-key` and `.ca-cert` properties use `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH`, `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH` and `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH` as environment aliases. They never replace its management-server `FIREMUD_GRPC_*` binding. Game Session binds `firemud.gameplay.authenticated-listener.enabled` and `.port` (default `8444`); the port must differ from ordinary HTTP. SSL bundle rotation updates the Game Session connector, and the Gateway uses the existing TLS certificate watcher for new outbound connections. Protected Redis bindings, external reset/restore/promotion exclusion, committed Account issuance/currentness and canonical admission sources remain independently required. A configured URI or mounted file is not their qualification. Current receiving and proof limits belong to the [player access tracker](../project-management/implementation-tracking/player-access-and-session.md). 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 cb20eb9f39..c37414ba7d 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -456,6 +456,8 @@ The Gateway retains a process-private TCP-origin proof only after authenticating The exact live backend socket/generation owns the genuine `InitialGameplayLoginOwner.Outcome`; lobby operations borrow its identical private result inside synchronous custody callbacks. Disconnect, replacement and shutdown revoke the old generation before draining and exact-original cleanup. Reconnection cannot reconstruct LOGIN from correlation IDs or retained SQL. WORLDS/REALMS/JOIN use the existing non-admitting lobby owners. The receiver refuses PLAY rather than invoking the retired numeric subscription-entitlement path. A complete canonical final admission/binding composition is still required. +The checked-in local Compose, base and Kustomize configurations do not enable the authenticated listener/upstream pair, so their ordinary TCP gameplay path fails closed under the [receiving contract](../../architecture/system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). Hosted shared values select the authenticated path, but the genuine `InitialGameplayLoginOwner` remains unregistered here: protected hosted LOGIN returns `UNAVAILABLE`, and PLAY remains intentionally denied even after a qualified LOGIN. This preparation does not enable the required public LOGIN/PLAY/LOOK smoke, hosted deployment success or branch-image publication; the separate direct-backend diagnostic exception above does not prove this protected path. + The latest completed focused gate passes 54 Gateway and 94 Game Session cases with zero failures, errors or skips, including actual mutual-TLS WebSocket upgrade, wrong-workload/namespace refusal before HTTP origin headers, exact-result custody, overlapping replacement drain, shutdown revocation and friendly JOIN wire routing. These cases use controlled upstream Account/result sources and are not genuine end-to-end Account issuance or public LOGIN-to-PLAY proof. The first Account dispatch run preserved 144 passing cases and four failed reject-before-payload assertions. After moving canonical selector dispatch behind the existing peer guard, the exact 148-case Account suite passes with zero failures, errors or skips. The physical Tomcat connector case requires client TLS, accepts only the exact Gateway namespace/workload, denies forged headers over public HTTP and limits the dedicated listener to the gameplay path. Affected main, unit and integration sources compile. The initial nine Checkstyle scopes and three Gateway SpotBugs scopes passed, while four Game Session static findings required correction. The corrected source snapshots singleton header values and retains the canonical parsed literal address with an IPv6 regression case. The later Game Session main/unit/integration and Account static recovery scopes pass; its Markdown environment failure is retained separately from the subsequent successful formatting and Markdown checks. The earlier complete source-composition graph has separately recorded Account and Game Session main/unit static proof in the successor; that historical result does not qualify this narrower patch boundary. Base NetworkPolicy contract passes; hosted chart and deployment preflight contracts remain locally unrun because Helm and kubectl are unavailable. Protected Redis client and runtime composition is retained in the successor; deployed Redis binding, external reset/restore/promotion exclusion, signing/currentness/source custody, final admission and real preview/CI LOGIN-to-PLAY remain incomplete. No fixture, mounted URI or process-local flag qualifies those authorities. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 89128eee30..042cc3a3cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -2,6 +2,7 @@ import java.util.List; import java.util.Map; +import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; import net.firedevops.firemud.gamesession.command.text.TextCommand; @@ -88,6 +89,18 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm case LOGOUT -> success("Logged out"); default -> failure("FEATURE_UNAVAILABLE", "Command unavailable"); }; + } catch (AuthenticatedDirectTextSessions.LoginRejectedException rejected) { + return switch (rejected.code()) { + case AuthenticationErrorCodes.INVALID_CREDENTIALS -> + failure("INVALID_CREDENTIALS", "Invalid credentials"); + case AuthenticationErrorCodes.ACCOUNT_LOCKED -> + failure("ACCOUNT_LOCKED", "Account is locked"); + case AuthenticationErrorCodes.RETRY_LATER -> + failure("RETRY_LATER", "Too many failed attempts; try again later"); + case "IDEMPOTENCY_CONFLICT", "RESPONSE_RECOVERY_EXPIRED" -> + failure(rejected.code(), "Login rejected"); + default -> failure("UNAVAILABLE", "Authenticated gameplay authority unavailable"); + }; } catch (RuntimeException unavailable) { return failure("UNAVAILABLE", "Authenticated gameplay authority unavailable"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java index 0701820a6b..1f06566ea3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java @@ -135,7 +135,7 @@ public void login(InitialGameplayLoginOwner owner, String email, char[] ownedSec outcome = received; credentials = null; if (received.status() != InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING) - throw unavailable(); + throw new LoginRejectedException(received.failureCode().orElse("UNAVAILABLE")); requireLive(); } finally { java.util.Arrays.fill(ownedSecret, '\0'); @@ -257,6 +257,20 @@ private void drainPredecessor() { } } + static final class LoginRejectedException extends IllegalStateException { + private static final long serialVersionUID = 1L; + private final String code; + + private LoginRejectedException(String code) { + super("Authenticated gameplay LOGIN was rejected"); + this.code = code; + } + + String code() { + return code; + } + } + private static IllegalStateException unavailable() { return new IllegalStateException("Current authenticated TCP LOGIN custody is unavailable"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java index e86b9890d5..098c84c55d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java @@ -12,16 +12,24 @@ import java.nio.charset.StandardCharsets; import java.security.cert.X509Certificate; 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 net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.TextCommand; +import net.firedevops.firemud.gamesession.command.text.TextCommandType; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginCleanupOwner; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; +import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.springframework.beans.factory.support.StaticListableBeanFactory; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.socket.WebSocketSession; @@ -30,6 +38,79 @@ class AuthenticatedDirectTextSessionsTest { private final AuthenticatedDirectTextSessions sessions = new AuthenticatedDirectTextSessions(); + @ParameterizedTest + @CsvSource({ + "AUTH_INVALID_CREDENTIALS, INVALID_CREDENTIALS", + "AUTH_ACCOUNT_LOCKED, ACCOUNT_LOCKED", + "AUTH_RETRY_LATER, RETRY_LATER", + "IDEMPOTENCY_CONFLICT, IDEMPOTENCY_CONFLICT", + "RESPONSE_RECOVERY_EXPIRED, RESPONSE_RECOVERY_EXPIRED", + "AUTH_UNAVAILABLE, UNAVAILABLE", + "CUSTODY_LOST, UNAVAILABLE", + "LOGIN_UNAVAILABLE, UNAVAILABLE", + "DEADLINE_EXCEEDED, UNAVAILABLE", + "untrusted-owner-diagnostic, UNAVAILABLE", + ", UNAVAILABLE" + }) + void rejectedLoginPreservesOnlyBoundedDecisionsThroughTheReceiver( + String ownerCode, String publicCode) throws Exception { + var socket = socket(); + sessions.open(socket); + var outcome = mock(InitialGameplayLoginOwner.Outcome.class); + when(outcome.status()).thenReturn(InitialGameplayLoginOwner.Status.CLEANUP_ACCOUNT_NO_TOKEN); + when(outcome.failureCode()).thenReturn(Optional.ofNullable(ownerCode)); + var owner = mock(InitialGameplayLoginOwner.class); + when(owner.receive(any())).thenReturn(outcome); + var beans = new StaticListableBeanFactory(Map.of("login", owner)); + var receiver = + new AuthenticatedDirectTextCommandReceiver( + sessions, + beans.getBeanProvider(InitialGameplayLoginOwner.class), + beans.getBeanProvider(DirectTextWorldSelectionService.class), + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + + var result = + receiver.receive( + socket, + new TextCommand( + TextCommandType.LOGIN, + List.of("player@example.test", "transient-secret"), + "LOGIN player@example.test transient-secret")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo(publicCode); + assertThat(result.commandResult().errorMessage()) + .doesNotContain("transient-secret", "untrusted-owner-diagnostic"); + if ("UNAVAILABLE".equals(publicCode)) { + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + } + verify(outcome, never()).withOwnedPrivateResult(any()); + sessions.close(socket); + verify(outcome).close(); + } + + @Test + void rejectedLoginErasesCredentialsAndRetainsCleanupOwnership() throws Exception { + var socket = socket(); + sessions.open(socket); + var outcome = mock(InitialGameplayLoginOwner.Outcome.class); + when(outcome.status()).thenReturn(InitialGameplayLoginOwner.Status.CLEANUP_HELD); + when(outcome.failureCode()).thenReturn(Optional.of("AUTH_INVALID_CREDENTIALS")); + var owner = mock(InitialGameplayLoginOwner.class); + when(owner.receive(any())).thenReturn(outcome); + char[] secret = "transient-private-secret".toCharArray(); + + assertThatThrownBy(() -> sessions.require(socket).login(owner, "player@example.test", secret)) + .isInstanceOf(AuthenticatedDirectTextSessions.LoginRejectedException.class) + .hasMessage("Authenticated gameplay LOGIN was rejected"); + + assertThat(secret).containsOnly('\0'); + verify(outcome, never()).close(); + sessions.close(socket); + verify(outcome).close(); + } + @Test void exactConnectionOwnsIdenticalPrivateResultOnlyInsideBorrow() throws Exception { var socket = socket(); diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java index 056f6fbec4..e5447bfe97 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java @@ -1066,7 +1066,7 @@ private UpdateControl status( phase = HostedEnvironmentIdentityStatus.Phase.Verifying; reason = "WorkloadIdentityEvidenceIncomplete"; message = - "all five protected publication projections and the exact Account, Game Session, and Social Groups workload identities are required for readiness; readiness does not authorize publication methods"; + "all five protected publication projections and the exact Account, Game Session, Social Groups, and Gateway client workload identities are required for readiness; readiness does not authorize publication methods"; } HostedEnvironmentIdentityStatus updatedStatus = statusService.status( diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java index 2ae398fe15..59feea4dfd 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java @@ -218,7 +218,7 @@ private Mono connectWithRetry( return bridgeUpstreamSession(downstream, upstream, state); }; Mono sessionLifecycle = - "wss".equals(upstreamUri.getScheme()) && authenticatedClient != null + authenticatedClient != null && upstreamUri.equals(authenticatedClient.upstream()) ? authenticatedClient.execute(upstreamHeaders, upstreamHandler) : client.execute(upstreamUri, upstreamHeaders, upstreamHandler); return Mono.when(connected.asMono().timeout(UPSTREAM_CONNECT_TIMEOUT), sessionLifecycle) diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java index 6017efe5b7..3c18407574 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java @@ -2,7 +2,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; 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.when; @@ -11,14 +13,19 @@ import java.net.URI; import java.time.Duration; import java.time.Instant; +import java.util.Map; +import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.springcloudgateway.config.GameplayWebSocketBridgeProperties; +import net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.reactivestreams.Publisher; import org.reactivestreams.Subscription; @@ -112,6 +119,87 @@ void bridgeGeneratesTransportSessionIdWhenTrustedAdmissionProvidesNone() { .isNotEqualTo("9001"); } + @ParameterizedTest + @ValueSource(strings = {"ws", "wss"}) + void ordinaryUpstreamKeepsItsClientWhenAuthenticatedUpstreamIsConfigured(String scheme) { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + AuthenticatedGameplayWebSocketClient authenticated = + mock(AuthenticatedGameplayWebSocketClient.class); + URI ordinaryUpstream = URI.create(scheme + "://game-session-service:8080/ws/game"); + when(authenticated.upstream()) + .thenReturn(URI.create("wss://game-session-service:8444/ws/game/tcp")); + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + when(downstream.getId()).thenReturn("ordinary-downstream"); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(new HttpHeaders()); + when(downstream.send(any())).thenReturn(Mono.never()); + when(downstream.receive()).thenReturn(Flux.never()); + when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) + .thenReturn(Mono.never()); + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties(ordinaryUpstream.toString(), 1, 50L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), + GameplayWebSocketObservability.disabled(), + authenticated); + + StepVerifier.create(handler.handle(downstream)).expectSubscription().thenCancel().verify(); + + verify(client) + .execute(eq(ordinaryUpstream), any(HttpHeaders.class), any(WebSocketHandler.class)); + verify(authenticated, never()).execute(any(), any()); + } + + @Test + void verifiedTcpOriginSelectsAuthenticatedClientAndRelaysOnlyVerifiedOrigin() { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + AuthenticatedGameplayWebSocketClient authenticated = + mock(AuthenticatedGameplayWebSocketClient.class); + when(authenticated.upstream()) + .thenReturn(URI.create("wss://game-session-service:8444/ws/game/tcp")); + when(authenticated.execute(any(), any())).thenReturn(Mono.never()); + VerifiedTcpProxyOrigin origin = mock(VerifiedTcpProxyOrigin.class); + UUID connectionId = UUID.fromString("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814"); + when(origin.clientAddress()).thenReturn("203.0.113.99"); + when(origin.proxyConnectionId()).thenReturn(connectionId); + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + when(downstream.getId()).thenReturn("tcp-downstream"); + when(downstream.getAttributes()) + .thenReturn(Map.of(VerifiedTcpProxyOrigin.class.getName(), origin)); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + HttpHeaders headers = new HttpHeaders(); + headers.set("X-Client-IP", "unverified"); + headers.set("X-Proxy-Connection-Id", "unverified"); + when(handshake.getHeaders()).thenReturn(headers); + when(downstream.send(any())).thenReturn(Mono.never()); + when(downstream.receive()).thenReturn(Flux.never()); + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties( + "wss://game-session-service:8080/ws/game", 1, 50L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), + GameplayWebSocketObservability.disabled(), + authenticated); + + StepVerifier.create(handler.handle(downstream)).expectSubscription().thenCancel().verify(); + + ArgumentCaptor forwarded = ArgumentCaptor.forClass(HttpHeaders.class); + verify(authenticated).execute(forwarded.capture(), any()); + verify(client, never()) + .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + assertThat(forwarded.getValue().getFirst("X-Client-IP")).isEqualTo("203.0.113.99"); + assertThat(forwarded.getValue().getFirst("X-Proxy-Connection-Id")) + .isEqualTo(connectionId.toString()); + assertThat(forwarded.getValue().getFirst("X-Firemud-Connection-Mode")) + .isEqualTo("trusted_tcp_proxy"); + } + @Test void actualLocalShutdownClosesEstablishedBridgeWithPlannedDrain() { SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); From ed97dcd9b0b2794e4f015cad8bb62c21b92e6495 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 07:44:36 +1300 Subject: [PATCH 07/20] Isolate authenticated response locale from retained context --- k8s/hosted-identity-controller/README.md | 4 +- .../GameSessionWebSocketHandler.java | 5 +- .../GameSessionWebSocketHandlerTest.java | 70 ++++++++++++++++++- 3 files changed, 73 insertions(+), 6 deletions(-) diff --git a/k8s/hosted-identity-controller/README.md b/k8s/hosted-identity-controller/README.md index 66eb538dae..77cef3e458 100644 --- a/k8s/hosted-identity-controller/README.md +++ b/k8s/hosted-identity-controller/README.md @@ -18,9 +18,9 @@ There is no user-supplied hostname, Secret, Certificate, issuer, port, key, roll The trusted preview workflow derives an explicit mode from the validated runtime artifact: a `ClusterIP` `tcp-proxy-service` selects `private`, and a `NodePort` selects `public`. The runtime Namespace must carry the matching `firemud.dev/preview-exposure-mode` label; an absent, unknown, or changed mode is invalid. The controller never infers private mode from a failed public probe. -In `private` mode, the runtime TCP Proxy Service remains `ClusterIP`, has no NodePort, and has no canonical Telnet-port annotation. `telnetPort=0` is an internal profile sentinel only. After all five labeled, key-complete publication projections, the distinct Account, Game Session, and Social Groups serving-workload projections, the Gateway client-only projection, and the required Gateway/TCP Proxy rollouts converge, `Ready=True` requires served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes. The private proof therefore proves the internal bridge without claiming a public TCP endpoint, Telnet smoke, or gameplay acceptance. +In `private` mode, the runtime TCP Proxy Service remains `ClusterIP`, has no NodePort, and has no canonical Telnet-port annotation. `telnetPort=0` is an internal profile sentinel only. After all [fourteen labeled, key-complete runtime projections](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle) and the required Gateway/TCP Proxy rollouts converge, `Ready=True` requires served HTTPS, the private Gateway-to-TCP Proxy mutual-TLS bridge, and gRPC probes. The private proof therefore proves the internal bridge without claiming a public TCP endpoint, Telnet smoke, or gameplay acceptance. -In `public` mode, the trusted allocator supplies the reserved NodePort and the runtime Namespace carries its Telnet-port annotation. `Ready=True` retains the public Telnet probe in addition to HTTPS, the Gateway-to-TCP Proxy bridge, gRPC, all five publication projections, the distinct Account, Game Session, and Social Groups serving-workload projections, the Gateway client-only projection, and rollout convergence; the trusted workflow then requires the public `LOGIN -> PLAY -> LOOK` smoke. A public probe or smoke failure is terminal for public mode and cannot fall back to private mode. This bounded private mode does not replace the public two-path target in [ADR 0178](../../design/architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md). +In `public` mode, the trusted allocator supplies the reserved NodePort and the runtime Namespace carries its Telnet-port annotation. `Ready=True` retains the public Telnet probe in addition to HTTPS, the Gateway-to-TCP Proxy bridge, gRPC, all [fourteen labeled, key-complete runtime projections](../../design/architecture/infrastructure/deployment-environments.md#hosted-identity-lifecycle), and rollout convergence; the trusted workflow then requires the public `LOGIN -> PLAY -> LOOK` smoke. A public probe or smoke failure is terminal for public mode and cannot fall back to private mode. This bounded private mode does not replace the public two-path target in [ADR 0178](../../design/architecture/decisions/adr-0178-disposable-transport-complete-pr-preview-proof.md). ## Resource and status contract diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index 4eb61bf156..8ca6b02c75 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -215,11 +215,12 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) try { sendProtocolMessage( session, - formatResponse( + outputProjector.projectCommandResponse( + session, command, interpretation, - session, interpretation.outputs(), + resolveLocaleTag(session), settingsResolver.presentation(null), null)); } finally { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index 2b1864926a..0e462a15d5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -146,6 +146,74 @@ void authenticatedLogoutClosesCustodyAfterResponseDelivery() throws Exception { Mockito.verifyNoInteractions(interpreter); } + @ParameterizedTest + @CsvSource({"8, fr-CA", "8,", ", fr-CA", ","}) + void authenticatedResponseUsesOnlyHandshakeLocaleWithoutReadingRetainedContext( + String tenantId, String localeTag) throws Exception { + var authenticatedSessions = Mockito.mock(AuthenticatedDirectTextSessions.class); + var receiver = Mockito.mock(AuthenticatedDirectTextCommandReceiver.class); + handler.authenticatedDirectTextReceiving(authenticatedSessions, receiver); + var attributes = new java.util.HashMap(); + attributes.put(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, "41"); + attributes.put( + AuthenticatedDirectTextIngress.ATTRIBUTE, + Mockito.mock(AuthenticatedDirectTextIngress.class)); + if (tenantId != null) + attributes.put(GameSessionWebSocketHandshakeInterceptor.TENANT_ID_ATTR, tenantId); + if (localeTag != null) + attributes.put(GameSessionWebSocketHandshakeInterceptor.LOCALE_ATTR, localeTag); + when(session.getAttributes()).thenReturn(attributes); + var unavailable = new SessionContextUnavailableException("retained context unavailable", null); + when(sessionAuthenticationService.resolveUnverifiedSessionContext(Mockito.anyString())) + .thenThrow(unavailable); + when(sessionAuthenticationService.resolveUnverifiedSessionContext( + Mockito.anyLong(), Mockito.anyLong())) + .thenThrow(unavailable); + TextCommand command = + new TextCommand( + TextCommandType.LOGIN, + List.of("player@example.test", "transient-secret"), + "LOGIN player@example.test transient-secret"); + var interpretation = + new TextCommandInterpretationResult( + CommandEnqueueResult.failure("INVALID_CREDENTIALS", "Invalid credentials"), + List.of(PlayerOutput.error("INVALID_CREDENTIALS", "Invalid credentials"))); + var presentation = new PresentationProperties(); + when(settingsResolver.presentation(null)).thenReturn(presentation); + when(parser.parse(command.rawLine())).thenReturn(command); + when(receiver.receive(session, command)).thenReturn(interpretation); + when(outputProjector.projectCommandResponse( + session, + command, + interpretation, + interpretation.outputs(), + localeTag, + presentation, + null)) + .thenReturn("ERROR INVALID_CREDENTIALS Invalid credentials"); + + handler.handleMessage(session, new TextMessage(command.rawLine())); + + verify(receiver).receive(session, command); + verify(outputProjector) + .projectCommandResponse( + session, + command, + interpretation, + interpretation.outputs(), + localeTag, + presentation, + null); + verify(session) + .sendMessage( + argThat( + message -> + "ERROR INVALID_CREDENTIALS Invalid credentials".equals(message.getPayload()))); + verify(session, never()).close(any()); + Mockito.verifyNoInteractions( + interpreter, sessionAuthenticationService, sessionContextService, authenticatedSessions); + } + @Test void authenticatedLogoutClosesCustodyWhenResponseSendFails() throws Exception { var authenticatedSessions = authenticatedLogoutReceiving(); @@ -176,8 +244,6 @@ private AuthenticatedDirectTextSessions authenticatedLogoutReceiving() { var interpretation = new TextCommandInterpretationResult(CommandEnqueueResult.success()); when(parser.parse("LOGOUT")).thenReturn(command); when(receiver.receive(session, command)).thenReturn(interpretation); - when(sessionAuthenticationService.resolveUnverifiedSessionContext("41")) - .thenReturn(Optional.empty()); when(activeTransportSessionRegistry.find(41L)).thenReturn(Optional.empty()); when(outputProjector.projectCommandResponse( eq(session), From df011656f07915fb19a97660d9d97f88a73c00fa Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 08:12:57 +1300 Subject: [PATCH 08/20] Preserve authenticated gameplay close and reactive failure semantics --- .../environment-and-secrets-overview.md | 2 +- ...uthenticatedDirectTextCommandReceiver.java | 2 +- .../AuthenticatedDirectTextSessions.java | 17 +-- .../GameSessionWebSocketHandler.java | 8 +- ...nticatedDirectTextCommandReceiverTest.java | 23 ++-- .../AuthenticatedDirectTextSessionsTest.java | 43 ++++++-- .../GameSessionWebSocketHandlerTest.java | 25 ++++- .../AuthenticatedGameplayWebSocketClient.java | 13 ++- ...henticatedGameplayWebSocketClientTest.java | 102 +++++++++++++++++- 9 files changed, 200 insertions(+), 35 deletions(-) diff --git a/design/architecture/infrastructure/environment-and-secrets-overview.md b/design/architecture/infrastructure/environment-and-secrets-overview.md index 19d6ade592..b72f112c03 100644 --- a/design/architecture/infrastructure/environment-and-secrets-overview.md +++ b/design/architecture/infrastructure/environment-and-secrets-overview.md @@ -446,7 +446,7 @@ The catalog document groups these variables by subsystem (PostgreSQL, Redis, TLS ## Certificate Management and Watchers -Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Ordinary Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; authenticated TCP LOGIN/lobby/PLAY receiving instead uses the dedicated workload-mTLS WebSocket boundary; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, Game Session, and Social Groups. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all eight namespace-scoped serving-workload Secrets, the client-only `firemud-grpc-spring-cloud-gateway` Secret, and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). The separately issued ninth workload leaf, `firemud-grpc-spring-cloud-gateway`, is client-only for authenticated TCP gameplay receiving. Its dedicated `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_*_PATH` binding leaves Gateway management-server `FIREMUD_GRPC_*` paths and its independent TCP-Proxy-facing WebSocket server leaf unchanged. Other gRPC workloads continue to use the legacy shared leaf. Each of the eight distinct serving-workload Pods projects only `tls.crt` and `tls.key` from its own Secret for its private identity, and only the public `ca.crt` key from `firemud-grpc-tls` for peer trust. The shared CA bundle must validate all nine distinct workload leaves as well as the shared leaf, so every distinct workload can verify either leaf generation during the intended mixed bootstrap. Hosted rendering remains non-player-facing/non-promotion evidence, and live issuance and consumer convergence remain unproved. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: +Internal service-to-service **gRPC** traffic uses mutual TLS in shared and player-facing Kubernetes environments. Ordinary Gateway-to-backend HTTP/WebSocket hops remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; authenticated TCP LOGIN/lobby/PLAY receiving instead uses the dedicated workload-mTLS WebSocket boundary; see [Security Architecture](../system-architecture-security.md#cross-service-trust). Explicit local-development and throwaway-test profiles may use the documented plaintext internal transports and do not provide player-facing or promotion evidence. The bounded Spring gRPC `1.0.x` plaintext `pr-preview` migration exception documented in [gRPC TLS requirements](../system-architecture-grpc.md#tls-requirements) is reserved policy, not the current hosted configuration. In hosted `pr-preview` and `dev-demo-cluster`, trusted certificate workflows provision distinct cert-manager-issued leaves for the five publication services, Account, Game Session, and Social Groups, plus the separate client-only Gateway leaf. The checked-in `k8s/base/` Pod manifests bind and mount each workload's corresponding `firemud-grpc-` Secret; they do not issue those certificates. Live leaf issuance and consumer readiness must be proven before hosted identity activation. Staging and production operators must provision all eight namespace-scoped serving-workload Secrets, the client-only `firemud-grpc-spring-cloud-gateway` Secret, and the shared `firemud-grpc-tls` trust bundle through the environment bootstrap process in the [deployment runbook](../system-architecture-deployment-runbook.md#environment-bootstrap). The separately issued ninth workload leaf, `firemud-grpc-spring-cloud-gateway`, is client-only for authenticated TCP gameplay receiving. Its dedicated `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_*_PATH` binding leaves Gateway management-server `FIREMUD_GRPC_*` paths and its independent TCP-Proxy-facing WebSocket server leaf unchanged. Other gRPC workloads continue to use the legacy shared leaf. Each of the eight distinct serving-workload Pods projects only `tls.crt` and `tls.key` from its own Secret for its private identity, and only the public `ca.crt` key from `firemud-grpc-tls` for peer trust. The shared CA bundle must validate all nine distinct workload leaves as well as the shared leaf, so every distinct workload can verify either leaf generation during the intended mixed bootstrap. Hosted rendering remains non-player-facing/non-promotion evidence, and live issuance and consumer convergence remain unproved. The canonical identity and trust requirements are owned by the [deployment-environment contract](./deployment-environments.md) and [ADR 0038](../decisions/adr-0038-explicit-jwt-profiles-and-mtls-workload-identity.md). These certificates secure: - All mTLS-protected gRPC calls between services - Any internal WebSocket bridges that require mTLS (for example, the TCP Proxy Service connecting to Spring Cloud Gateway over `wss://`) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 042cc3a3cf..2eba1999ad 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -85,7 +85,7 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm }); // LOGIN and JOIN are not admission. Until the canonical binding owner is qualified, the // retired numeric entitlement route must never be selected by this protected receiver. - case PLAY -> failure("ENTITLEMENT_UNAVAILABLE", "Canonical gameplay admission unavailable"); + case PLAY -> failure("ADMISSION_UNAVAILABLE", "Canonical gameplay admission unavailable"); case LOGOUT -> success("Logged out"); default -> failure("FEATURE_UNAVAILABLE", "Command unavailable"); }; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java index 1f06566ea3..431875d959 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java @@ -28,6 +28,8 @@ @Component public final class AuthenticatedDirectTextSessions { private static final String ATTRIBUTE = AuthenticatedDirectTextSessions.class.getName(); + private static final CloseStatus GENERATION_CLOSED = + new CloseStatus(1012, "backend_generation_closed"); private final Map current = new ConcurrentHashMap<>(); private final Object lifecycleMonitor = new Object(); private boolean shuttingDown; @@ -41,7 +43,7 @@ public void closeAll() { shuttingDown = true; current.clear(); } - connections.forEach(Connection::close); + connections.forEach(connection -> connection.close(GENERATION_CLOSED)); } public void open(WebSocketSession socket) { @@ -62,7 +64,7 @@ public void open(WebSocketSession socket) { replacement.drainPredecessor(); if (current.get(ingress.transport().transportSessionId()) == replacement && socket.isOpen()) replacement.live.set(true); - else replacement.close(); + else replacement.close(GENERATION_CLOSED); } public Connection require(WebSocketSession socket) { @@ -75,12 +77,13 @@ public Connection require(WebSocketSession socket) { return connection; } - public void close(WebSocketSession socket) { + public void close(WebSocketSession socket, CloseStatus status) { + Objects.requireNonNull(status, "Close status required"); Object value = socket.getAttributes().get(ATTRIBUTE); if (value instanceof Connection connection && connection.socket == socket) { connection.requireExternalLifecycle(); current.remove(connection.ingress.transport().transportSessionId(), connection); - connection.close(); + connection.close(status); } } @@ -199,7 +202,7 @@ private void requireLive() { if (!isCurrent()) throw unavailable(); } - private void close() { + private void close(CloseStatus status) { requireExternalLifecycle(); if (!closing.compareAndSet(false, true)) { while (closingThread == null) Thread.onSpinWait(); @@ -232,7 +235,7 @@ private void close() { lifetime.writeLock().unlock(); } try { - if (socket.isOpen()) socket.close(new CloseStatus(1012, "backend_generation_closed")); + if (socket.isOpen()) socket.close(status); } catch (IOException ignored) { // Custody was already revoked and drained before the best-effort transport close. } @@ -251,7 +254,7 @@ private void requireExternalLifecycle() { private void drainPredecessor() { var previous = predecessor; if (previous != null) { - previous.close(); + previous.close(GENERATION_CLOSED); predecessor = null; } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index 8ca6b02c75..051caf713f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -189,7 +189,7 @@ public void afterConnectionEstablished(WebSocketSession session) { @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) { if (authenticatedDirectText(session)) { - authenticatedSessions.close(session); + authenticatedSessions.close(session, status); return; } parseNumericSessionId(resolveTransportSessionId(session)) @@ -224,7 +224,8 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) settingsResolver.presentation(null), null)); } finally { - if (command.type() == TextCommandType.LOGOUT) authenticatedSessions.close(session); + if (command.type() == TextCommandType.LOGOUT) + authenticatedSessions.close(session, new CloseStatus(1000, "logout")); } return; } @@ -299,7 +300,8 @@ protected void handleTextMessage(WebSocketSession session, TextMessage message) @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { - if (authenticatedDirectText(session)) authenticatedSessions.close(session); + if (authenticatedDirectText(session)) + authenticatedSessions.close(session, new CloseStatus(1011, "internal_error")); super.handleTransportError(session, exception); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index 8361d684f4..50ef6c4c1b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -16,9 +16,11 @@ import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandType; +import net.firedevops.firemud.gamesession.config.PresentationProperties; 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.presentation.TextPlayerOutputRenderer; import net.firedevops.firemud.gamesession.service.InitialGameplayLoginOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; @@ -80,15 +82,20 @@ void emptyOrDifferentJoinSelectionNeverCallsAccountLobbyOwner() { @Test void loginAndLobbyObservationsNeverSubstituteForCanonicalPlayAdmission() { var fixture = fixture(); - var result = - fixture.receiver.receive( - fixture.socket, - new TextCommand( - TextCommandType.PLAY, - List.of("demo", "production", "hero"), - "PLAY demo production hero")); + var command = + new TextCommand( + TextCommandType.PLAY, + List.of("demo", "production", "hero"), + "PLAY demo production hero"); + var result = fixture.receiver.receive(fixture.socket, command); assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); + assertThat(result.commandResult().errorCode()).isEqualTo("ADMISSION_UNAVAILABLE"); + var wireResponse = + new TextPlayerOutputRenderer(new PresentationProperties()) + .renderAll(command, result.commandResult(), result.outputs()); + assertThat(wireResponse) + .isEqualTo("ERROR ADMISSION_UNAVAILABLE Canonical gameplay admission unavailable") + .doesNotContain("ENTITLEMENT_UNAVAILABLE"); verifyNoInteractions(fixture.lobby, fixture.selections); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java index 098c84c55d..37bf4e8119 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java @@ -3,6 +3,7 @@ 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.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -32,6 +33,7 @@ import org.springframework.beans.factory.support.StaticListableBeanFactory; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.WebSocketSession; /** Process-local custody proof with controlled Account result/cleanup sources, not admission. */ @@ -86,7 +88,7 @@ void rejectedLoginPreservesOnlyBoundedDecisionsThroughTheReceiver( .isEqualTo("Authenticated gameplay authority unavailable"); } verify(outcome, never()).withOwnedPrivateResult(any()); - sessions.close(socket); + sessions.close(socket, CloseStatus.NORMAL); verify(outcome).close(); } @@ -107,7 +109,7 @@ void rejectedLoginErasesCredentialsAndRetainsCleanupOwnership() throws Exception assertThat(secret).containsOnly('\0'); verify(outcome, never()).close(); - sessions.close(socket); + sessions.close(socket, CloseStatus.NORMAL); verify(outcome).close(); } @@ -124,7 +126,7 @@ void exactConnectionOwnsIdenticalPrivateResultOnlyInsideBorrow() throws Exceptio connection.withLogin( (original, result) -> { assertThat(result).isSameAs(fixture.result()); - assertThatThrownBy(() -> sessions.close(socket)) + assertThatThrownBy(() -> sessions.close(socket, CloseStatus.NORMAL)) .isInstanceOf(IllegalStateException.class); assertThatThrownBy(sessions::closeAll).isInstanceOf(IllegalStateException.class); assertThat(sessions.require(socket)).isSameAs(connection); @@ -135,7 +137,7 @@ void exactConnectionOwnsIdenticalPrivateResultOnlyInsideBorrow() throws Exceptio assertThatThrownBy( () -> connection.withCurrent(fixture.original(), fixture.result(), transport -> true)) .isInstanceOf(IllegalStateException.class); - sessions.close(socket); + sessions.close(socket, CloseStatus.NORMAL); verify(fixture.cleanup()).abandonAndRetire(fixture.original()); assertThatThrownBy(fixture.result()::compactJwtBytes).isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> sessions.require(socket)).isInstanceOf(IllegalStateException.class); @@ -161,16 +163,18 @@ void disconnectRevokesBeforeDrainingAndCleansOnlyAfterBorrowReturns() throws Exc return true; })); assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); - var closer = executor.submit(() -> sessions.close(socket)); + var closer = executor.submit(() -> sessions.close(socket, CloseStatus.NORMAL)); for (int i = 0; i < 1000 && connection.isCurrent(); i++) Thread.sleep(1); assertThat(connection.isCurrent()).isFalse(); assertThat(closer.isDone()).isFalse(); verify(fixture.cleanup(), never()).abandonAndRetire(any()); + verify(socket, never()).close(any()); release.countDown(); assertThatThrownBy(() -> borrower.get(5, TimeUnit.SECONDS)) .hasCauseInstanceOf(IllegalStateException.class); closer.get(5, TimeUnit.SECONDS); verify(fixture.cleanup()).abandonAndRetire(fixture.original()); + verify(socket).close(CloseStatus.NORMAL); } finally { release.countDown(); } @@ -210,9 +214,10 @@ void replacementCannotActivateBeforeOldGenerationDrainsOrReconstructOldLogin() t var current = sessions.require(replacement); assertThatThrownBy(() -> current.withLogin((original, result) -> true)) .isInstanceOf(IllegalStateException.class); - sessions.close(socket); + verify(socket).close(new CloseStatus(1012, "backend_generation_closed")); + sessions.close(socket, CloseStatus.NORMAL); assertThat(sessions.require(replacement)).isSameAs(current); - sessions.close(replacement); + sessions.close(replacement, CloseStatus.NORMAL); verify(fixture.cleanup()).abandonAndRetire(fixture.original()); } finally { release.countDown(); @@ -313,12 +318,36 @@ void shutdownRevokesEveryGenerationBeforeDrainingAndRefusesNewConnections() thro shutdown.get(5, TimeUnit.SECONDS); verify(firstFixture.cleanup()).abandonAndRetire(firstFixture.original()); verify(secondFixture.cleanup()).abandonAndRetire(secondFixture.original()); + verify(first).close(new CloseStatus(1012, "backend_generation_closed")); + verify(second).close(new CloseStatus(1012, "backend_generation_closed")); assertThatThrownBy(() -> sessions.open(newSocket)).isInstanceOf(IllegalStateException.class); } finally { release.countDown(); } } + @ParameterizedTest + @CsvSource({"1000, logout", "1011, internal_error"}) + void callerCloseStatusIsRetainedAfterExactOriginalCleanup(int code, String reason) + throws Exception { + var socket = socket(); + sessions.open(socket); + var fixture = fixture(); + var connection = sessions.require(socket); + connection.login(fixture.owner(), "player@example.test", "secret".toCharArray()); + var status = new CloseStatus(code, reason); + + sessions.close(socket, status); + sessions.close(socket, new CloseStatus(1012, "backend_generation_closed")); + + var order = inOrder(fixture.cleanup(), socket); + order.verify(fixture.cleanup()).abandonAndRetire(fixture.original()); + order.verify(socket).close(status); + verify(socket, org.mockito.Mockito.times(1)).close(any()); + assertThat(connection.isCurrent()).isFalse(); + assertThatThrownBy(fixture.result()::compactJwtBytes).isInstanceOf(IllegalStateException.class); + } + private static WebSocketSession socket() throws Exception { return socket("42"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index 0e462a15d5..ecbbdab0dd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -142,7 +142,7 @@ void authenticatedLogoutClosesCustodyAfterResponseDelivery() throws Exception { InOrder order = Mockito.inOrder(session, authenticatedSessions); order.verify(session).sendMessage(argThat(message -> "OK LOGOUT".equals(message.getPayload()))); - order.verify(authenticatedSessions).close(session); + order.verify(authenticatedSessions).close(session, new CloseStatus(1000, "logout")); Mockito.verifyNoInteractions(interpreter); } @@ -225,10 +225,31 @@ void authenticatedLogoutClosesCustodyWhenResponseSendFails() throws Exception { InOrder order = Mockito.inOrder(session, authenticatedSessions); order.verify(session).sendMessage(argThat(message -> "OK LOGOUT".equals(message.getPayload()))); - order.verify(authenticatedSessions).close(session); + order.verify(authenticatedSessions).close(session, new CloseStatus(1000, "logout")); Mockito.verifyNoInteractions(interpreter); } + @Test + void authenticatedTransportErrorUsesInternalErrorInsteadOfRestart() throws Exception { + var authenticatedSessions = authenticatedLogoutReceiving(); + + handler.handleTransportError(session, new IOException("transport failed")); + + verify(authenticatedSessions).close(session, new CloseStatus(1011, "internal_error")); + Mockito.verifyNoInteractions(interpreter, sessionAuthenticationService); + } + + @Test + void authenticatedConnectionClosedPreservesObservedStatus() { + var authenticatedSessions = authenticatedLogoutReceiving(); + var status = new CloseStatus(1001, "idle_timeout"); + + handler.afterConnectionClosed(session, status); + + verify(authenticatedSessions).close(session, status); + Mockito.verifyNoInteractions(interpreter, sessionAuthenticationService); + } + private AuthenticatedDirectTextSessions authenticatedLogoutReceiving() { var authenticatedSessions = Mockito.mock(AuthenticatedDirectTextSessions.class); var receiver = Mockito.mock(AuthenticatedDirectTextCommandReceiver.class); diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java index 735f2c857b..238a394a66 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java @@ -111,10 +111,15 @@ private void reload() throws IOException { } public Mono execute(HttpHeaders headers, WebSocketHandler handler) { - ReactorNettyWebSocketClient current = client; - if (current == null) - throw new IllegalStateException("Authenticated gameplay client unavailable"); - return current.execute(upstream, headers, handler); + return Mono.defer( + () -> { + ReactorNettyWebSocketClient current = client; + if (current == null) { + return Mono.error( + new IllegalStateException("Authenticated gameplay client unavailable")); + } + return current.execute(upstream, headers, handler); + }); } public URI upstream() { diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java index e444d9bd1d..f83697652c 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java @@ -2,18 +2,41 @@ 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.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; import io.netty.handler.ssl.ClientAuth; import io.netty.handler.ssl.SslContextBuilder; import java.nio.file.Path; import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.runtime.RuntimeIdentity; +import net.firedevops.firemud.springcloudgateway.config.GameplayWebSocketBridgeProperties; +import net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin; import net.firedevops.firemud.test.LoopbackMtlsTestPki; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.http.HttpHeaders; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.reactive.socket.CloseStatus; +import org.springframework.web.reactive.socket.HandshakeInfo; +import org.springframework.web.reactive.socket.WebSocketMessage; +import org.springframework.web.reactive.socket.WebSocketSession; +import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; import reactor.netty.http.server.HttpServer; +import reactor.test.StepVerifier; class AuthenticatedGameplayWebSocketClientTest { @TempDir static Path directory; @@ -66,13 +89,88 @@ void localClientRequiresItsDedicatedGatewayIdentityAndClientUsage() throws Excep assertThatThrownBy(client::initialize).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> - client.execute( - new HttpHeaders(), socket -> reactor.core.publisher.Mono.empty())) + client + .execute(new HttpHeaders(), socket -> Mono.empty()) + .block(Duration.ofSeconds(5))) .isInstanceOf(IllegalStateException.class); } } } + @Test + void executionSignalsUnavailableWhenClosedBeforeOrAfterAssembly() throws Exception { + try (var client = + new AuthenticatedGameplayWebSocketClient( + pki.clientProperties(directory, pki.identity("gateway")), + "test", + "wss://localhost:8444/ws/game/tcp")) { + client.initialize(); + Mono assembled = client.execute(new HttpHeaders(), socket -> Mono.empty()); + client.close(); + + for (Mono execution : + List.of(assembled, client.execute(new HttpHeaders(), socket -> Mono.empty()))) { + StepVerifier.create(execution) + .expectErrorMatches( + error -> + error instanceof IllegalStateException + && "Authenticated gameplay client unavailable".equals(error.getMessage())) + .verify(Duration.ofSeconds(5)); + } + } + } + + @Test + void closedClientFollowsBridgeCloseAndReleasesActiveRegistration() throws Exception { + try (var client = + new AuthenticatedGameplayWebSocketClient( + pki.clientProperties(directory, pki.identity("gateway")), + "test", + "wss://localhost:8444/ws/game/tcp")) { + client.initialize(); + client.close(); + ReactorNettyWebSocketClient ordinaryClient = mock(ReactorNettyWebSocketClient.class); + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + VerifiedTcpProxyOrigin origin = mock(VerifiedTcpProxyOrigin.class); + when(origin.clientAddress()).thenReturn("203.0.113.99"); + when(origin.proxyConnectionId()) + .thenReturn(UUID.fromString("9fb38c88-2f1d-42aa-8e0b-7eb69caf8814")); + when(downstream.getAttributes()) + .thenReturn(Map.of(VerifiedTcpProxyOrigin.class.getName(), origin)); + when(downstream.getId()).thenReturn("closed-client-downstream"); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(new HttpHeaders()); + Sinks.Empty closed = Sinks.empty(); + when(downstream.send(any())).thenReturn(closed.asMono()); + when(downstream.receive()) + .thenReturn(closed.asMono().thenMany(Flux.empty())); + when(downstream.close(any(CloseStatus.class))) + .thenAnswer( + invocation -> { + closed.tryEmitEmpty(); + return Mono.empty(); + }); + GameplayWebSocketBridgeHandler bridge = + new GameplayWebSocketBridgeHandler( + ordinaryClient, + new GameplayWebSocketBridgeProperties(null, 1, 1L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), + GameplayWebSocketObservability.disabled(), + client); + + StepVerifier.withVirtualTime(() -> bridge.handle(downstream)) + .thenAwait(Duration.ofMillis(2)) + .expectComplete() + .verify(Duration.ofSeconds(5)); + + verify(downstream).close(new CloseStatus(1013, "backend_unavailable")); + assertThat(ReflectionTestUtils.getField(bridge, "activeBridges")).isEqualTo(Set.of()); + verifyNoInteractions(ordinaryClient); + } + } + private void exchange(String identity, AtomicInteger requests, boolean accepted) throws Exception { var serverIdentity = pki.identity(identity); From a9c2079602d845489547d33b391a52484eb20554 Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 9 Nov 2026 08:51:37 +1300 Subject: [PATCH 09/20] Clarify authenticated ingress diagnostics and certificate purposes --- .../contract/HostedIdentityContract.java | 7 +++ .../CertificateMaterialService.java | 2 +- .../CertificateResourceFactory.java | 6 +-- .../CertificateResourceFactoryTest.java | 15 ++++++ .../EnvironmentIdentityPlannerTest.java | 27 ++++++++++ .../GameplayWebSocketBridgeHandler.java | 6 +++ .../GameplayWebSocketBridgeHandlerTest.java | 53 +++++++++++++++++++ 7 files changed, 112 insertions(+), 4 deletions(-) diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java index 376e021e90..db256f692f 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/contract/HostedIdentityContract.java @@ -113,6 +113,13 @@ public static boolean isGrpcWorkloadIdentityRole(String role) { || isGrpcPublicationRole(role); } + /** + * Gateway's workload identity is client-only; the other workload identity roles also serve TLS. + */ + public static boolean grpcWorkloadIdentityServesTls(String role) { + return !GRPC_GATEWAY_CLIENT_ROLE.equals(role); + } + public static boolean isGrpcPublicationRole(String role) { return role != null && GRPC_PUBLICATION_WORKLOADS.stream() diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java index 1ef4294341..a3dde2ad68 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java @@ -254,7 +254,7 @@ private RoleMaterial grpcWorkloadIdentity( new RoleExpectation( plan.grpcWorkloadIdentityDnsNames(workload), List.of(plan.grpcWorkloadIdentityUriSan(workload)), - !HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE.equals(role), + HostedIdentityContract.grpcWorkloadIdentityServesTls(role), true, "kubernetes.io/tls", properties.getGrpcTrustAnchorSha256()); diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java index e1114da7e9..58696f1d4e 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactory.java @@ -152,9 +152,9 @@ GenericKubernetesResource grpcWorkloadIdentity( plan.grpcIssuer(), plan.grpcWorkloadIdentityDnsNames(workload), List.of(plan.grpcWorkloadIdentityUriSan(workload)), - HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE.equals(role) - ? List.of("digital signature", "key encipherment", "client auth") - : List.of("digital signature", "key encipherment", "server auth", "client auth"), + HostedIdentityContract.grpcWorkloadIdentityServesTls(role) + ? List.of("digital signature", "key encipherment", "server auth", "client auth") + : List.of("digital signature", "key encipherment", "client auth"), HostedIdentityProperties.INTERNAL_CERTIFICATE_DURATION, renewBefore); } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java index a6d1c5b7ae..916e83d7c1 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateResourceFactoryTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.time.Duration; import java.util.Map; @@ -14,6 +15,20 @@ import org.junit.jupiter.api.Test; class CertificateResourceFactoryTest { + @Test + void onlyGatewayWorkloadIdentityRoleIsClientOnly() { + var plan = new EnvironmentIdentityPlanner(new HostedIdentityProperties()).plan("pr-42"); + + assertFalse( + HostedIdentityContract.grpcWorkloadIdentityServesTls( + HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE)); + for (String role : plan.grpcWorkloadIdentityCertificateNames().keySet()) { + if (!HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE.equals(role)) { + assertTrue(HostedIdentityContract.grpcWorkloadIdentityServesTls(role), role); + } + } + } + @Test void ingressCertificateUsesPublicServerMaterialContract() { var plan = new EnvironmentIdentityPlanner(new HostedIdentityProperties()).plan("pr-42"); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java index 7fbb8c8180..dca31f20b2 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/EnvironmentIdentityPlannerTest.java @@ -102,6 +102,33 @@ void derivesPreviewTargetsFromOnlyTheClosedNameContract() { } } + @Test + void workloadDnsNamesUseWorkloadNamesAndKeepGatewayClientWithoutServerNames() { + List serverWorkloads = + new ArrayList<>(HostedIdentityContract.GRPC_PUBLICATION_WORKLOADS); + serverWorkloads.addAll( + List.of( + HostedIdentityContract.GRPC_ACCOUNT_WORKLOAD, + HostedIdentityContract.GRPC_GAME_SESSION_WORKLOAD, + HostedIdentityContract.GRPC_SOCIAL_GROUPS_WORKLOAD)); + + for (String environment : List.of("pr-42", "dev-demo")) { + var plan = planner.plan(environment); + assertEquals( + List.of(), + plan.grpcWorkloadIdentityDnsNames(HostedIdentityContract.GRPC_GATEWAY_WORKLOAD)); + for (String workload : serverWorkloads) { + assertEquals( + List.of( + workload, + workload + "." + plan.runtimeNamespace(), + workload + "." + plan.runtimeNamespace() + ".svc", + workload + "." + plan.runtimeNamespace() + ".svc.cluster.local"), + plan.grpcWorkloadIdentityDnsNames(workload)); + } + } + } + @Test void derivesDevDemoWithoutAcceptingUserSuppliedTopology() { var plan = planner.plan("dev-demo"); diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java index 59feea4dfd..1cacafc85d 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java @@ -65,6 +65,7 @@ public class GameplayWebSocketBridgeHandler implements WebSocketHandler, SmartLi private final GameplayWebSocketObservability gameplayWebSocketObservability; private final Set activeBridges = ConcurrentHashMap.newKeySet(); private final AtomicBoolean shuttingDown = new AtomicBoolean(); + private final AtomicBoolean missingAuthenticatedClientWarningLogged = new AtomicBoolean(); private final Object lifecycleMonitor = new Object(); private volatile Mono shutdownCompletion; @@ -120,6 +121,11 @@ public Mono handle(WebSocketSession downstream) { } if (origin != null && authenticatedClient == null) { activeBridges.remove(state); + // This configuration cannot change during the handler's lifetime; do not log every retry. + if (missingAuthenticatedClientWarningLogged.compareAndSet(false, true)) { + LOG.warn( + "Verified TCP Proxy gameplay origin rejected: no authenticated gameplay upstream client is configured; set firemud.gateway.gameplay.bridge.authenticated-upstream-url (logged once per handler)"); + } return downstream.close(BACKEND_UNAVAILABLE); } HttpHeaders upstreamHeaders = buildUpstreamHeaders(downstream); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java index 3c18407574..a54a9ae9db 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java @@ -24,12 +24,15 @@ import net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.reactivestreams.Publisher; import org.reactivestreams.Subscription; import org.slf4j.MDC; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.http.HttpHeaders; import org.springframework.web.reactive.socket.CloseStatus; import org.springframework.web.reactive.socket.HandshakeInfo; @@ -200,6 +203,56 @@ void verifiedTcpOriginSelectsAuthenticatedClientAndRelaysOnlyVerifiedOrigin() { .isEqualTo("trusted_tcp_proxy"); } + @Test + @ExtendWith(OutputCaptureExtension.class) + void missingAuthenticatedClientWarnsOnceWithoutConnectionDetailsAndKeepsFailClosed( + CapturedOutput output) { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties( + "ws://game-session-service:8080/ws/game", 1, 50L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null)); + VerifiedTcpProxyOrigin origin = mock(VerifiedTcpProxyOrigin.class); + HttpHeaders headers = new HttpHeaders(); + headers.set("X-Firemud-Connection-Mode", "trusted_tcp_proxy"); + headers.set("X-Firemud-Transport-Session-Id", "private-transport-session"); + headers.set("X-Firemud-Connect-Context", "private-connect-context"); + headers.set(HttpHeaders.AUTHORIZATION, "Bearer private-credential"); + headers.set(HttpHeaders.COOKIE, "private-cookie"); + + for (int attempt = 0; attempt < 10; attempt++) { + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + when(downstream.getId()).thenReturn("private-downstream-session"); + when(downstream.getAttributes()) + .thenReturn(Map.of(VerifiedTcpProxyOrigin.class.getName(), origin)); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(headers); + when(downstream.close(any(CloseStatus.class))).thenReturn(Mono.empty()); + + StepVerifier.create(handler.handle(downstream)).verifyComplete(); + + verify(downstream).close(new CloseStatus(1013, "backend_unavailable")); + verify(downstream, never()).send(any()); + verify(downstream, never()).receive(); + } + + verify(client, never()) + .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + assertThat(output.getAll()) + .containsOnlyOnce("no authenticated gameplay upstream client is configured") + .contains("firemud.gateway.gameplay.bridge.authenticated-upstream-url") + .doesNotContain( + "private-transport-session", + "private-connect-context", + "private-credential", + "private-cookie", + "private-downstream-session"); + } + @Test void actualLocalShutdownClosesEstablishedBridgeWithPlannedDrain() { SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); From a9531e09f855dbf0cc8c92e85680873b0ea53e61 Mon Sep 17 00:00:00 2001 From: Ben Hook Date: Mon, 9 Nov 2026 16:58:57 +1300 Subject: [PATCH 10/20] Make authenticated Gateway client immutable through constructor delegation --- .../GameplayWebSocketBridgeHandler.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java index 1cacafc85d..5ec051aa53 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java @@ -59,7 +59,7 @@ public class GameplayWebSocketBridgeHandler implements WebSocketHandler, SmartLi TRANSPORT_SESSION_HEADER); private final ReactorNettyWebSocketClient client; - private AuthenticatedGameplayWebSocketClient authenticatedClient; + private final AuthenticatedGameplayWebSocketClient authenticatedClient; private final GameplayWebSocketBridgeProperties properties; private final RuntimeIdentity runtimeIdentity; private final GameplayWebSocketObservability gameplayWebSocketObservability; @@ -69,27 +69,28 @@ public class GameplayWebSocketBridgeHandler implements WebSocketHandler, SmartLi private final Object lifecycleMonitor = new Object(); private volatile Mono shutdownCompletion; - @SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Injected client, properties, and runtime identity remain internal.") public GameplayWebSocketBridgeHandler( ReactorNettyWebSocketClient client, GameplayWebSocketBridgeProperties properties, RuntimeIdentity runtimeIdentity, GameplayWebSocketObservability gameplayWebSocketObservability) { - this.client = client; - this.properties = properties; - this.runtimeIdentity = runtimeIdentity; - this.gameplayWebSocketObservability = gameplayWebSocketObservability; + this(client, properties, runtimeIdentity, gameplayWebSocketObservability, null); } + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "Injected clients, properties, runtime identity, and observability remain internal.") public GameplayWebSocketBridgeHandler( ReactorNettyWebSocketClient client, GameplayWebSocketBridgeProperties properties, RuntimeIdentity runtimeIdentity, - GameplayWebSocketObservability observability, + GameplayWebSocketObservability gameplayWebSocketObservability, AuthenticatedGameplayWebSocketClient authenticatedClient) { - this(client, properties, runtimeIdentity, observability); + this.client = client; + this.properties = properties; + this.runtimeIdentity = runtimeIdentity; + this.gameplayWebSocketObservability = gameplayWebSocketObservability; this.authenticatedClient = authenticatedClient; } From 22b5122682dd77d0d86323d075ae7085a98fa165 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Mon, 9 Nov 2026 22:41:53 +1300 Subject: [PATCH 11/20] Explain authenticated TCP command usage without masking custody failures --- .../player-access-and-session.md | 2 +- ...uthenticatedDirectTextCommandReceiver.java | 91 ++++++++----- .../AuthenticatedDirectTextSessions.java | 11 +- ...nticatedDirectTextCommandReceiverTest.java | 123 ++++++++++++++++++ .../AuthenticatedDirectTextSessionsTest.java | 31 +++++ 5 files changed, 220 insertions(+), 38 deletions(-) diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 8d86317336..5e7e3e38c5 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -599,7 +599,7 @@ With canonical scope consumers absent from the default composition, Account conn | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java); [EmailVerificationTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/EmailVerificationTokenRepository.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [AccountFreshEnrollmentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentRepository.java); [AccountFreshEnrollmentPolicyRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPolicyRepository.java); [AccountRecentReauthenticationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java); [AccountRecentReauthenticationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationRepository.java); [V1018__account_fresh_enrollment_certification.sql](../../../services/account-service/src/main/resources/db/migration/V1018__account_fresh_enrollment_certification.sql); [V1018.1__recent_reauthentication_replay_credentials.sql](../../../services/account-service/src/main/resources/db/migration/V1018.1__recent_reauthentication_replay_credentials.sql); [V1018.2](../../../services/account-service/src/main/resources/db/migration/V1018.2__recent_reauthentication_replay_failure_budget.sql); [AccountControlUiCurrentActorVerifier.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java); [V1016__account_recent_reauthentication_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V1016__account_recent_reauthentication_evidence.sql); [V1017__account_global_control_ui_issuance_scope.sql](../../../services/account-service/src/main/resources/db/migration/V1017__account_global_control_ui_issuance_scope.sql) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java); [AccountCredentialPeerGrpcMtlsTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountCredentialPeerGrpcMtlsTest.java); [EmailVerificationHttpAuthWiringTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountFreshEnrollmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java); [AccountGlobalControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java); [AccountGlobalControlUiScopePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java); [AccountRecentReauthenticationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java); [AccountRecentReauthenticationReplayTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java); [AccountControlUiCurrentActorVerifierTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` still fails closed with `501 NOT_IMPLEMENTED` before mutation: the internal recent-reauthentication owner is purpose-bound to self-service game creation and is not wired to factor changes. General factor-change evidence and mutation composition remain open under ADR 0045. Account-global Control-UI, fresh-enrollment certification and purpose-specific recent-reauthentication preparation are present in the sources and focused proof linked here; their receiving limits are recorded below, and they do not establish production registration or custody. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal retained numeric subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; the canonical UUID billing-owner detection gap is recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving), and retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. Email confirmation atomically claims an exact unexpired token under a fresh locked Account/source transaction; equality at expiry, expired and replayed tokens refuse without Account changes. Credential RPCs require the exact same-namespace Game Session workload; only Authenticate has a separate disabled-by-default local Entity demo fixture. Unbound export/linking/Account-ID email-initiation and deferred currency adapters refuse before owner effects; supported REST and token owners remain. This containment and focused proof do not implement those deferred APIs or remove the existing recovery, audit, production and registration gaps. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [StripeWebhookIntakeService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/StripeWebhookIntakeService.java); [StripeEventInboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/StripeEventInboxRepository.java); [AccountBillingCustomerProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java); [AccountBillingCustomerRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepository.java); [AccountBillingPrerequisiteConfirmationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationService.java); [AccountPaymentInstrumentAttachmentService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java); [AccountPaymentInstrumentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepository.java); [V1026__stripe_event_inbox.sql](../../../services/account-service/src/main/resources/db/migration/V1026__stripe_event_inbox.sql); [V1027__account_billing_customer_and_instrument_owners.sql](../../../services/account-service/src/main/resources/db/migration/V1027__account_billing_customer_and_instrument_owners.sql); [V1027.1__billing_customer_first_dispatch_claim.sql](../../../services/account-service/src/main/resources/db/migration/V1027.1__billing_customer_first_dispatch_claim.sql); [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml); [StripeHostingSubscriptionProvisioner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisioner.java); [AccountHostingSubscriptionProvisioningService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningService.java); [StripeHostingSubscriptionObserver.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserver.java); [AccountHostingSubscriptionLifecycleRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java); [AccountHostingSubscriptionLifecycleService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java); [AccountSubscriptionIntentRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepository.java); [AccountHostingPlanCatalog.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalog.java) | [StripeWebhookIntakePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java); [AccountBillingPrerequisitesPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java); [AccountBillingCustomerDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java); [AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java); [AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java); [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java); [StripeHostingSubscriptionProvisionerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java); [AccountHostingSubscriptionProvisioningServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java); [AccountHostingSubscriptionDispatchPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java); [StripeHostingSubscriptionObserverTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java); [AccountHostingSubscriptionLifecycleRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java); [AccountHostingSubscriptionLifecycleServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java); [AccountSubscriptionIntentRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java); [AccountHostingPlanCatalogTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | The first cut adds an unregistered verified Stripe event inbox (V1026), durable customer intent/first-dispatch source (V1027 and V1027.1), and exact-customer saved-method confirmation source. Controlled Stripe SDK/readback and PostgreSQL proof sources do not establish live provider calls or a public route. The unregistered hosting observer, intent, lifecycle and plan sources and their focused unit proof are present. The canonical UUID schema/lifecycle and exact focused proof are present in [canonical billing receiving](#canonical-billing-and-retention-receiving); V1028 retains the original numeric archive, and active canonical ownership uses V1029 and its forward lifecycle migrations. Existing public facade convergence and positive consumers remain in [#3390](https://github.com/benhook1013/FireMUD/pull/3390); `CreateSubscription` still fails closed before mutation. The linked receiving section owns bounded intent/lifecycle/reconciliation and terminal-cancellation proof; production registration, live provider/custody qualification, remaining lifecycle outcomes, complete consumer/runtime enforcement, transfer and replacement-before-detach remain incomplete. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION`; generic provider-mutating substrate is unsupported. Creator/player commerce, donations, fees/shares, payouts, and settlement remain deferred. Webhook intake, billing-customer and saved-method registration additionally require approved finite category schedules, guarded minimization/erasure and account-deletion/backup treatment with physical proof under [the Stripe registration prerequisites](../../architecture/microservices/account-service/stripe-integration.md#billing-owner-source-registration-prerequisites). Append-only provider payloads and card-display history do not authorize indefinite production retention or retention of the Account beyond ADR 0043’s minimum billing-evidence boundary. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The current numeric runtime entitlement endpoint returns `ENTITLEMENT_UNAVAILABLE` before reading retained numeric subscription rows. Current status, preserved positive receiving obligations, and proof history are recorded in [canonical billing and retention receiving](#canonical-billing-and-retention-receiving); earlier focused storage/retry proof does not establish a live legacy-row producer. Legacy gRPC still carries unavailable outcomes in its error field, an explicit transport-classification gap. Current connect-token issuance follows the [Account API conditional bootstrap/scope validation boundary](../../architecture/microservices/account-service/api-contracts.md#rest-apis), but remains unavailable before entitlement reads, cached replay, or token issuance; older positive-issuance tests are historical. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its shared subscription-version/billing-sequence projection and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. No current gameplay or public-join eligibility is inferred from a retained numeric `past_due` row while the runtime entitlement boundary is held. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [Authenticated TCP receiver](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java); [live LOGIN custody](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java); [verified TCP origin](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/VerifiedTcpProxyOrigin.java); [dedicated mTLS Gateway client](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java); [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql); [DirectTextAuthenticatedLobbyOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java); [DirectTextAuthenticatedLobbyRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java); [V1052__direct_text_authenticated_lobby.sql](../../../services/game-session-service/src/main/resources/db/migration/V1052__direct_text_authenticated_lobby.sql) | [authenticated receiver units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java); [live custody units](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java); [Gateway mTLS client units](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java); [TCP listener admission integration](../../../services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java); [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above; [DirectTextAuthenticatedLobbyTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java); [DirectTextAuthenticatedLobbyIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Authenticated TCP receiving preserves the Gateway-verified origin over the dedicated exact-namespace mTLS hop and retains LOGIN custody on the original live backend generation. Missing protected owners or custody fail closed as `UNAVAILABLE`; malformed commands and missing local LOGIN/WORLDS/REALMS steps return bounded actionable errors. Source and controlled-component proof do not qualify a deployed authenticated LOGIN-to-PLAY chain, canonical admission, fresh-image runtime behavior, or production Redis/PKI/source custody. Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` returns `AUTH_UNAVAILABLE` before bootstrap/scope validation when canonical scope consumers are absent; when manually configured, it validates bootstrap identity and reads the connect scope before refusing cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Direct-text `CHARS` returns unavailable without legacy Entity enumeration or an accepted command event; Account HTTP/bootstrap roster discovery remains separate. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). The authenticated lobby SQL companion exists but is unregistered; live REALMS/JOIN registration and admission remain open. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. Current WebSocket reconnect suppresses retained private-context presentation while durable episode/generation eligibility is unqualified; rows remain stored, so this is neither deletion nor proof of logout invalidation. R1424 executed bounded suppression/redraw proof (57 WebSocket-handler units, 20 integration cases and ten LOOK cross-service cases), separately attributed in [Reconnect and Continuity](#reconnect-and-continuity); this is not a fresh current-head image result or proof of eligible-context replay. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisMovementEffectIdempotencyService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisMovementEffectIdempotencyServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java); [SessionContextSecretAndPresenceRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. The [local secret/presence containment](#session-secret-and-presence-containment) prevents new raw delegation-JWT persistence and projects legacy values without rehydration; physical retained-value cleanup remains open; scoped receiving proof is recorded at that owner. | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 2eba1999ad..41f16a14aa 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -35,11 +35,18 @@ public AuthenticatedDirectTextCommandReceiver( } public TextCommandInterpretationResult receive(WebSocketSession socket, TextCommand command) { - var connection = sessions.require(socket); try { + var connection = sessions.require(socket); return switch (command.type()) { case LOGIN -> { - var credentials = command.credentialsPayload().orElseThrow(); + var credentials = command.credentialsPayload().orElse(null); + if (command.args().size() != 2 + || credentials == null + || credentials.loginName() == null + || credentials.loginName().isBlank() + || credentials.password() == null + || credentials.password().isEmpty()) + yield failure("INVALID_ARGUMENT", "Usage: LOGIN "); var owner = required(logins); String email = EmailCanonicalization.normalize(credentials.loginName()); connection.login(owner, email, credentials.password().toCharArray()); @@ -49,46 +56,58 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm connection.menu = required(selections).browse().orElseThrow(); yield success(String.join("\n", connection.menu.selectors())); } - case REALMS -> - connection.withLogin( - (original, result) -> { - if (command.args().size() != 1 || connection.menu == null) - throw new IllegalArgumentException(); - connection.selectedScope = - required(lobbies) - .realms( - original, - result, - connection, - connection.menu, - command.args().getFirst()); - return success(connection.selectedScope.publicTarget().realmDisplayName()); - }); - case JOIN -> - connection.withLogin( - (original, result) -> { - if (connection.menu == null || connection.selectedScope == null) - throw new IllegalArgumentException(); - var request = command.joinRequestPayload().orElseThrow(); - var selected = - required(selections) - .resolve(connection.menu, request.worldSelector()) - .orElseThrow(); - if (!selected.equals(connection.selectedScope.publicTarget())) - throw new IllegalArgumentException(); - var observation = required(lobbies).join(original, result, connection); - if (observation.status() - != DirectTextAuthenticatedLobbyOwner.Status - .COMPLETED_CURRENT_NON_ADMITTING - || observation.currentReply().isEmpty()) throw new IllegalStateException(); - return success("Joined public production realm"); - }); + case REALMS -> { + var request = command.realmBrowsePayload().orElse(null); + if (command.args().size() != 1 + || request == null + || request.worldSelector() == null + || request.worldSelector().isBlank()) + yield failure("INVALID_ARGUMENT", "Usage: REALMS "); + yield connection.withLogin( + (original, result) -> { + if (connection.menu == null) + return failure("INVALID_ARGUMENT", "Run WORLDS before REALMS "); + connection.selectedScope = + required(lobbies) + .realms( + original, result, connection, connection.menu, request.worldSelector()); + return success(connection.selectedScope.publicTarget().realmDisplayName()); + }); + } + case JOIN -> { + var request = command.joinRequestPayload().orElse(null); + if (command.args().size() != 1 + || request == null + || request.worldSelector() == null + || request.worldSelector().isBlank()) + yield failure("INVALID_ARGUMENT", "Usage: JOIN "); + yield connection.withLogin( + (original, result) -> { + if (connection.menu == null || connection.selectedScope == null) + return failure( + "INVALID_ARGUMENT", "Run WORLDS and REALMS before JOIN "); + var selected = + required(selections) + .resolve(connection.menu, request.worldSelector()) + .orElseThrow(); + if (!selected.equals(connection.selectedScope.publicTarget())) + return failure( + "INVALID_ARGUMENT", "Use REALMS before JOIN of a different world"); + var observation = required(lobbies).join(original, result, connection); + if (observation.status() + != DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING + || observation.currentReply().isEmpty()) throw new IllegalStateException(); + return success("Joined public production realm"); + }); + } // LOGIN and JOIN are not admission. Until the canonical binding owner is qualified, the // retired numeric entitlement route must never be selected by this protected receiver. case PLAY -> failure("ADMISSION_UNAVAILABLE", "Canonical gameplay admission unavailable"); case LOGOUT -> success("Logged out"); default -> failure("FEATURE_UNAVAILABLE", "Command unavailable"); }; + } catch (AuthenticatedDirectTextSessions.LoginRequiredException missingLogin) { + return failure("LOGIN_REQUIRED", "Use LOGIN before REALMS or JOIN"); } catch (AuthenticatedDirectTextSessions.LoginRejectedException rejected) { return switch (rejected.code()) { case AuthenticationErrorCodes.INVALID_CREDENTIALS -> diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java index 431875d959..27ef162fda 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java @@ -159,7 +159,7 @@ public T withLogin( try { requireLive(); InitialGameplayLoginOwner.Outcome owned = outcome; - if (owned == null) throw unavailable(); + if (owned == null) throw new LoginRequiredException(); return owned.withOwnedPrivateResult( result -> { if (borrowed.putIfAbsent(Thread.currentThread(), result) != null) throw unavailable(); @@ -260,6 +260,15 @@ private void drainPredecessor() { } } + /** A live connection has not installed a LOGIN result; this grants no custody or authority. */ + static final class LoginRequiredException extends IllegalStateException { + private static final long serialVersionUID = 1L; + + private LoginRequiredException() { + super("LOGIN is required on this live connection"); + } + } + static final class LoginRejectedException extends IllegalStateException { private static final long serialVersionUID = 1L; private final String code; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index 50ef6c4c1b..003cf91e33 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -12,9 +12,11 @@ import java.util.Optional; import java.util.UUID; import java.util.function.BiFunction; +import java.util.stream.Stream; import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; import net.firedevops.firemud.gamesession.command.text.TextCommand; +import net.firedevops.firemud.gamesession.command.text.TextCommandPayload; import net.firedevops.firemud.gamesession.command.text.TextCommandType; import net.firedevops.firemud.gamesession.config.PresentationProperties; import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; @@ -25,6 +27,8 @@ import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyOwner; import net.firedevops.firemud.gamesession.service.directtext.DirectTextAuthenticatedLobbyScope; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.support.StaticListableBeanFactory; import org.springframework.web.socket.WebSocketSession; @@ -99,6 +103,125 @@ void loginAndLobbyObservationsNeverSubstituteForCanonicalPlayAdmission() { verifyNoInteractions(fixture.lobby, fixture.selections); } + @ParameterizedTest + @MethodSource("malformedCommands") + void malformedCommandsReturnUsageBeforeOwnerOrLoginDispatch(TextCommand command) { + var fixture = fixture(); + + var result = fixture.receiver.receive(fixture.socket, command); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()).startsWith("Usage: " + command.type()); + assertThat( + new TextPlayerOutputRenderer(new PresentationProperties()) + .renderAll(command, result.commandResult(), result.outputs())) + .startsWith("ERROR INVALID_ARGUMENT Usage: " + command.type()); + verifyNoInteractions(fixture.connection, fixture.lobby, fixture.selections); + } + + private static Stream malformedCommands() { + return Stream.of( + new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"), + new TextCommand(TextCommandType.LOGIN, List.of("player@example.test"), "LOGIN"), + new TextCommand( + TextCommandType.LOGIN, List.of("player@example.test", "secret", "extra"), "LOGIN"), + new TextCommand(TextCommandType.LOGIN, List.of(" ", "secret"), "LOGIN"), + new TextCommand(TextCommandType.LOGIN, List.of("player@example.test", ""), "LOGIN"), + new TextCommand( + TextCommandType.LOGIN, + List.of("player@example.test", "secret"), + "LOGIN", + "LOGIN", + new TextCommandPayload.Credentials(null, "secret")), + new TextCommand( + TextCommandType.LOGIN, + List.of("player@example.test", "secret"), + "LOGIN", + "LOGIN", + new TextCommandPayload.Credentials("player@example.test", null)), + new TextCommand(TextCommandType.REALMS, List.of(), "REALMS"), + new TextCommand(TextCommandType.REALMS, List.of("demo", "extra"), "REALMS"), + new TextCommand(TextCommandType.REALMS, List.of(" "), "REALMS"), + new TextCommand(TextCommandType.JOIN, List.of(), "JOIN"), + new TextCommand(TextCommandType.JOIN, List.of("demo", "extra"), "JOIN"), + new TextCommand(TextCommandType.JOIN, List.of(" "), "JOIN")); + } + + @Test + void realmsBeforeWorldsExplainsTheRequiredLocalSequence() { + var fixture = fixture(); + fixture.connection.menu = null; + + var result = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo")); + + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()).isEqualTo("Run WORLDS before REALMS "); + verifyNoInteractions(fixture.lobby, fixture.selections); + } + + @Test + void joinBeforeRealmsExplainsTheRequiredLocalSequence() { + var fixture = fixture(); + fixture.connection.selectedScope = null; + + var result = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Run WORLDS and REALMS before JOIN "); + verifyNoInteractions(fixture.lobby, fixture.selections); + } + + @Test + void differentResolvedWorldRequiresItsOwnRealmsSelection() { + var fixture = fixture(); + when(fixture.selections.resolve(fixture.connection.menu, "other")) + .thenReturn(Optional.of(mock(CanonicalPlayableTarget.class))); + + var result = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("other"), "JOIN other")); + + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()).contains("REALMS "); + verifyNoInteractions(fixture.lobby); + } + + @Test + void protectedOwnerAndSelectionFailuresRemainUnavailableRatherThanUsageErrors() { + for (RuntimeException failure : + List.of( + new IllegalArgumentException("private-source"), + new IllegalStateException("private-custody"))) { + var realms = fixture(); + when(realms.lobby.realms(null, null, realms.connection, realms.connection.menu, "demo")) + .thenThrow(failure); + var realmResult = + realms.receiver.receive( + realms.socket, + new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo")); + assertThat(realmResult.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(realmResult.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + + var join = fixture(); + when(join.selections.resolve(join.connection.menu, "demo")).thenThrow(failure); + var joinResult = + join.receiver.receive( + join.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + assertThat(joinResult.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(joinResult.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + verifyNoInteractions(join.lobby); + } + } + private Fixture fixture() { var socket = mock(WebSocketSession.class); var sessions = mock(AuthenticatedDirectTextSessions.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java index 37bf4e8119..649653f941 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java @@ -30,6 +30,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.EnumSource; import org.springframework.beans.factory.support.StaticListableBeanFactory; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.mock.web.MockHttpServletRequest; @@ -92,6 +93,36 @@ void rejectedLoginPreservesOnlyBoundedDecisionsThroughTheReceiver( verify(outcome).close(); } + @ParameterizedTest + @EnumSource( + value = TextCommandType.class, + names = {"REALMS", "JOIN"}) + void missingLoginIsActionableButClosedCustodyRemainsUnavailable(TextCommandType type) + throws Exception { + var socket = socket(); + sessions.open(socket); + var beans = new StaticListableBeanFactory(); + var receiver = + new AuthenticatedDirectTextCommandReceiver( + sessions, + beans.getBeanProvider(InitialGameplayLoginOwner.class), + beans.getBeanProvider(DirectTextWorldSelectionService.class), + beans.getBeanProvider(DirectTextAuthenticatedLobbyOwner.class)); + var command = new TextCommand(type, List.of("demo"), type + " demo"); + + var missingLogin = receiver.receive(socket, command); + + assertThat(missingLogin.commandResult().errorCode()).isEqualTo("LOGIN_REQUIRED"); + assertThat(missingLogin.commandResult().errorMessage()).contains("LOGIN "); + sessions.close(socket, CloseStatus.NORMAL); + + var closedCustody = receiver.receive(socket, command); + + assertThat(closedCustody.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(closedCustody.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); + } + @Test void rejectedLoginErasesCredentialsAndRetainsCleanupOwnership() throws Exception { var socket = socket(); From 672ca35b9f69533507d542cdbd9ba2b8f90b505a Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:37:12 +1300 Subject: [PATCH 12/20] docs(gateway): include authenticated Game Session egress --- .../microservices/spring-cloud-gateway/configuration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index 3f8a3b7f89..4fbed7c8ce 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -32,7 +32,7 @@ The trusted default-branch workflow treats the hosted preview Gateway configurat The Gateway Deployment has a matching exact contract for its per-container `env` and `envFrom` fields. PR-controlled `extraEnv` or additional configuration references cannot replace the managed listener/trust settings or introduce an equivalent route or JVM override. This contract is enforced by the hosted artifact validator and must be updated together with the trusted Helm defaults when a legitimate Gateway setting is added. -The hosted Gateway pod also has default-deny egress. Its only permitted destinations are cluster DNS, the five canonical HTTP route services on TCP/8080 (`account-service`, `game-design-service`, `game-session-service`, `logging-admin-service`, and `social-groups-service`), Cache/Rate-Limit Redis on TCP/6379, and the OpenTelemetry collector on TCP/4317. This egress boundary prevents a surviving configuration or runtime override from turning the Gateway into an arbitrary network proxy. +The hosted Gateway pod also has default-deny egress. Its only permitted destinations are cluster DNS, the five canonical HTTP route services on TCP/8080 (`account-service`, `game-design-service`, `game-session-service`, `logging-admin-service`, and `social-groups-service`), Game Session on TCP/8444 for the dedicated authenticated mTLS WebSocket receiver at `/ws/game/tcp`, Cache/Rate-Limit Redis on TCP/6379, and the OpenTelemetry collector on TCP/4317. This egress boundary prevents a surviving configuration or runtime override from turning the Gateway into an arbitrary network proxy. ### TCP Proxy TLS listener From 5565650ff058b6adbdead101f5cadb833495747c Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:51:01 +1300 Subject: [PATCH 13/20] fix(game-session): preserve authenticated TCP login errors --- ...uthenticatedDirectTextCommandReceiver.java | 7 +++- .../AuthenticatedDirectTextSessions.java | 9 ++++-- ...nticatedDirectTextCommandReceiverTest.java | 32 +++++++++++++++++++ .../AuthenticatedDirectTextSessionsTest.java | 10 ++++-- 4 files changed, 51 insertions(+), 7 deletions(-) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 41f16a14aa..1c6e09b508 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -47,8 +47,13 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm || credentials.password() == null || credentials.password().isEmpty()) yield failure("INVALID_ARGUMENT", "Usage: LOGIN "); + String email; + try { + email = EmailCanonicalization.normalize(credentials.loginName()); + } catch (IllegalArgumentException invalidEmail) { + yield failure("INVALID_ARGUMENT", "Usage: LOGIN "); + } var owner = required(logins); - String email = EmailCanonicalization.normalize(credentials.loginName()); connection.login(owner, email, credentials.password().toCharArray()); yield connection.withLogin((original, result) -> success("Logged in as " + email)); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java index 27ef162fda..ea5812f051 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java @@ -135,10 +135,13 @@ public void login(InitialGameplayLoginOwner owner, String email, char[] ownedSec requireLive(); InitialGameplayLoginOwner.Outcome received = Objects.requireNonNull(owner).receive(credentials); - outcome = received; credentials = null; - if (received.status() != InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING) - throw new LoginRejectedException(received.failureCode().orElse("UNAVAILABLE")); + if (received.status() != InitialGameplayLoginOwner.Status.INSTALLED_NON_ADMITTING) { + String failureCode = received.failureCode().orElse("UNAVAILABLE"); + received.close(); + throw new LoginRejectedException(failureCode); + } + outcome = received; requireLive(); } finally { java.util.Arrays.fill(ownedSecret, '\0'); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index 003cf91e33..2727167c85 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -3,6 +3,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -29,6 +30,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.support.StaticListableBeanFactory; import org.springframework.web.socket.WebSocketSession; @@ -53,6 +55,36 @@ void authenticatedLoginWithoutOwnerRefusesBeforeDispatch() { verifyNoInteractions(fixture.connection, fixture.lobby, fixture.selections); } + @Test + @SuppressWarnings("unchecked") + void emailNormalizationRejectionReturnsUsageBeforeProtectedOwnerLookup() { + var socket = mock(WebSocketSession.class); + var sessions = mock(AuthenticatedDirectTextSessions.class); + var connection = mock(AuthenticatedDirectTextSessions.Connection.class); + when(sessions.require(socket)).thenReturn(connection); + ObjectProvider logins = mock(ObjectProvider.class); + ObjectProvider selections = mock(ObjectProvider.class); + ObjectProvider lobbies = mock(ObjectProvider.class); + var receiver = + new AuthenticatedDirectTextCommandReceiver(sessions, logins, selections, lobbies); + var malformedEmail = " \u0000 "; + var command = + new TextCommand( + TextCommandType.LOGIN, + List.of(malformedEmail, "secret"), + "LOGIN malformed secret", + "LOGIN", + new TextCommandPayload.Credentials(malformedEmail, "secret")); + + var result = receiver.receive(socket, command); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()).isEqualTo("Usage: LOGIN "); + verify(logins, never()).getIfAvailable(); + verifyNoInteractions(connection); + } + @Test void joinUsesOneFriendlyWorldSelectorButDispatchesOnlyTheRetainedScope() { var fixture = fixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java index 649653f941..28fae900fb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java @@ -89,8 +89,12 @@ void rejectedLoginPreservesOnlyBoundedDecisionsThroughTheReceiver( .isEqualTo("Authenticated gameplay authority unavailable"); } verify(outcome, never()).withOwnedPrivateResult(any()); - sessions.close(socket, CloseStatus.NORMAL); + var laterBorrow = + receiver.receive( + socket, new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo")); + assertThat(laterBorrow.commandResult().errorCode()).isEqualTo("LOGIN_REQUIRED"); verify(outcome).close(); + sessions.close(socket, CloseStatus.NORMAL); } @ParameterizedTest @@ -139,9 +143,9 @@ void rejectedLoginErasesCredentialsAndRetainsCleanupOwnership() throws Exception .hasMessage("Authenticated gameplay LOGIN was rejected"); assertThat(secret).containsOnly('\0'); - verify(outcome, never()).close(); - sessions.close(socket, CloseStatus.NORMAL); verify(outcome).close(); + sessions.close(socket, CloseStatus.NORMAL); + verify(outcome, org.mockito.Mockito.times(1)).close(); } @Test From 9d48a2ff077d3f5551c98da99b3310ec1f738456 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:24:18 +1300 Subject: [PATCH 14/20] fix(gameplay): prevent late TLS reload after shutdown --- .../InitialGameplayLoginOwnerTest.java | 2 +- ...nticatedDirectTextCommandReceiverTest.java | 30 +++++++--- ...sionWebSocketHandshakeInterceptorTest.java | 24 ++++++++ .../AuthenticatedGameplayWebSocketClient.java | 47 +++++++++++++-- ...henticatedGameplayWebSocketClientTest.java | 58 +++++++++++++++++++ 5 files changed, 148 insertions(+), 13 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java index 83dc0d0af3..5d78317387 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java @@ -146,7 +146,7 @@ void ownedBorrowPinsExactResultAndRefusesReentrantLifecycleChanges() { return "non-admitting"; }); assertThat(value).isEqualTo("non-admitting"); - verify(success.result()).close(); + assertThat(success.result().compactJwtBytes()).isNotEmpty(); verify(success.fixture().cleanup, never()).abandonAndRetire(any()); org.mockito.Mockito.clearInvocations(success.result()); outcome.close(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index 2727167c85..a9c37e54a3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -104,14 +104,30 @@ void joinUsesOneFriendlyWorldSelectorButDispatchesOnlyTheRetainedScope() { } @Test - void emptyOrDifferentJoinSelectionNeverCallsAccountLobbyOwner() { + void refusedJoinReportsTheExactInvalidArgumentOrUnavailableError() { var fixture = fixture(); - for (var args : List.of(List.of(), List.of("other"), List.of("demo", "production"))) { - var result = - fixture.receiver.receive( - fixture.socket, new TextCommand(TextCommandType.JOIN, args, "JOIN")); - assertThat(result.commandResult().accepted()).isFalse(); - } + var empty = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of(), "JOIN")); + assertThat(empty.commandResult().accepted()).isFalse(); + assertThat(empty.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(empty.commandResult().errorMessage()).isEqualTo("Usage: JOIN "); + + var excessive = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.JOIN, List.of("demo", "production"), "JOIN")); + assertThat(excessive.commandResult().accepted()).isFalse(); + assertThat(excessive.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(excessive.commandResult().errorMessage()).isEqualTo("Usage: JOIN "); + + var unresolved = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("other"), "JOIN other")); + assertThat(unresolved.commandResult().accepted()).isFalse(); + assertThat(unresolved.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(unresolved.commandResult().errorMessage()) + .isEqualTo("Authenticated gameplay authority unavailable"); verifyNoInteractions(fixture.lobby); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java index de960c0856..8110b3e24b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java @@ -157,6 +157,30 @@ void rejectsSpoofedHeadersWrongWorkloadsNamespacesAndPublicListener() throws Exc assertRejected(duplicateMode); } + @Test + void rejectsMissingCertificateClientAuthEkuAndSpiffeSan() throws Exception { + var missingCertificate = + authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + missingCertificate.removeAttribute("jakarta.servlet.request.X509Certificate"); + assertRejected(missingCertificate); + + var missingClientAuth = + authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + var nonClientAuthCertificate = + (X509Certificate[]) + missingClientAuth.getAttribute("jakarta.servlet.request.X509Certificate"); + when(nonClientAuthCertificate[0].getExtendedKeyUsage()) + .thenReturn(List.of("1.3.6.1.5.5.7.3.1")); + assertRejected(missingClientAuth); + + var missingSpiffeSan = authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + var certificateWithNoUriSan = + (X509Certificate[]) + missingSpiffeSan.getAttribute("jakarta.servlet.request.X509Certificate"); + when(certificateWithNoUriSan[0].getSubjectAlternativeNames()).thenReturn(List.of()); + assertRejected(missingSpiffeSan); + } + private void assertRejected(MockHttpServletRequest request) { var attributes = new HashMap(); var response = new MockHttpServletResponse(); diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java index 238a394a66..b1d0e4d719 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java @@ -23,11 +23,23 @@ public final class AuthenticatedGameplayWebSocketClient implements AutoCloseable private final String expectedPeer; private final String expectedClient; private final URI upstream; + private final Object publicationLock = new Object(); + private final Runnable beforePublish; private volatile ReactorNettyWebSocketClient client; private TlsCertificateWatcher watcher; + private boolean closed; public AuthenticatedGameplayWebSocketClient( CommonGrpcClientProperties properties, String namespace, String upstreamUrl) { + this(properties, namespace, upstreamUrl, () -> {}); + } + + AuthenticatedGameplayWebSocketClient( + CommonGrpcClientProperties properties, + String namespace, + String upstreamUrl, + Runnable beforePublish) { + this.beforePublish = beforePublish; tls = properties.copy(); FileBackedGrpcMtlsPolicy.require( tls, @@ -50,7 +62,8 @@ public AuthenticatedGameplayWebSocketClient( public void initialize() throws IOException { reload(); - watcher = + if (isClosed()) return; + TlsCertificateWatcher newWatcher = TlsCertificateWatcher.createAndStart( List.of( Path.of(tls.getCertChain()), @@ -64,9 +77,16 @@ public void initialize() throws IOException { "Authenticated gameplay TLS reload failed", failure); } }); + boolean discardWatcher; + synchronized (publicationLock) { + discardWatcher = closed; + if (!discardWatcher) watcher = newWatcher; + } + if (discardWatcher) newWatcher.close(); } - private void reload() throws IOException { + void reload() throws IOException { + if (isClosed()) return; try (var input = java.nio.file.Files.newInputStream(Path.of(tls.getCertChain()))) { var certificate = (java.security.cert.X509Certificate) @@ -107,7 +127,17 @@ private void reload() throws IOException { .isEmpty()) throw new IllegalStateException("Authenticated Game Session peer required"); }); - client = new ReactorNettyWebSocketClient(http); + ReactorNettyWebSocketClient newClient = new ReactorNettyWebSocketClient(http); + beforePublish.run(); + synchronized (publicationLock) { + if (!closed) client = newClient; + } + } + + private boolean isClosed() { + synchronized (publicationLock) { + return closed; + } } public Mono execute(HttpHeaders headers, WebSocketHandler handler) { @@ -128,7 +158,14 @@ public URI upstream() { @Override public void close() throws IOException { - if (watcher != null) watcher.close(); - client = null; + TlsCertificateWatcher currentWatcher; + synchronized (publicationLock) { + if (closed) return; + closed = true; + client = null; + currentWatcher = watcher; + watcher = null; + } + if (currentWatcher != null) currentWatcher.close(); } } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java index f83697652c..1c233e2a11 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java @@ -17,7 +17,10 @@ import java.util.Map; import java.util.Set; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.springcloudgateway.config.GameplayWebSocketBridgeProperties; import net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin; @@ -120,6 +123,61 @@ void executionSignalsUnavailableWhenClosedBeforeOrAfterAssembly() throws Excepti } } + @Test + void lateReloadCannotRepublishClientAfterClose() throws Exception { + CountDownLatch candidateBuilt = new CountDownLatch(1); + CountDownLatch finishReload = new CountDownLatch(1); + AtomicInteger reloads = new AtomicInteger(); + Runnable beforePublish = + () -> { + if (reloads.incrementAndGet() == 2) { + candidateBuilt.countDown(); + try { + finishReload.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + } + }; + try (var client = + new AuthenticatedGameplayWebSocketClient( + pki.clientProperties(directory, pki.identity("gateway")), + "test", + "wss://localhost:8444/ws/game/tcp", + beforePublish)) { + client.initialize(); + AtomicReference reloadFailure = new AtomicReference<>(); + Thread lateReload = + new Thread( + () -> { + try { + client.reload(); + } catch (Exception failure) { + reloadFailure.set(failure); + } + }); + lateReload.start(); + try { + assertThat(candidateBuilt.await(5, TimeUnit.SECONDS)).isTrue(); + client.close(); + assertThat(lateReload.isAlive()).isTrue(); + } finally { + finishReload.countDown(); + lateReload.join(Duration.ofSeconds(5).toMillis()); + } + + assertThat(lateReload.isAlive()).isFalse(); + assertThat(reloadFailure.get()).isNull(); + StepVerifier.create(client.execute(new HttpHeaders(), socket -> Mono.empty())) + .expectErrorMatches( + error -> + error instanceof IllegalStateException + && "Authenticated gameplay client unavailable".equals(error.getMessage())) + .verify(Duration.ofSeconds(5)); + } + } + @Test void closedClientFollowsBridgeCloseAndReleasesActiveRegistration() throws Exception { try (var client = From 3ee9480a4220ad11fc38f241949dfb41edf39a32 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:54:55 +1300 Subject: [PATCH 15/20] fix(gameplay): enforce verified TCP transport selection --- .../environment-and-secrets-catalog.md | 15 ++++++ .../game-session-service/configuration.md | 4 ++ .../spring-cloud-gateway/configuration.md | 6 ++- .../text/DirectTextWorldSelectionService.java | 18 ++++++- ...uthenticatedDirectTextCommandReceiver.java | 5 ++ .../DirectTextWorldSelectionServiceTest.java | 24 ++++++--- ...nticatedDirectTextCommandReceiverTest.java | 53 ++++++++++++++++--- ...sionWebSocketHandshakeInterceptorTest.java | 29 +++++----- .../GameplayWebSocketBridgeHandler.java | 34 ++++++------ .../GameplayWebSocketBridgeHandlerTest.java | 36 +++++++++++++ 10 files changed, 172 insertions(+), 52 deletions(-) diff --git a/design/architecture/infrastructure/environment-and-secrets-catalog.md b/design/architecture/infrastructure/environment-and-secrets-catalog.md index cdedc77143..19f30c887e 100644 --- a/design/architecture/infrastructure/environment-and-secrets-catalog.md +++ b/design/architecture/infrastructure/environment-and-secrets-catalog.md @@ -121,6 +121,21 @@ A sample `Certificate` manifest is provided at `k8s/base/firemud-grpc-certificat | `FIREMUD_GRPC_PRIVATE_KEY_PATH` | Filesystem path to the private key matching the certificate chain | `certs/client.key` | | `FIREMUD_GRPC_CA_CERT_PATH` | Filesystem path to the CA bundle used to verify peer services | `certs/ca.crt` | +### Authenticated TCP Gameplay Bridge + +Ordinary Gateway-to-backend HTTP and WebSocket routes remain explicit in-cluster exceptions with their existing Gateway trust, header-canonicalization, and NetworkPolicy controls. Authenticated TCP gameplay receiving uses a separate verified-origin `wss://` connection from Gateway to Game Session, with a dedicated client identity and a dedicated Game Session TLS listener. The [Security Architecture](../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving) owns the trust and custody contract; the [player access tracker](../../project-management/implementation-tracking/player-access-and-session.md) records current registration and deployment proof status. + +| Variable | Purpose | Default / current binding | +| -------- | ------- | ------- | +| `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_AUTHENTICATED_UPSTREAM_URL` | Gateway's authenticated receiver URI; the authenticated client is absent when this property is unset. | No code default; unset unless deployment binds it. Hosted Helm binds `wss://game-session-service.$(FIREMUD_GRPC_WORKLOAD_NAMESPACE).svc.cluster.local:8444/ws/game/tcp`. | +| `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CERT_CHAIN_PATH` | Gateway's dedicated client certificate chain for the authenticated receiver. | Empty by default; base and hosted bindings use `/gameplay-client-tls/tls.crt`. | +| `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_PRIVATE_KEY_PATH` | Private key matching the dedicated Gateway client certificate. | Empty by default; base and hosted bindings use `/gameplay-client-tls/tls.key`. | +| `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_CA_CERT_PATH` | Trust bundle used by Gateway to verify Game Session's authenticated listener certificate. | Empty by default; base and hosted bindings use `/gameplay-client-trust/ca.crt`. | +| `FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_ENABLED` | Enables Game Session's separate authenticated gameplay TLS listener. | `false`; hosted Helm sets `true`. | +| `FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_PORT` | Port for the separate listener, distinct from the configured ordinary HTTP port. | `8444`; hosted Helm sets `8444`. | + +The TLS path defaults are empty in Gateway's authenticated-client binding; Kubernetes supplies the dedicated mounted paths shown above. Game Session's listener is disabled unless enabled explicitly. The shared `firemud-grpc` SSL bundle currently supplies the listener certificate and reload source; these gameplay-specific Gateway client paths do not replace Gateway's `FIREMUD_GRPC_*` management-plane paths or its independent TCP Proxy-facing WebSocket server identity. Exact registration, issuance, and deployment evidence remains subject to the linked owner and tracker. + ### Gateway HTTP Management-Plane TLS (Target State) Gateway-owned HTTP management endpoints use a dedicated operator client identity and listener trust bundle. These paths are separate from the Gateway service's `FIREMUD_GRPC_*` workload identity and are resolved from the selected `operator-credential-binding/v1` record. For `SECRET_BACKED` and `CERT_MANAGER` bindings, the client certificate/key and trust bundle are file-backed through the variables below; a `WORKLOAD_IDENTITY` binding uses its provider-projected client identity and trust bundle and does not require a substitute Secret or these file paths. The binding record's closed `bindingType` and source-specific resolution, not this catalog or endpoint-local configuration, determine which representation applies: diff --git a/design/architecture/microservices/game-session-service/configuration.md b/design/architecture/microservices/game-session-service/configuration.md index da1714a54f..9e594b15da 100644 --- a/design/architecture/microservices/game-session-service/configuration.md +++ b/design/architecture/microservices/game-session-service/configuration.md @@ -14,6 +14,8 @@ Game Session follows the configuration scheme from [Environment Variables & Secr TLS certificates are supplied via [`FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC_PRIVATE_KEY_PATH`, `FIREMUD_GRPC_CA_CERT_PATH`](../../infrastructure/environment-and-secrets.md#grpc-tls-certificates). Peer services can be discovered using variables prefixed `FIREMUD_SERVICES_`. The OpenTelemetry collector endpoint can be overridden via `OTEL_ENDPOINT`. +The authenticated TCP gameplay receiver uses a separate internal TLS listener, disabled by default and distinct from the configured ordinary HTTP port. [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving) owns the mTLS trust and custody contract. The [environment and secrets catalog](../../infrastructure/environment-and-secrets-catalog.md#authenticated-tcp-gameplay-bridge) records the deployed bindings. + | Variable | Purpose | Default | | -------- | ------- | ------- | | `GAME_TICK_DURATION_MS` | Tick cadence (`tick_interval_ms`): target interval between ticks for a region | `1000` | @@ -25,6 +27,8 @@ TLS certificates are supplied via [`FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC | `FIREMUD_SERVICES_WORLD_MANAGEMENT_SERVICE` | gRPC endpoint (`host:port`) for World Management Service | `world-management-service:6565` | | `FIREMUD_SERVICES_ENTITY_MANAGEMENT_SERVICE` | gRPC endpoint (`host:port`) for Entity Management Service | `entity-management-service:6565` | | `FIREMUD_CONFLICT_TTL_SECONDS` | TTL for conflict hotspot tracking in Redis | `300` | +| `FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_ENABLED` | Enables the separate mTLS listener for authenticated TCP gameplay receiving. | `false` (hosted Helm: `true`) | +| `FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_PORT` | Port for the separate listener; must differ from the ordinary HTTP port. | `8444` (hosted Helm: `8444`) | ## FireMUD Settings Domains diff --git a/design/architecture/microservices/spring-cloud-gateway/configuration.md b/design/architecture/microservices/spring-cloud-gateway/configuration.md index 4fbed7c8ce..d62e9ab4d6 100644 --- a/design/architecture/microservices/spring-cloud-gateway/configuration.md +++ b/design/architecture/microservices/spring-cloud-gateway/configuration.md @@ -20,6 +20,7 @@ Spring Cloud Gateway reads its configuration from a small set of sources. The fu | `FIREMUD_REDIS_CACHE_HOST` / `FIREMUD_REDIS_CACHE_PORT` | Cache/Rate-Limit Redis endpoint used by the gateway `RequestRateLimiter` filter. | See [Redis Connection](../../infrastructure/environment-and-secrets.md#redis-connection). | | `firemud.gateway.header-trust.*` | Header-trust and canonicalization configuration enforced by `HeaderTrustFilter` for public ingress versus trusted proxy sources. | Service-local gateway trust boundary; behavior must stay aligned with [Gateway Architecture](../../system-architecture-gateway.md#header-trust-model). | | `FIREMUD_GATEWAY_TCP_PROXY_TLS_*` / `FIREMUD_GATEWAY_TCP_PROXY_TRUST_*` | Dedicated internal TLS listener material, environment classification, and the one selected TCP Proxy trust profile. | Service-local implementation of [ADR 0169](../../decisions/adr-0169-exclusive-environment-bound-tcp-proxy-trust.md); exact variables are listed below. | +| `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_AUTHENTICATED_UPSTREAM_URL` and `FIREMUD_GATEWAY_GAMEPLAY_BRIDGE_TLS_*_PATH` | Dedicated verified-origin `wss` client for authenticated TCP gameplay receiving. | See the [environment and secrets catalog](../../infrastructure/environment-and-secrets-catalog.md#authenticated-tcp-gameplay-bridge); custody and trust rules belong to [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). | | `firemud.gateway.backendUnavailableGraceMs` / `firemud.gateway.backendUnavailableRecoverySuccessCount` | Target gameplay-route backend-unavailable elapsed-time cutoff and recovery hysteresis knobs. The grace value must be positive and no greater than ADR 0013's 30,000 ms hard cutoff; ordinary qualifying recovery targets 10 seconds. | Not implemented in the current bound properties or bridge. Canonical behavior lives in [Gateway Architecture](../../system-architecture-gateway.md#backend-unavailable-grace-window), [Reconnection Strategy](../../system-architecture-reconnection.md#backend-unavailable-scenarios), and [ADR 0013](../../decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md). | | `FIREMUD_GRPC_CERT_CHAIN_PATH`, `FIREMUD_GRPC_PRIVATE_KEY_PATH`, `FIREMUD_GRPC_CA_CERT_PATH` | TLS certificate and key paths for the gateway internal gRPC management plane. | See [gRPC TLS Certificates](../../infrastructure/environment-and-secrets.md#grpc-tls-certificates). | | `OTEL_ENDPOINT` | OpenTelemetry collector endpoint for traces. | See [Observability](../../infrastructure/environment-and-secrets.md#observability). | @@ -97,13 +98,14 @@ Any additional gateway-local caches must explicitly declare whether they are str - **Target-state JWT and presence boundary:** Spring Cloud Gateway does not validate or parse ordinary JWTs for routed gameplay or admin traffic, does not require JWT signing material for those routes, and does not own gameplay login, session, or presence state. Downstream services, especially Game Session, remain responsible for those concerns. The target gameplay-connect exception is `/ws/game/**`: Gateway validates the short-lived connect credential and emits the owner-defined signed downstream context only after the canonical signature, claim, expiry, scope, replay-readiness, and atomic-consume checks. **Current first-party implementation:** `GameplayHandshakeFilter` does not parse a gameplay-connect credential, sign a context, or consult/consume replay state. It rejects a presented cookie with `CONNECT_REPLAY_PROTECTION_UNAVAILABLE`, and gameplay-route readiness is `OUT_OF_SERVICE` pending canonical Account production, shared replay fencing, and dedicated Gateway signing-key qualification. The separate trusted TCP Proxy admission path remains available under its existing trust profile. - Admin and other meta/control services validate JWTs themselves. The gateway `JwtAuthFilter` only enforces the presence of an `Authorization` header on protected routes and forwards tokens unchanged. - External TLS is terminated by the load balancer. -- Spring Cloud Gateway routes to backend services over in-cluster `http://` and `ws://` endpoints, while internal service-to-service traffic uses mTLS gRPC as described in the [Security Architecture](../../system-architecture-security.md). +- Ordinary Spring Cloud Gateway backend routes use in-cluster `http://` and `ws://` endpoints under their existing Gateway trust, header-canonicalization, and NetworkPolicy controls; those route exceptions do not establish authenticated TCP receiving authority. That receiver uses a separate verified-origin `wss://` connection to Game Session with the dedicated client identity and trust paths documented in the [environment and secrets catalog](../../infrastructure/environment-and-secrets-catalog.md#authenticated-tcp-gameplay-bridge), under the [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). Internal service-to-service gRPC traffic uses mTLS as described in the [Security Architecture](../../system-architecture-security.md). - When internal WebSocket clients such as the TCP Proxy Service connect over `wss://` to `/ws/game/**`, the host used in `GATEWAY_WS_URL` must match a name present in the Gateway certificate SANs so SNI and hostname verification succeed. Using a bare IP or an unrelated hostname causes client-side TLS failure, and those failures should remain visible in TCP Proxy bridge metrics and logs. ## Dependencies - Internal dependencies: - - Game Session Service and other backend services via configured `http://` and `ws://` route targets. + - Game Session Service and other backend services via configured ordinary `http://` and `ws://` route targets, which remain explicit in-cluster exceptions. + - Game Session's authenticated TCP receiver via its dedicated verified-origin `wss://` endpoint and Gateway client mTLS identity; see the [environment and secrets catalog](../../infrastructure/environment-and-secrets-catalog.md#authenticated-tcp-gameplay-bridge) and [Security Architecture](../../system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). - TCP Proxy Service, which forwards Telnet traffic into the gateway. - External dependency: - Spring Cloud Gateway infrastructure. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java index 66a8783f25..d9b75867b6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java @@ -120,7 +120,12 @@ private Optional compose(Instant createdAt, Instant expiresAt) { return Optional.of(new Snapshot(choices, original.fingerprint(), createdAt, expiresAt)); } - /** Resolves only the retained vector, then revalidates the complete selected owner record. */ + /** + * Resolves only the retained vector, then revalidates the complete selected owner record. + * + * @throws UnknownWorldSelectorException when a nonblank selector does not uniquely match a choice + * in a live menu owned by this service + */ public Optional resolve(SelectionSnapshot retained, String selector) { if (retained == null || retained.owner != this @@ -132,7 +137,7 @@ public Optional resolve(SelectionSnapshot retained, Str Snapshot snapshot = retained.snapshot; Optional selected = select(snapshot.choices(), selector); if (selected.isEmpty()) { - return Optional.empty(); + throw new UnknownWorldSelectorException(); } CanonicalPlayableTarget expected = selected.orElseThrow().target(); CanonicalPlayableTarget current; @@ -279,6 +284,15 @@ private String selector() { } } + /** A nonblank selector did not uniquely select a choice in this exact live menu. */ + public static final class UnknownWorldSelectorException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public UnknownWorldSelectorException() { + super("Unknown or ambiguous world selector"); + } + } + private record RuntimeWorldIdentity(long tenantId, String worldSlug) {} private record RuntimeTargetIdentity(long tenantId, long gameInstanceId) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 1c6e09b508..5c951f058c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -5,6 +5,7 @@ import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.UnknownWorldSelectorException; import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandInterpretationResult; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; @@ -113,6 +114,10 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm }; } catch (AuthenticatedDirectTextSessions.LoginRequiredException missingLogin) { return failure("LOGIN_REQUIRED", "Use LOGIN before REALMS or JOIN"); + } catch (UnknownWorldSelectorException unknownSelector) { + return failure( + "INVALID_ARGUMENT", + "Unknown or ambiguous world selector. Run WORLDS and choose a listed selector."); } catch (AuthenticatedDirectTextSessions.LoginRejectedException rejected) { return switch (rejected.code()) { case AuthenticationErrorCodes.INVALID_CREDENTIALS -> diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java index f1bd561f5d..8d62a75edd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java @@ -388,9 +388,14 @@ void pairsAreCaseFoldedAndBareTenantRequiresExactlyOneSnapshotWorld() { assertThat(service.resolve(menu, "STUDIO/FOREST")).contains(first); assertThat(service.resolve(menu, "studio/other-world")).contains(sameFriendlyTenant); - assertThat(service.resolve(menu, "studio")).isEmpty(); - assertThat(service.resolve(menu, "forest")).isEmpty(); - assertThat(service.resolve(menu, "other-world")).isEmpty(); + clearInvocations(reader); + assertThatThrownBy(() -> service.resolve(menu, "studio")) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); + assertThatThrownBy(() -> service.resolve(menu, "forest")) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); + assertThatThrownBy(() -> service.resolve(menu, "other-world")) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); + verifyNoInteractions(reader); var single = service(List.of(world(first)), List.of(first)); assertThat(single.resolve(single.browse().orElseThrow(), "STUDIO")).contains(first); @@ -426,7 +431,12 @@ void invalidSelectorsDoNotReadSources(String selector) { clearInvocations(reader); int before = catalogReads.get(); - assertThat(service.resolve(menu, selector)).isEmpty(); + if (selector.isBlank()) { + assertThat(service.resolve(menu, selector)).isEmpty(); + } else { + assertThatThrownBy(() -> service.resolve(menu, selector)) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); + } assertThat(service.resolve(menu, null)).isEmpty(); assertThat(service.resolve(null, "1")).isEmpty(); assertThat(catalogReads.get()).isEqualTo(before); @@ -447,7 +457,8 @@ void bareTenantSelectionNeverFallsBackToAnotherTenantsWorldSlug() { assertThat(service.resolve(menu, "forest")).containsSame(tenantNamedLikeFirstWorld); assertThat(service.resolve(menu, "studio/forest")).containsSame(first); assertThat(service.resolve(menu, "forest/other-world")).containsSame(tenantNamedLikeFirstWorld); - assertThat(service.resolve(menu, "other-world")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "other-world")) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); } @Test @@ -769,7 +780,8 @@ void canonicalTargetsNeverRestoreCatalogCollisionCardinalityOrHiddenRowOmissions when(authority.listPointers()).thenReturn(pointers); var menu = service.browse().orElseThrow(); assertThat(menu.selectors()).isEmpty(); - assertThat(service.resolve(menu, "studio/forest")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "studio/forest")) + .isInstanceOf(DirectTextWorldSelectionService.UnknownWorldSelectorException.class); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index a9c37e54a3..d2c90ed861 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -16,6 +16,7 @@ import java.util.stream.Stream; import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.UnknownWorldSelectorException; import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandPayload; import net.firedevops.firemud.gamesession.command.text.TextCommandType; @@ -103,6 +104,41 @@ void joinUsesOneFriendlyWorldSelectorButDispatchesOnlyTheRetainedScope() { verify(fixture.lobby).join(null, null, fixture.connection); } + @Test + void unknownRealmSelectorReturnsActionableInvalidArgument() { + var fixture = fixture(); + when(fixture.lobby.realms(null, null, fixture.connection, fixture.connection.menu, "missing")) + .thenThrow(new UnknownWorldSelectorException()); + + var result = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.REALMS, List.of("missing"), "REALMS missing")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Unknown or ambiguous world selector. Run WORLDS and choose a listed selector."); + } + + @Test + void unknownJoinSelectorReturnsActionableInvalidArgumentBeforeLobbyDispatch() { + var fixture = fixture(); + when(fixture.selections.resolve(fixture.connection.menu, "missing")) + .thenThrow(new UnknownWorldSelectorException()); + + var result = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.JOIN, List.of("missing"), "JOIN missing")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("Unknown or ambiguous world selector. Run WORLDS and choose a listed selector."); + verifyNoInteractions(fixture.lobby); + } + @Test void refusedJoinReportsTheExactInvalidArgumentOrUnavailableError() { var fixture = fixture(); @@ -121,14 +157,17 @@ void refusedJoinReportsTheExactInvalidArgumentOrUnavailableError() { assertThat(excessive.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(excessive.commandResult().errorMessage()).isEqualTo("Usage: JOIN "); - var unresolved = - fixture.receiver.receive( - fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("other"), "JOIN other")); - assertThat(unresolved.commandResult().accepted()).isFalse(); - assertThat(unresolved.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); - assertThat(unresolved.commandResult().errorMessage()) + var unresolved = fixture(); + when(unresolved.selections.resolve(unresolved.connection.menu, "demo")) + .thenReturn(Optional.empty()); + var unresolvedResult = + unresolved.receiver.receive( + unresolved.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + assertThat(unresolvedResult.commandResult().accepted()).isFalse(); + assertThat(unresolvedResult.commandResult().errorCode()).isEqualTo("UNAVAILABLE"); + assertThat(unresolvedResult.commandResult().errorMessage()) .isEqualTo("Authenticated gameplay authority unavailable"); - verifyNoInteractions(fixture.lobby); + verifyNoInteractions(unresolved.lobby); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java index 8110b3e24b..14d326ee2a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java @@ -164,21 +164,11 @@ void rejectsMissingCertificateClientAuthEkuAndSpiffeSan() throws Exception { missingCertificate.removeAttribute("jakarta.servlet.request.X509Certificate"); assertRejected(missingCertificate); - var missingClientAuth = - authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); - var nonClientAuthCertificate = - (X509Certificate[]) - missingClientAuth.getAttribute("jakarta.servlet.request.X509Certificate"); - when(nonClientAuthCertificate[0].getExtendedKeyUsage()) - .thenReturn(List.of("1.3.6.1.5.5.7.3.1")); - assertRejected(missingClientAuth); - - var missingSpiffeSan = authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); - var certificateWithNoUriSan = - (X509Certificate[]) - missingSpiffeSan.getAttribute("jakarta.servlet.request.X509Certificate"); - when(certificateWithNoUriSan[0].getSubjectAlternativeNames()).thenReturn(List.of()); - assertRejected(missingSpiffeSan); + assertRejected( + authenticatedRequest( + List.of(List.of(6, "spiffe://firemud/ns/test/sa/spring-cloud-gateway")), + "1.3.6.1.5.5.7.3.1")); + assertRejected(authenticatedRequest(List.of(), "1.3.6.1.5.5.7.3.2")); } private void assertRejected(MockHttpServletRequest request) { @@ -200,12 +190,17 @@ private void assertRejected(MockHttpServletRequest request) { } private static MockHttpServletRequest authenticatedRequest(String peer) throws Exception { + return authenticatedRequest(List.of(List.of(6, peer)), "1.3.6.1.5.5.7.3.2"); + } + + private static MockHttpServletRequest authenticatedRequest( + List> subjectAlternativeNames, String keyUsage) throws Exception { var request = new MockHttpServletRequest("GET", "/ws/game/tcp"); request.setSecure(true); request.setLocalPort(8444); var certificate = mock(X509Certificate.class); - when(certificate.getExtendedKeyUsage()).thenReturn(List.of("1.3.6.1.5.5.7.3.2")); - when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, peer))); + when(certificate.getExtendedKeyUsage()).thenReturn(List.of(keyUsage)); + when(certificate.getSubjectAlternativeNames()).thenReturn(subjectAlternativeNames); request.setAttribute( "jakarta.servlet.request.X509Certificate", new X509Certificate[] {certificate}); request.addHeader("X-Client-IP", "203.0.113.7"); diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java index 5ec051aa53..15dd3ae85f 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java @@ -13,6 +13,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.common.runtime.RuntimeLoggingContext; import net.firedevops.firemud.springcloudgateway.config.GameplayWebSocketBridgeProperties; @@ -130,12 +131,17 @@ public Mono handle(WebSocketSession downstream) { return downstream.close(BACKEND_UNAVAILABLE); } HttpHeaders upstreamHeaders = buildUpstreamHeaders(downstream); - URI upstreamUri = - origin == null ? URI.create(properties.upstreamUrl()) : authenticatedClient.upstream(); - if (origin != null) { + Function> upstreamConnector; + if (origin == null) { + URI upstreamUri = URI.create(properties.upstreamUrl()); + upstreamConnector = + upstreamHandler -> client.execute(upstreamUri, upstreamHeaders, upstreamHandler); + } else { upstreamHeaders.set("X-Client-IP", origin.clientAddress()); upstreamHeaders.set("X-Proxy-Connection-Id", origin.proxyConnectionId().toString()); upstreamHeaders.set(CONNECTION_MODE_HEADER, "trusted_tcp_proxy"); + upstreamConnector = + upstreamHandler -> authenticatedClient.execute(upstreamHeaders, upstreamHandler); } Mono downstreamSend = @@ -157,7 +163,7 @@ public Mono handle(WebSocketSession downstream) { state.outboundToClient.tryEmitComplete(); }); - Mono upstreamLoop = connectWithRetry(downstream, upstreamUri, upstreamHeaders, state, 0); + Mono upstreamLoop = connectWithRetry(downstream, upstreamConnector, state, 0); return Mono.when(downstreamSend, downstreamReceive, upstreamLoop) .then() .doFinally(signal -> activeBridges.remove(state)); @@ -211,8 +217,7 @@ private Mono getOrCreateShutdownCompletion() { private Mono connectWithRetry( WebSocketSession downstream, - URI upstreamUri, - HttpHeaders upstreamHeaders, + Function> upstreamConnector, BridgeState state, int attempt) { if (state.downstreamClosed.get()) { @@ -224,10 +229,7 @@ private Mono connectWithRetry( connected.tryEmitEmpty(); return bridgeUpstreamSession(downstream, upstream, state); }; - Mono sessionLifecycle = - authenticatedClient != null && upstreamUri.equals(authenticatedClient.upstream()) - ? authenticatedClient.execute(upstreamHeaders, upstreamHandler) - : client.execute(upstreamUri, upstreamHeaders, upstreamHandler); + Mono sessionLifecycle = upstreamConnector.apply(upstreamHandler); return Mono.when(connected.asMono().timeout(UPSTREAM_CONNECT_TIMEOUT), sessionLifecycle) .onErrorResume( GameplayBridgeReconnectException.class, @@ -252,9 +254,7 @@ private Mono connectWithRetry( downstream.getId()); } return Mono.delay(Duration.ofMillis(properties.reconnectDelayMs())) - .then( - connectWithRetry( - downstream, upstreamUri, upstreamHeaders, state, attempt + 1)); + .then(connectWithRetry(downstream, upstreamConnector, state, attempt + 1)); }) .onErrorResume( GameplayBridgeTerminalCloseException.class, @@ -265,14 +265,12 @@ private Mono connectWithRetry( return closeDownstream(state, terminal.closeClassification()); }) .onErrorResume( - transportError -> - retryTransportFailure(downstream, upstreamUri, upstreamHeaders, state, attempt)); + transportError -> retryTransportFailure(downstream, upstreamConnector, state, attempt)); } private Mono retryTransportFailure( WebSocketSession downstream, - URI upstreamUri, - HttpHeaders upstreamHeaders, + Function> upstreamConnector, BridgeState state, int attempt) { if (state.downstreamClosed.get()) { @@ -294,7 +292,7 @@ private Mono retryTransportFailure( downstream.getId()); } return Mono.delay(Duration.ofMillis(properties.reconnectDelayMs())) - .then(connectWithRetry(downstream, upstreamUri, upstreamHeaders, state, attempt + 1)); + .then(connectWithRetry(downstream, upstreamConnector, state, attempt + 1)); } private Mono bridgeUpstreamSession( diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java index a54a9ae9db..69886c6afb 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java @@ -156,6 +156,42 @@ void ordinaryUpstreamKeepsItsClientWhenAuthenticatedUpstreamIsConfigured(String verify(authenticated, never()).execute(any(), any()); } + @Test + void ordinaryUpstreamRetryKeepsItsClientWhenUrisMatchAuthenticatedUpstream() { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + AuthenticatedGameplayWebSocketClient authenticated = + mock(AuthenticatedGameplayWebSocketClient.class); + URI upstream = URI.create("wss://game-session-service:8444/ws/game/tcp"); + when(authenticated.upstream()).thenReturn(upstream); + when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) + .thenReturn(Mono.error(new IllegalStateException("connection failed"))); + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + when(downstream.getId()).thenReturn("ordinary-retry-downstream"); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(new HttpHeaders()); + Sinks.Empty closed = Sinks.empty(); + when(downstream.send(any())).thenReturn(Mono.empty()); + when(downstream.receive()).thenReturn(closed.asMono().thenMany(Flux.empty())); + when(downstream.close(any(CloseStatus.class))) + .thenReturn(Mono.fromRunnable(closed::tryEmitEmpty)); + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties(upstream.toString(), 1, 0L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), + GameplayWebSocketObservability.disabled(), + authenticated); + + StepVerifier.create(handler.handle(downstream)).expectComplete().verify(Duration.ofSeconds(5)); + + verify(client, times(2)) + .execute(eq(upstream), any(HttpHeaders.class), any(WebSocketHandler.class)); + verify(authenticated, never()).execute(any(), any()); + verify(downstream).close(new CloseStatus(1013, "backend_unavailable")); + } + @Test void verifiedTcpOriginSelectsAuthenticatedClientAndRelaysOnlyVerifiedOrigin() { ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); From b4ab15dcc509de22bae506404080b559013fdd78 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:17:39 +1300 Subject: [PATCH 16/20] fix(hosted-identity): use canonical bridge probe connection UUIDs --- .../system-architecture-gateway.md | 8 +++--- .../probe/ServedEnvironmentProbe.java | 5 ++-- .../probe/ServedEnvironmentProbeTest.java | 28 ++++++++++++++++--- 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/design/architecture/system-architecture-gateway.md b/design/architecture/system-architecture-gateway.md index bf19580beb..2089f46ef3 100644 --- a/design/architecture/system-architecture-gateway.md +++ b/design/architecture/system-architecture-gateway.md @@ -81,7 +81,7 @@ Spring Cloud Gateway acts as the canonicalizer for client identity and session/t - Derives canonical `X-Client-IP` from `X-Proxy-Client-IP` (and any PROXY-provided metadata) and overwrites any existing `X-Client-IP`. - Generates and forwards only canonical `X-Game-Instance-Id` and `X-Tenant-Id` from the corresponding authenticated proxy inputs where appropriate for gameplay routes; raw `X-Proxy-Game-Instance-Id` and `X-Proxy-Tenant-Id` never reach downstream services. - Accepts the routing bundle only when all three fields are present and valid or all three are absent, rejects a partial or malformed bundle, and forwards the validated advisory `X-World-Slug`, `X-Realm-Slug`, and `X-Pointer-Version` values to Game Session. - - Preserves the authenticated TCP Proxy's `X-Proxy-Connection-Id` value unchanged as the **sole mTLS-bound raw-name correlation exception**: a server-owned opaque Telnet-socket identity for disconnect correlation and observability. Gateway does not generate a replacement identifier or treat it as authorization material. The TCP Proxy's `NotifyDisconnect` event carries this same `proxyConnectionId` with its per-connection `disconnectSequence`; a public or untrusted raw value is never forwarded. + - Preserves the authenticated TCP Proxy's connection UUID unchanged as the **sole mTLS-bound raw-name correlation exception**. The TCP Proxy's `NotifyDisconnect` event carries this same `proxyConnectionId` with its per-connection `disconnectSequence` for lifecycle correlation. - Downstream services must treat `X-Client-IP`, `X-Game-Instance-Id`, `X-Tenant-Id`, `X-World-Slug`, `X-Realm-Slug`, and `X-Pointer-Version` as **gateway-owned or gateway-validated** headers. Services must ignore or overwrite any attempts by callers to spoof these values via gRPC metadata or additional HTTP headers and should rely on their own Redis/session keys and authoritative pointer reads for identity and admission as described in [Authentication & Authorization](./system-architecture-authentication.md) and [Multi-Tenancy](./system-architecture-multi-tenancy.md). - All JWT validation and authorization logic lives in downstream admin and meta services (such as the Logging & Admin Service and Account Service), which must treat Spring Cloud Gateway as a dumb proxy and may not assume it has performed any authentication checks. @@ -96,7 +96,7 @@ Spring Cloud Gateway is the **canonicalization point** for any client-identity a These headers are treated as **untrusted inputs** unless the gateway has authenticated the upstream hop as the TCP Proxy Service: - `X-Proxy-Client-IP` – the Telnet client IP address as observed by the TCP Proxy Service (ideally recovered via PROXY protocol from the Telnet edge proxy in Kubernetes SNAT scenarios). -- `X-Proxy-Connection-Id` – the TCP Proxy's server-generated stable identifier for the Telnet socket. This is the sole mTLS-bound raw-name correlation exception: Gateway preserves this authenticated value unchanged so it remains the `proxyConnectionId` used with the TCP Proxy's `disconnectSequence` to correlate `NotifyDisconnect` events; it is not a Gateway-generated session, scope, or authorization identifier. +- `X-Proxy-Connection-Id` – the TCP Proxy's stable, server-generated Telnet-socket correlation identifier. On certificate-bound gameplay routes Gateway requires the canonical lowercase UUID v4 form with the RFC variant and returns HTTP 403 for invalid values. Gateway preserves the verified value unchanged for disconnect correlation. Backend session and authorization have their own identifiers and checks. - `X-Proxy-Game-Instance-Id` / `X-Proxy-Tenant-Id` – advisory context captured from server-owned proxy defaults or a future explicitly selected transport adapter. These values are never semantic protocol negotiation or gameplay authority. ### Public Ingress Strip/Drop Rules @@ -141,7 +141,7 @@ After applying strip/authentication rules, the gateway sets or forwards the down - `X-Client-IP` – canonical client IP address: - If the upstream hop is authenticated as the TCP Proxy Service and `X-Proxy-Client-IP` is present, set `X-Client-IP` from `X-Proxy-Client-IP`. - Otherwise derive `X-Client-IP` from the trusted load balancer forwarded headers (for example `X-Forwarded-For`) using the gateway’s configured trusted-proxy rules. -- `X-Proxy-Connection-Id` – preserved unchanged only after TCP Proxy authentication as the sole gateway-authenticated, server-owned opaque raw-name correlation field so downstream services can correlate lifecycle signals with the TCP Proxy's `NotifyDisconnect {proxyConnectionId, disconnectSequence}`; the raw inbound header is stripped before this authenticated value is re-added. It is not authentication or session authority. +- `X-Proxy-Connection-Id` – Gateway strips the raw inbound header and re-adds only the verified connection UUID for correlation with `NotifyDisconnect {proxyConnectionId, disconnectSequence}`. - `X-Game-Instance-Id` / `X-Tenant-Id` – downstream game/tenant context generated from authenticated TCP Proxy metadata when the corresponding `X-Proxy-Game-Instance-Id` / `X-Proxy-Tenant-Id` inputs are present. Raw proxy names are stripped and never forwarded. - `X-World-Slug` / `X-Realm-Slug` / `X-Pointer-Version` – one all-or-none routing bundle derived from verified connect-token claims on non-proxy admission or accepted from the authenticated TCP Proxy bridge. A partial, malformed, or non-positive-version bundle is rejected. These values and the game/tenant fields remain advisory admission context; Game Session validates them against current session, entitlement, catalog, and admission-pointer authority. - `X-Firemud-Connect-Context` – for non-proxy `/ws/game/**` handshakes that pass connect-token validation, Gateway emits the signed short-lived envelope whose closed schema, exact protected header, canonical encoding, audience/recipient, source-claim mapping, signed canonical client address, and `first_party_web` abuse classification are defined by [Authentication and authorization](./system-architecture-authentication.md#gateway-to-game-session-connect-context-normative). Gateway validates and carries the Account-produced selected-target snapshot without reinterpretation, independent realm resolution, or rescoping; private/playtest fields remain exact and are distinct from `pointerVersion`. `expiresAt` must not exceed the source token expiry or the 30-second envelope maximum. Gateway alone consumes `connectTokenJti` against the shared replay fence; Game Session does not create a second replay authority and must not expose `connectTokenJti` in client metadata, ordinary logs, metrics, or trace attributes. @@ -506,7 +506,7 @@ If gameplay execution is sharded across multiple Game Session instances, that sh ## TLS Termination for Gateway - **Browser / Web clients** – External `https://` / `wss://` connections terminate at the Internet-facing load balancer. The load balancer forwards `http://` / `ws://` traffic to Spring Cloud Gateway pods in the DMZ. The gateway then routes traffic to backend services using in-cluster `http://` and `ws://` targets (typically on port `8080`), while backend services communicate with each other over mTLS-protected gRPC as described in [Security Architecture](./system-architecture-security.md#tls-termination-for-gateway). -- **Telnet clients** – Telnet (plaintext) or Telnet-over-TLS connections terminate at the TCP Proxy Service. The proxy then connects to the canonical gameplay route `/ws/game/**` on Spring Cloud Gateway by dialing the Gateway’s internal-only WebSocket mTLS listener over `wss://` with mutual TLS. Spring Cloud Gateway forwards gameplay to the Game Session Service over the same WebSocket route (`/ws/game/**`). Detailed certificate and environment variable mappings are documented in [Security Architecture](./system-architecture-security.md#tls-termination-for-gateway) and [Protocol Bridging](./system-architecture-protocol-bridging.md#websocket-bridge-configuration). +- **Telnet clients** – Telnet and Telnet-over-TLS connections terminate at the TCP Proxy Service. The proxy connects to Gateway's internal gameplay listener at `/ws/game/**` over `wss://` with mutual TLS. Gateway forwards verified TCP origins to Game Session's [dedicated `/ws/game/tcp` mTLS receiver](./system-architecture-security.md#authenticated-tcp-gateway-to-game-session-receiving). [Protocol Bridging](./system-architecture-protocol-bridging.md#websocket-bridge-configuration) describes the Proxy-to-Gateway configuration. ## Management Plane Security diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java index a9fb3eb6e4..da3836b682 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java @@ -30,6 +30,7 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; +import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; @@ -776,9 +777,7 @@ private static boolean websocketUpgrade(SSLSocket socket, String hostname, int p byte[] nonceBytes = new byte[16]; WEBSOCKET_NONCE_SOURCE.nextBytes(nonceBytes); String nonce = Base64.getEncoder().encodeToString(nonceBytes); - byte[] connectionIdBytes = new byte[16]; - WEBSOCKET_NONCE_SOURCE.nextBytes(connectionIdBytes); - String connectionId = Base64.getUrlEncoder().withoutPadding().encodeToString(connectionIdBytes); + String connectionId = UUID.randomUUID().toString(); String expectedAccept = websocketAccept(nonce); OutputStream output = socket.getOutputStream(); output.write( diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java index 832187b658..f05eef0094 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java @@ -18,6 +18,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.KeyPairGenerator; import java.security.MessageDigest; @@ -31,6 +32,7 @@ import java.util.Locale; import java.util.Map; import java.util.Set; +import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -564,10 +566,11 @@ void internalBridgeProbeRequiresAWebSocketUpgradeAndSendsTrustedProxyIdentity() String connectionId = requestHeader(fixture.request(), "X-Proxy-Connection-Id"); String nonce = requestHeader(fixture.request(), "Sec-WebSocket-Key"); assertNotNull(connectionId); - assertTrue(connectionId.matches("[A-Za-z0-9_-]{22}")); + assertCanonicalTcpProxyConnectionId(connectionId); + assertEquals(16, Base64.getDecoder().decode(nonce).length); assertFalse( java.util.Arrays.equals( - Base64.getDecoder().decode(nonce), Base64.getUrlDecoder().decode(connectionId))); + Base64.getDecoder().decode(nonce), uuidBytes(UUID.fromString(connectionId)))); } @Test @@ -589,8 +592,11 @@ void successiveInternalBridgeProbesUseDistinctConnectionIds() throws Exception { assertNotNull(firstConnectionId); assertNotNull(secondConnectionId); assertNotEquals(firstConnectionId, secondConnectionId); - assertTrue(firstConnectionId.matches("[A-Za-z0-9_-]{22}")); - assertTrue(secondConnectionId.matches("[A-Za-z0-9_-]{22}")); + assertCanonicalTcpProxyConnectionId(firstConnectionId); + assertCanonicalTcpProxyConnectionId(secondConnectionId); + assertNotEquals( + requestHeader(first.request(), "Sec-WebSocket-Key"), + requestHeader(second.request(), "Sec-WebSocket-Key")); } @Test @@ -838,6 +844,20 @@ private static String requestHeader(String request, String name) { return null; } + private static void assertCanonicalTcpProxyConnectionId(String connectionId) { + UUID parsed = UUID.fromString(connectionId); + assertEquals(parsed.toString(), connectionId); + assertEquals(4, parsed.version()); + assertEquals(2, parsed.variant()); + } + + private static byte[] uuidBytes(UUID uuid) { + return ByteBuffer.allocate(16) + .putLong(uuid.getMostSignificantBits()) + .putLong(uuid.getLeastSignificantBits()) + .array(); + } + private static String websocketAccept(String nonce) throws Exception { byte[] digest = MessageDigest.getInstance("SHA-1") From 26d8a49af0df1beea419021e8424b7ac539b5a74 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:35:42 +1300 Subject: [PATCH 17/20] fix(gateway): defer gameplay retry until backoff elapses --- .../GameplayWebSocketBridgeHandler.java | 6 ++- .../GameplayWebSocketBridgeHandlerTest.java | 51 +++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java index 15dd3ae85f..74feb97d6f 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java @@ -254,7 +254,9 @@ private Mono connectWithRetry( downstream.getId()); } return Mono.delay(Duration.ofMillis(properties.reconnectDelayMs())) - .then(connectWithRetry(downstream, upstreamConnector, state, attempt + 1)); + .flatMap( + ignored -> + connectWithRetry(downstream, upstreamConnector, state, attempt + 1)); }) .onErrorResume( GameplayBridgeTerminalCloseException.class, @@ -292,7 +294,7 @@ private Mono retryTransportFailure( downstream.getId()); } return Mono.delay(Duration.ofMillis(properties.reconnectDelayMs())) - .then(connectWithRetry(downstream, upstreamConnector, state, attempt + 1)); + .flatMap(ignored -> connectWithRetry(downstream, upstreamConnector, state, attempt + 1)); } private Mono bridgeUpstreamSession( diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java index 69886c6afb..6deabf4840 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java @@ -192,6 +192,57 @@ void ordinaryUpstreamRetryKeepsItsClientWhenUrisMatchAuthenticatedUpstream() { verify(downstream).close(new CloseStatus(1013, "backend_unavailable")); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void downstreamClosureDuringReconnectBackoffSkipsNextUpstreamExecution( + boolean failAfterTransportConnect) { + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + WebSocketSession downstream = mock(WebSocketSession.class); + WebSocketSession upstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + Sinks.Empty downstreamClosed = Sinks.empty(); + + when(downstream.getId()).thenReturn("reconnect-backoff-downstream"); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(new HttpHeaders()); + when(downstream.send(any())).thenReturn(Mono.empty()); + when(downstream.receive()) + .thenReturn(downstreamClosed.asMono().thenMany(Flux.empty())); + when(upstream.send(any())).thenReturn(Mono.never()); + when(upstream.receive()).thenReturn(Flux.empty()); + when(upstream.closeStatus()).thenReturn(Mono.empty()); + when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) + .thenAnswer( + invocation -> { + if (!failAfterTransportConnect) { + return Mono.error(new IllegalStateException("connection failed")); + } + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); + + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties( + "ws://game-session-service:8080/ws/game", 1, 1_000L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null)); + + StepVerifier.withVirtualTime(() -> handler.handle(downstream)) + .then( + () -> { + verify(client) + .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + downstreamClosed.tryEmitEmpty(); + }) + .thenAwait(Duration.ofSeconds(2)) + .expectComplete() + .verify(Duration.ofSeconds(5)); + + verify(client).execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + } + @Test void verifiedTcpOriginSelectsAuthenticatedClientAndRelaysOnlyVerifiedOrigin() { ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); From d2cf7bb016a24ed2302f371872f2734b7e49be22 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:56:12 +1300 Subject: [PATCH 18/20] fix(gameplay): enforce verified TCP session identity --- .../system-architecture-security.md | 2 +- .../text/DirectTextWorldSelectionService.java | 24 ++++++++--- ...uthenticatedDirectTextCommandReceiver.java | 4 ++ .../AuthenticatedDirectTextIngress.java | 1 + .../DirectTextWorldMenuRedisStoreTest.java | 3 +- .../DirectTextWorldSelectionServiceTest.java | 43 ++++++++++++++++--- ...nticatedDirectTextCommandReceiverTest.java | 36 ++++++++++++++++ ...sionWebSocketHandshakeInterceptorTest.java | 6 +++ .../HostedIdentityReconcilerSafetyTest.java | 1 + .../GameplayWebSocketBridgeHandler.java | 1 + .../filter/HeaderTrustFilterTest.java | 36 ++++++++++++++++ .../GameplayWebSocketBridgeHandlerTest.java | 2 + 12 files changed, 145 insertions(+), 14 deletions(-) diff --git a/design/architecture/system-architecture-security.md b/design/architecture/system-architecture-security.md index 5e2fc249ef..6688596c1a 100644 --- a/design/architecture/system-architecture-security.md +++ b/design/architecture/system-architecture-security.md @@ -158,7 +158,7 @@ This matrix is the authoritative reference for configuring the Proxy → Gateway The credential-bearing TCP LOGIN/lobby/PLAY receiver is `/ws/game/tcp` on a dedicated internal Game Session TLS connector, separate from the ordinary HTTP port. It requires client certificates and accepts only the exact `spiffe://firemud/ns//sa/spring-cloud-gateway` URI SAN in the receiver's configured namespace, with `clientAuth` usage. Gateway validates the Game Session CA chain, hostname and exact same-namespace `game-session-service` URI SAN before releasing the upgrade request. Game Session reuses its distinct `FIREMUD_GRPC_*` server key, certificate and trust binding. Gateway uses an independently issued client-only workload leaf for this hop, distinct from both its existing management-server bundle and its TCP-Proxy-facing WebSocket server leaf; sharing the legacy generic leaf does not qualify either peer. -Gateway may relay the TCP-origin address and original proxy connection UUID only from its private proof produced after the selected TCP Proxy mTLS trust policy succeeds. Header strings, public ingress, development CIDR trust and network location cannot produce that proof. Game Session validates the relay on the dedicated authenticated connector, allocates a fresh backend generation and binds it to the exact live WebSocket object. Retained UUIDs, numeric transport IDs, menus and SQL witnesses do not reconstruct that custody. +Gateway may relay the TCP-origin address and original proxy connection UUID only from its private proof produced after the selected TCP Proxy mTLS trust policy succeeds. Header strings, public ingress, development CIDR trust and network location cannot produce that proof. Game Session validates the relay on the dedicated authenticated connector, derives the transport session identifier from the verified proxy connection UUID, and refuses an explicit `X-Firemud-Transport-Session-Id` on that hop. It allocates a fresh backend generation and binds it to the exact live WebSocket object. Retained UUIDs, numeric transport IDs, menus and SQL witnesses do not reconstruct that custody. The ordinary HTTP/WebSocket connector is not a supported TCP gameplay fallback. Missing or disabled authenticated Gateway upstream or Game Session listener configuration leaves TCP gameplay unavailable; stripping the trusted TCP connection mode to reach an ordinary receiver cannot supply authenticated custody. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java index d9b75867b6..bd4b016d75 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java @@ -125,16 +125,21 @@ private Optional compose(Instant createdAt, Instant expiresAt) { * * @throws UnknownWorldSelectorException when a nonblank selector does not uniquely match a choice * in a live menu owned by this service + * @throws ExpiredWorldSelectionException when this service's exact menu has expired before the + * resolution begins */ public Optional resolve(SelectionSnapshot retained, String selector) { - if (retained == null - || retained.owner != this - || selector == null - || selector.isBlank() - || !isLive(retained.snapshot)) { + if (retained == null || retained.owner != this || selector == null || selector.isBlank()) { return Optional.empty(); } Snapshot snapshot = retained.snapshot; + Instant now = clock.instant(); + if (now.isBefore(snapshot.createdAt())) { + return Optional.empty(); + } + if (!now.isBefore(snapshot.expiresAt())) { + throw new ExpiredWorldSelectionException(); + } Optional selected = select(snapshot.choices(), selector); if (selected.isEmpty()) { throw new UnknownWorldSelectorException(); @@ -293,6 +298,15 @@ public UnknownWorldSelectorException() { } } + /** The exact selection owner's retained menu expired before resolution began. */ + public static final class ExpiredWorldSelectionException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public ExpiredWorldSelectionException() { + super("World selection menu expired"); + } + } + private record RuntimeWorldIdentity(long tenantId, String worldSlug) {} private record RuntimeTargetIdentity(long tenantId, long gameInstanceId) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 5c951f058c..60d5234f1d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -5,6 +5,7 @@ import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.common.EmailCanonicalization; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.ExpiredWorldSelectionException; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.UnknownWorldSelectorException; import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandInterpretationResult; @@ -114,6 +115,9 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm }; } catch (AuthenticatedDirectTextSessions.LoginRequiredException missingLogin) { return failure("LOGIN_REQUIRED", "Use LOGIN before REALMS or JOIN"); + } catch (ExpiredWorldSelectionException expiredSelection) { + return failure( + "INVALID_ARGUMENT", "World menu expired. Run WORLDS and choose a listed selector again."); } catch (UnknownWorldSelectorException unknownSelector) { return failure( "INVALID_ARGUMENT", diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextIngress.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextIngress.java index 4f5bf49335..4b7929663a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextIngress.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextIngress.java @@ -48,6 +48,7 @@ static AuthenticatedDirectTextIngress authenticate( || address.contains("%") || !address.matches("[0-9a-fA-F:.]+") || !"trusted_tcp_proxy".equals(mode) + || headers.containsHeader("X-Firemud-Transport-Session-Id") || headers.containsHeader("X-Firemud-Connect-Context")) throw unavailable(); String canonicalAddress = java.net.InetAddress.ofLiteral(address).getHostAddress(); var observed = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java index 987d2e10e5..15968f9f4f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java @@ -201,7 +201,8 @@ void expiredRetainedHandleCannotUseTheFreshDiscoveryPath() { clearInvocations(commands, connection, routes); assertThat(localStore.reassert(transport, menu)).isFalse(); - assertThat(localSelection.resolve(menu, "1")).isEmpty(); + assertThatThrownBy(() -> localSelection.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); assertThat(stored.get()).isEqualTo(original); verifyNoInteractions(commands, connection, routes); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java index 8d62a75edd..9177c00339 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java @@ -82,7 +82,12 @@ void historicalEncodingRemainsClockIndependentWhileRestorationAndResolutionRefus assertThat(foreignOwner.encodeSnapshot(menu)).isEmpty(); assertThat(source.encodeSnapshot(null)).isEmpty(); assertThat(source.restoreSnapshot(original)).isEmpty(); - assertThat(source.resolve(menu, "1")).isEmpty(); + if (expired) { + assertThatThrownBy(() -> source.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); + } else { + assertThat(source.resolve(menu, "1")).isEmpty(); + } assertThat(reads.get()).isEqualTo(2); verifyNoInteractions(reader); } @@ -120,7 +125,8 @@ void restoresAcrossInstancesWithOriginalOrderOwnershipAndDeadline() { clearInvocations(reader); clock.now = NOW.plusSeconds(300); assertThat(replacement.restoreSnapshot(stored)).isEmpty(); - assertThat(replacement.resolve(restored, "1")).isEmpty(); + assertThatThrownBy(() -> replacement.resolve(restored, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); verifyNoInteractions(reader); } @@ -479,8 +485,10 @@ void retainedOrdinalCannotBeSilentlyUpgradedToANewCatalogRevision() { assertThat(service.resolve(refreshed, "1")).containsSame(revised); clock.now = NOW.plusSeconds(300); clearInvocations(reader); - assertThat(service.resolve(oldMenu, "1")).isEmpty(); - assertThat(service.resolve(refreshed, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(oldMenu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); + assertThatThrownBy(() -> service.resolve(refreshed, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); verifyNoInteractions(reader); } @@ -555,13 +563,34 @@ void expiryIsExclusiveAtFiveMinutesAndExpiredSelectionsHaveNoSourceEffects() { int before = catalogReads.get(); clock.now = NOW.plusSeconds(300); - assertThat(service.resolve(menu, "1")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); clock.now = NOW.plusSeconds(301); - assertThat(service.resolve(menu, "studio/forest")).isEmpty(); + assertThatThrownBy(() -> service.resolve(menu, "studio/forest")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); assertThat(catalogReads.get()).isEqualTo(before); verifyNoInteractions(reader); } + @Test + void expiryOutcomeRequiresTheExactOwnerAndDoesNotClassifyFutureMenusAsExpired() { + var first = target(""); + var catalog = GameplayWorldCatalog.forWorldViews(List.of(world(first))); + var service = service(catalog, List.of(first)); + var menu = service.browse().orElseThrow(); + var foreignOwner = service(catalog, List.of(first)); + clearInvocations(reader); + + clock.now = menu.expiresAt(); + assertThatThrownBy(() -> service.resolve(menu, "1")) + .isInstanceOf(DirectTextWorldSelectionService.ExpiredWorldSelectionException.class); + assertThat(foreignOwner.resolve(menu, "1")).isEmpty(); + + clock.now = NOW.minusNanos(1); + assertThat(service.resolve(menu, "1")).isEmpty(); + verifyNoInteractions(reader); + } + @Test void expiryIsRecheckedAfterCanonicalAndCatalogReads() { var first = target(""); @@ -583,9 +612,9 @@ void expiryIsRecheckedAfterCanonicalAndCatalogReads() { }); assertThat(service.resolve(menu, "1")).isEmpty(); - clock.now = NOW; when(reader.readCurrentTarget(first)).thenReturn(first); onCatalogRead.set(() -> clock.now = NOW.plusSeconds(300)); + clock.now = NOW; assertThat(service.resolve(menu, "1")).isEmpty(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index d2c90ed861..a07611335c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -16,6 +16,7 @@ import java.util.stream.Stream; import net.firedevops.firemud.account.v1.JoinPublicProductionMembershipResponse; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService; +import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.ExpiredWorldSelectionException; import net.firedevops.firemud.gamesession.command.text.DirectTextWorldSelectionService.UnknownWorldSelectorException; import net.firedevops.firemud.gamesession.command.text.TextCommand; import net.firedevops.firemud.gamesession.command.text.TextCommandPayload; @@ -139,6 +140,41 @@ void unknownJoinSelectorReturnsActionableInvalidArgumentBeforeLobbyDispatch() { verifyNoInteractions(fixture.lobby); } + @Test + void expiredRealmMenuReturnsActionableInvalidArgumentAfterTheGuardedLobbyCall() { + var fixture = fixture(); + when(fixture.lobby.realms(null, null, fixture.connection, fixture.connection.menu, "demo")) + .thenThrow(new ExpiredWorldSelectionException()); + + var result = + fixture.receiver.receive( + fixture.socket, + new TextCommand(TextCommandType.REALMS, List.of("demo"), "REALMS demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("World menu expired. Run WORLDS and choose a listed selector again."); + verify(fixture.lobby).realms(null, null, fixture.connection, fixture.connection.menu, "demo"); + } + + @Test + void expiredJoinMenuReturnsActionableInvalidArgumentBeforeLobbyDispatch() { + var fixture = fixture(); + when(fixture.selections.resolve(fixture.connection.menu, "demo")) + .thenThrow(new ExpiredWorldSelectionException()); + + var result = + fixture.receiver.receive( + fixture.socket, new TextCommand(TextCommandType.JOIN, List.of("demo"), "JOIN demo")); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(result.commandResult().errorMessage()) + .isEqualTo("World menu expired. Run WORLDS and choose a listed selector again."); + verifyNoInteractions(fixture.lobby); + } + @Test void refusedJoinReportsTheExactInvalidArgumentOrUnavailableError() { var fixture = fixture(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java index 14d326ee2a..c7ee9d146b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java @@ -112,6 +112,7 @@ void preservesCanonicalProxyConnectionIdOnlyForAuthenticatedGatewayOnDedicatedLi assertThat(observed.proxyConnectionId()).isEqualTo(UUID.fromString(proxyConnectionId)); assertThat(observed.transportSessionId()) .isEqualTo(attributes.get(GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR)); + assertThat(observed.transportSessionId()).matches("\\d+"); assertThat(observed.transportSessionId()).isNotEqualTo(proxyConnectionId); } @@ -155,6 +156,11 @@ void rejectsSpoofedHeadersWrongWorkloadsNamespacesAndPublicListener() throws Exc var duplicateMode = authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); duplicateMode.addHeader("X-Firemud-Connection-Mode", "first_party_web"); assertRejected(duplicateMode); + var transportOverride = + authenticatedRequest("spiffe://firemud/ns/test/sa/spring-cloud-gateway"); + transportOverride.addHeader( + GameSessionWebSocketHandshakeInterceptor.TRANSPORT_SESSION_HEADER, "999999"); + assertRejected(transportOverride); } @Test diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java index 7536dba3cc..85ccd905a5 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java @@ -1995,6 +1995,7 @@ private static boolean crdSchemaAccepts(Map propertySchema, Object value) assertEquals(consumerSchema, statusProperties.get("grpcAccountService")); assertEquals(consumerSchema, statusProperties.get("grpcGameSessionService")); assertEquals(consumerSchema, statusProperties.get("grpcSocialGroupsService")); + assertEquals(consumerSchema, statusProperties.get("grpcGatewayClient")); assertEquals( consumerSchema, publicationSchema.get("additionalProperties"), diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java index 74feb97d6f..e8039befa3 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java @@ -137,6 +137,7 @@ public Mono handle(WebSocketSession downstream) { upstreamConnector = upstreamHandler -> client.execute(upstreamUri, upstreamHeaders, upstreamHandler); } else { + upstreamHeaders.remove(TRANSPORT_SESSION_HEADER); upstreamHeaders.set("X-Client-IP", origin.clientAddress()); upstreamHeaders.set("X-Proxy-Connection-Id", origin.proxyConnectionId().toString()); upstreamHeaders.set(CONNECTION_MODE_HEADER, "trusted_tcp_proxy"); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java index 817b89cb2a..198499fe11 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilterTest.java @@ -434,6 +434,42 @@ void rejectsAuthenticatedSessionWhenProxyClientIpIsMissingOrMalformed() throws E } } + @Test + void rejectsNonCanonicalProxyConnectionIdsOnAuthenticatedListener() throws Exception { + GatewayHeaderTrustProperties headerProperties = new GatewayHeaderTrustProperties(); + GatewayTcpProxyListenerProperties listenerProperties = certificateListenerProperties(); + TcpProxyTrustPolicy policy = + new TcpProxyTrustPolicy( + listenerProperties, + headerProperties, + 8080, + TCP_PROXY_CERTIFICATE_CLOCK, + Set.of("test")); + HeaderTrustFilter filter = new HeaderTrustFilter(headerProperties, policy); + SslInfo authenticatedPeer = authenticatedTcpProxyPeer(); + + for (String connectionId : + new String[] { + null, + "opaque", + "9FB38C88-2F1D-42AA-8E0B-7EB69CAF8814", + "9fb38c88-2f1d-12aa-8e0b-7eb69caf8814", + "9fb38c88-2f1d-42aa-ce0b-7eb69caf8814" + }) { + MockServerHttpRequest.BaseBuilder requestBuilder = + MockServerHttpRequest.get("/ws/game/test") + .localAddress(new InetSocketAddress("127.0.0.1", 8443)) + .remoteAddress(new InetSocketAddress("127.0.0.1", 50000)) + .sslInfo(authenticatedPeer) + .header("X-Proxy-Client-IP", "203.0.113.99"); + if (connectionId != null) { + requestBuilder.header("X-Proxy-Connection-Id", connectionId); + } + MockServerWebExchange exchange = MockServerWebExchange.from(requestBuilder.build()); + assertForbiddenWithoutDelegation(filter, exchange, "connectionId=" + connectionId); + } + } + @Test void rejectsLegacyTrustedProxyWhenProxyClientIpIsMissingOrMalformed() { GatewayHeaderTrustProperties properties = new GatewayHeaderTrustProperties(); diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java index 6deabf4840..858cad7740 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java @@ -264,6 +264,7 @@ void verifiedTcpOriginSelectsAuthenticatedClientAndRelaysOnlyVerifiedOrigin() { HttpHeaders headers = new HttpHeaders(); headers.set("X-Client-IP", "unverified"); headers.set("X-Proxy-Connection-Id", "unverified"); + headers.set("X-Firemud-Transport-Session-Id", "9001"); when(handshake.getHeaders()).thenReturn(headers); when(downstream.send(any())).thenReturn(Mono.never()); when(downstream.receive()).thenReturn(Flux.never()); @@ -288,6 +289,7 @@ void verifiedTcpOriginSelectsAuthenticatedClientAndRelaysOnlyVerifiedOrigin() { .isEqualTo(connectionId.toString()); assertThat(forwarded.getValue().getFirst("X-Firemud-Connection-Mode")) .isEqualTo("trusted_tcp_proxy"); + assertThat(forwarded.getValue().getFirst("X-Firemud-Transport-Session-Id")).isNull(); } @Test From e53f5a67db70fb42bd07f9832b1d94d97b210a28 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:20:47 +1300 Subject: [PATCH 19/20] Bound authenticated TCP rejection closes in Gateway --- .../GameplayWebSocketBridgeHandler.java | 8 +-- .../GameplayWebSocketObservability.java | 9 +++ .../GameplayWebSocketBridgeHandlerTest.java | 57 +++++++++++++++++++ 3 files changed, 70 insertions(+), 4 deletions(-) diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java index e8039befa3..569d8fbd30 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java @@ -118,17 +118,17 @@ public Mono handle(WebSocketSession downstream) { .equals(downstream.getHandshakeInfo().getHeaders().getFirst(CONNECTION_MODE_HEADER)) && origin == null && authenticatedClient != null) { - activeBridges.remove(state); - return downstream.close(new CloseStatus(1008, "authenticated_tcp_origin_required")); + return closeDownstream(state, gameplayWebSocketObservability.authenticatedTcpOriginRequired()) + .doFinally(signal -> activeBridges.remove(state)); } if (origin != null && authenticatedClient == null) { - activeBridges.remove(state); // This configuration cannot change during the handler's lifetime; do not log every retry. if (missingAuthenticatedClientWarningLogged.compareAndSet(false, true)) { LOG.warn( "Verified TCP Proxy gameplay origin rejected: no authenticated gameplay upstream client is configured; set firemud.gateway.gameplay.bridge.authenticated-upstream-url (logged once per handler)"); } - return downstream.close(BACKEND_UNAVAILABLE); + return closeDownstream(state, gameplayWebSocketObservability.classify(BACKEND_UNAVAILABLE)) + .doFinally(signal -> activeBridges.remove(state)); } HttpHeaders upstreamHeaders = buildUpstreamHeaders(downstream); Function> upstreamConnector; diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java index 501c6e7bb6..7361fc734d 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketObservability.java @@ -100,6 +100,15 @@ public CloseClassification classify(CloseStatus upstreamStatus) { }; } + CloseClassification authenticatedTcpOriginRequired() { + return new CloseClassification( + new CloseStatus(1008, "authenticated_tcp_origin_required"), + POLICY_VIOLATION, + NO_SUBREASON, + false, + UNATTRIBUTED_FAILURE); + } + public CloseClassification slowClientClose() { return close(POLICY_VIOLATION, EDGE_BACKPRESSURE, true, UNATTRIBUTED_FAILURE); } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java index 858cad7740..a64b873ac1 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java @@ -17,6 +17,7 @@ import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.runtime.RuntimeIdentity; @@ -342,6 +343,62 @@ void missingAuthenticatedClientWarnsOnceWithoutConnectionDetailsAndKeepsFailClos "private-downstream-session"); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void rejectedTcpOriginCloseIsBoundedAndRecorded(boolean verifiedOrigin) { + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + ReactorNettyWebSocketClient client = mock(ReactorNettyWebSocketClient.class); + AuthenticatedGameplayWebSocketClient authenticated = + mock(AuthenticatedGameplayWebSocketClient.class); + WebSocketSession downstream = mock(WebSocketSession.class); + HandshakeInfo handshake = mock(HandshakeInfo.class); + HttpHeaders headers = new HttpHeaders(); + headers.set("X-Firemud-Connection-Mode", "trusted_tcp_proxy"); + Map attributes = + verifiedOrigin + ? Map.of(VerifiedTcpProxyOrigin.class.getName(), mock(VerifiedTcpProxyOrigin.class)) + : Map.of(); + when(downstream.getId()).thenReturn("tcp-downstream"); + when(downstream.getAttributes()).thenReturn(attributes); + when(downstream.getHandshakeInfo()).thenReturn(handshake); + when(handshake.getHeaders()).thenReturn(headers); + when(downstream.close(any(CloseStatus.class))).thenReturn(Mono.never()); + + GameplayWebSocketBridgeHandler handler = + new GameplayWebSocketBridgeHandler( + client, + new GameplayWebSocketBridgeProperties( + "ws://game-session-service:8080/ws/game", 1, 50L, 128), + new RuntimeIdentity( + "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null), + new GameplayWebSocketObservability(meterRegistry), + verifiedOrigin ? null : authenticated); + + StepVerifier.withVirtualTime(() -> handler.handle(downstream)) + .thenAwait(Duration.ofSeconds(2)) + .expectError(TimeoutException.class) + .verify(Duration.ofSeconds(5)); + + CloseStatus expected = + verifiedOrigin + ? new CloseStatus(1013, "backend_unavailable") + : new CloseStatus(1008, "authenticated_tcp_origin_required"); + verify(downstream).close(expected); + verify(client, never()) + .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + verify(authenticated, never()).execute(any(), any()); + assertThat( + meterRegistry + .get("gateway.websocket.closes") + .tags( + "reason", verifiedOrigin ? "backend_unavailable" : "policy_violation", + "subreason", "none", + "bridge_shutdown_class", "unattributed_failure") + .counter() + .count()) + .isEqualTo(1.0); + } + @Test void actualLocalShutdownClosesEstablishedBridgeWithPlannedDrain() { SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); From bf6935020a9936738b0f5b5650f4a2ba209130aa Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:34:09 +1300 Subject: [PATCH 20/20] Handle blank gameplay upstream and prove custody and preview guards --- .../test_validate_preview_artifact.py | 28 ++++++++++ .../AuthenticatedDirectTextSessionsTest.java | 47 ++++++++++++++++ .../config/GameplayWebSocketBridgeConfig.java | 20 +++++-- .../GameplayWebSocketBridgeConfigTest.java | 53 +++++++++++++++++++ 4 files changed, 144 insertions(+), 4 deletions(-) diff --git a/dev-tools/validation/test_validate_preview_artifact.py b/dev-tools/validation/test_validate_preview_artifact.py index 5c4d3fc272..873cbac3d9 100644 --- a/dev-tools/validation/test_validate_preview_artifact.py +++ b/dev-tools/validation/test_validate_preview_artifact.py @@ -2661,6 +2661,34 @@ def test_gateway_exact_environment_contract_is_accepted(self): [self._gateway_document()], "pr-42" ) + def test_gateway_rejects_unsafe_gameplay_mount(self): + for option, value in (("readOnly", False), ("subPath", "tls.key")): + with self.subTest(option=option): + document = self._gateway_document() + mounts = document["spec"]["template"]["spec"]["containers"][0]["volumeMounts"] + gameplay_mount = next( + mount for mount in mounts if mount["name"] == "gameplay-client-tls" + ) + gameplay_mount[option] = value + with ( + patch.object(self.validator, "SERVICE_IMAGES", {"spring-cloud-gateway"}), + self.assertRaisesRegex(ValueError, "unsafe gameplay-client-tls mount"), + ): + self.validator.validate_service_consumers([document], "pr-42") + + def test_gateway_rejects_extra_gameplay_client_tls_item(self): + document = self._gateway_document() + volumes = document["spec"]["template"]["spec"]["volumes"] + gameplay_volume = next( + volume for volume in volumes if volume["name"] == "gameplay-client-tls" + ) + gameplay_volume["secret"]["items"].append({"key": "ca.crt", "path": "ca.crt"}) + with ( + patch.object(self.validator, "SERVICE_IMAGES", {"spring-cloud-gateway"}), + self.assertRaisesRegex(ValueError, "unsafe grpc-tls projection"), + ): + self.validator.validate_service_consumers([document], "pr-42") + def test_gateway_rejects_redirect_and_jvm_environment_injection(self): for injected in ( { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java index 28fae900fb..f5601452a6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java @@ -178,6 +178,53 @@ void exactConnectionOwnsIdenticalPrivateResultOnlyInsideBorrow() throws Exceptio assertThatThrownBy(() -> sessions.require(socket)).isInstanceOf(IllegalStateException.class); } + @Test + void selectionFailuresPropagateThroughCustodyWithoutDiscardingExactLogin() throws Exception { + var socket = socket(); + sessions.open(socket); + var fixture = fixture(); + var connection = sessions.require(socket); + connection.login(fixture.owner(), "player@example.test", "secret".toCharArray()); + + var unknown = new DirectTextWorldSelectionService.UnknownWorldSelectorException(); + assertThatThrownBy( + () -> + connection.withLogin( + (original, result) -> + connection.withCurrent( + original, + result, + transport -> { + throw unknown; + }))) + .isSameAs(unknown); + + var expired = new DirectTextWorldSelectionService.ExpiredWorldSelectionException(); + assertThatThrownBy( + () -> + connection.withLogin( + (original, result) -> + connection.withCurrent( + original, + result, + transport -> { + throw expired; + }))) + .isSameAs(expired); + + assertThat( + connection.withLogin( + (original, result) -> { + assertThat(result).isSameAs(fixture.result()); + return connection.withCurrent( + original, result, transport -> transport.transportSessionId().equals("42")); + })) + .isTrue(); + + sessions.close(socket, CloseStatus.NORMAL); + verify(fixture.cleanup()).abandonAndRetire(fixture.original()); + } + @Test void disconnectRevokesBeforeDrainingAndCleansOnlyAfterBorrowReturns() throws Exception { var socket = socket(); diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfig.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfig.java index e57576b41a..3b33943730 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfig.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfig.java @@ -12,10 +12,14 @@ import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Condition; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; +import org.springframework.core.type.AnnotatedTypeMetadata; +import org.springframework.util.StringUtils; import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; @@ -26,6 +30,8 @@ @Configuration public class GameplayWebSocketBridgeConfig { + private static final String AUTHENTICATED_UPSTREAM_URL_PROPERTY = + "firemud.gateway.gameplay.bridge.authenticated-upstream-url"; @Bean @Primary @@ -53,9 +59,7 @@ GameplayWebSocketBridgeHandler gameplayWebSocketBridgeHandler( } @Bean(initMethod = "initialize", destroyMethod = "close") - @ConditionalOnProperty( - prefix = "firemud.gateway.gameplay.bridge", - name = "authenticated-upstream-url") + @Conditional(AuthenticatedUpstreamConfigured.class) AuthenticatedGameplayWebSocketClient authenticatedGameplayWebSocketClient( @Value("${firemud.grpc.workload-namespace:}") String namespace, @Value("${firemud.gateway.gameplay.bridge.authenticated-upstream-url}") String upstream, @@ -95,4 +99,12 @@ HandlerMapping gameplayWebSocketBridgeMapping( WebSocketHandlerAdapter gameplayWebSocketHandlerAdapter() { return new WebSocketHandlerAdapter(); } + + static final class AuthenticatedUpstreamConfigured implements Condition { + @Override + public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { + String upstream = context.getEnvironment().getProperty(AUTHENTICATED_UPSTREAM_URL_PROPERTY); + return StringUtils.hasText(upstream) && !"false".equalsIgnoreCase(upstream.trim()); + } + } } diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java index 9d9ebca787..91ff0d08db 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java @@ -11,12 +11,15 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.io.InputStream; import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.time.Clock; import java.time.Instant; import java.time.ZoneOffset; import java.util.HashMap; +import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; @@ -24,13 +27,16 @@ import net.firedevops.firemud.springcloudgateway.filter.HeaderTrustFilter; import net.firedevops.firemud.springcloudgateway.filter.TcpProxyTrustPolicy; import net.firedevops.firemud.springcloudgateway.filter.VerifiedTcpProxyOrigin; +import net.firedevops.firemud.springcloudgateway.websocket.AuthenticatedGameplayWebSocketClient; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketBridgeHandler; import net.firedevops.firemud.springcloudgateway.websocket.GameplayWebSocketObservability; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.MockedConstruction; import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.MapPropertySource; import org.springframework.http.server.reactive.SslInfo; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; @@ -71,6 +77,53 @@ void gameplayWebSocketPathIsOwnedByGatewayCode() { }); } + @Test + void authenticatedGameplayClientIsOmittedForUnsetBlankOrExplicitFalseEndpoint() { + contextRunner.run( + context -> assertThat(context).doesNotHaveBean(AuthenticatedGameplayWebSocketClient.class)); + + for (String endpoint : new String[] {"", " \t ", "false"}) { + contextRunner + .withInitializer( + applicationContext -> + applicationContext + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "test-authenticated-upstream", + Map.of( + "firemud.gateway.gameplay.bridge.authenticated-upstream-url", + endpoint)))) + .run( + context -> + assertThat(context) + .as("endpoint=%s", endpoint) + .doesNotHaveBean(AuthenticatedGameplayWebSocketClient.class)); + } + } + + @Test + void malformedNonblankAuthenticatedEndpointFailsFast(@TempDir Path dir) throws Exception { + Path certificate = Files.createFile(dir.resolve("client.pem")); + Path privateKey = Files.createFile(dir.resolve("client.key")); + Path caCertificate = Files.createFile(dir.resolve("ca.pem")); + + contextRunner + .withPropertyValues( + "firemud.grpc.workload-namespace=test", + "firemud.gateway.gameplay.bridge.authenticated-upstream-url=http://game-session:8444/ws/game/tcp", + "firemud.gateway.gameplay.bridge.tls.cert-chain=" + certificate, + "firemud.gateway.gameplay.bridge.tls.private-key=" + privateKey, + "firemud.gateway.gameplay.bridge.tls.ca-cert=" + caCertificate) + .run( + context -> + assertThat(context) + .hasFailed() + .getFailure() + .hasRootCauseMessage("Dedicated authenticated gameplay wss endpoint required")); + } + @Test void gameplayWebSocketMappingUsesPathPatternSemanticsForMatrixParameters() { contextRunner.run(